/* Copyright (c) 2006-2009, Apple Inc. All rights reserved. */
/* Compressed JavaScript. Do not modify. */


/* widgets_core.js */

var requiredUIRevision='WikiServerUI-189';function prepare(inAlwaysRun){if(window.unitTestHandler&&(!inAlwaysRun))return true;if(window.opera&&gPrepareIteration++>0)return true;try{publisher().publish('awakeFromPage',d);publisher().publish('PAGE_INITIALIZE_FINISHED',d);}
catch(e){reportError(e);}}
function reportErrorInDebugMode(e,optRealErrorObj){if(gDebug)
{return reportError(e,optRealErrorObj);}
else
{return false;}}
function reportError(e,optRealErrorObj){if(window.gLastErrorObj&&(e==gLastErrorObj||optRealErrorObj==gLastErrorObj))return;gLastErrorObj=e;if(window.parent&&window.parent.AppleUnitTester){if(window.parent.AppleUnitTester.sharedTester().mIsLoadingPage&&e.getAllResponseHeaders){return false;}
else{window.parent.AppleUnitTester.sharedTester().reportError(e);}}
else if(gDebug){debugger;var errorString='unknown';try{if(e.request&&e.status&&e.request.url&&e.getAllResponseHeaders){debug_message('Request returned error:');debug_message(e.request.method.toUpperCase()+' '+e.request.url);if(e.request.options&&e.request.options.requestHeaders)$H(e.request.options.requestHeaders).each(function(hdr){debug_message(hdr.key+': '+hdr.value);});if(e.request.options&&e.request.options.postBody)debug_message(e.request.options.postBody);debug_message('--- RESPONSE: '+e.status+' ---');debug_message(e.getAllResponseHeaders());if(e.responseText)debug_message(e.responseText);errorString='Server returned an error: '+e.status+'. Check the console for detailed request/response logs.';}
else{errorString=(Object.isString(e)?e:$H(optRealErrorObj||e).inspect());}}
catch(e2){try{errorString=e.toString();}
catch(e3){}}
alert('Error: '+errorString);throw e;return false;}
throw e;}
function debug_message(inString){if(window.gDebug&&window.console){window.console.log(inString);}}
Class.createWithSharedInstance=function(inOptInstanceShortcutName,inOptInstantiateOnAwakeFromPage){var cls=null;cls=function(){var result=this.initialize.apply(this,arguments);if(result==invalidate){var timeoutCallback=function(){try{if(this&&this['_parentClass']&&this['_parentClass']['_sharedInstance']==this){var cp=this;this['_parentClass']['_sharedInstance']=null;}}
catch(e){if(window.reportError)reportError(e);else throw e;}}
setTimeout(timeoutCallback.bind(this),200);}}
cls.autocreate=inOptInstantiateOnAwakeFromPage;cls.sharedInstance=function(){if(!cls['_sharedInstance']){cls['_sharedInstance']=new cls();cls['_sharedInstance']['_parentClass']=cls;}
return cls['_sharedInstance'];}
if(inOptInstanceShortcutName)window[inOptInstanceShortcutName]=cls.sharedInstance;if(inOptInstantiateOnAwakeFromPage){publisher().subscribe(function(){if(cls.autocreate)cls.sharedInstance();},'awakeFromPage');}
return cls;}
var NotificationPublisher=Class.createWithSharedInstance('publisher');NotificationPublisher.prototype={initialize:function(){this.mSubcribers=[];},publish:function(inMessage,inObject,inUserInfo){var subscriberDidRespond=false;for(var subscriberIdx=0;subscriberIdx<this.mSubcribers.length;subscriberIdx++){var subscriber=this.mSubcribers[subscriberIdx];var m=subscriber.message||inMessage;var o=subscriber.obj||inObject;if(m==inMessage&&o==inObject){subscriber.callback(inMessage,inObject,inUserInfo);subscriberDidRespond=true;}}
if(window.parent&&window.parent.AppleUnitTester){window.parent.AppleUnitTester.sharedTester().publishMessage(inMessage);}
return subscriberDidRespond;},subscribe:function(inCallback,inMessage,inObject){this.mSubcribers.push({callback:inCallback,message:inMessage,obj:inObject});},unsubscribe:function(inCallback,inMessage,inObject){this.mSubcribers=this.mSubcribers.reject(function(subscriber){return(subscriber.callback==inCallback&&subscriber.message==inMessage&&subscriber.obj==inObject);});}}
function invalidate(){return false;}
function getMetaTagValue(inTagName){var matchingTag=$A(d.getElementsByTagName('META')).detect(function(tag){return(tag.name==inTagName);});return(matchingTag?matchingTag.content:null);}
function padNumberStr(theNumber,digits){var padder=((arguments.length>2)?arguments[2]:'0');var theString="";theString+=theNumber;for(var i=0;i<(digits-theString.length);i++){theString=padder+theString;}
return theString;}
function createDateObjFromISO8601(inISOString,inOptIsGMT){if(!inISOString)return null;var str=inISOString.match(/[Tt]/)?inISOString:inISOString+'T000000Z';var d=str.match(/(\d{4})-?(\d{2})-?(\d{2})\s*[Tt]?(\d{2}):?(\d{2}):?(\d{2})/);if(!d)return null;var dt=new Date(d[1],d[2]-1,d[3],d[4],d[5],d[6]);if(inOptIsGMT)dt.setHours(dt.getHours()-(dt.getTimezoneOffset()/60));return dt;}
function dateObjToISO8601(inDateObj,inOptMakeGMT,inIncludeZ){if(!inDateObj)return null;var includeZ=(arguments.length>2?inIncludeZ:true);var dt=new Date(inDateObj.getTime());if(inOptMakeGMT)dt.setHours(dt.getHours()-(dt.getTimezoneOffset()/(-60)));var iso_string='';iso_string+=dt.getFullYear()
+padNumberStr(dt.getMonth()+1,2)
+padNumberStr(dt.getDate(),2)
+'T'
+padNumberStr(dt.getHours(),2)
+padNumberStr(dt.getMinutes(),2)
+padNumberStr(dt.getSeconds(),2)
+(includeZ?'Z':'');return iso_string;}
function getEndDateUsingDuration(inDate,inDuration){var dt=new Date(inDate.getTime());if(inDuration.days)dt.setDate(dt.getDate()+inDuration.days);if(inDuration.hours)dt.setHours(dt.getHours()+inDuration.hours);if(inDuration.minutes)dt.setMinutes(dt.getMinutes()+inDuration.minutes);if(inDuration.seconds)dt.setMinutes(dt.getSeconds()+inDuration.seconds);return dt;}
function getDurationUsingEndDate(inStartDate,inEndDate){var time=Math.floor((inEndDate.getTime()-inStartDate.getTime())/1000);var whole=(time<0?Math.ceil:Math.floor);var duration={days:whole(time/86400)};time=time%86400;duration.hours=whole(time/3600);time=time%3600;duration.minutes=whole(time/60);duration.seconds=time%60;return duration;}
function durationFromISO8601(inISOString){if(!inISOString)return null;var dt=inISOString.match(/^P([^T]*)T?(.*)$/);if(!dt)return null;var duration=new Object();['years','months','days','hours','minutes','seconds'].each(function(key,i){var mat=dt[Math.floor(i/3)+1].match("([0-9]+)"+key.charAt(0).toUpperCase());duration[key]=mat?parseInt(mat[1]):0;});return duration;}
function durationToISO8601(inDuration){var str='P';if(inDuration.years&&inDuration.years>0)str+=inDuration.years+'Y';if(inDuration.months&&inDuration.months>0)str+=inDuration.months+'M';if(inDuration.days&&inDuration.days>0)str+=inDuration.days+'D';str+='T';if(inDuration.hours&&inDuration.hours>0)str+=inDuration.hours+'H';if(inDuration.minutes&&inDuration.minutes>0)str+=inDuration.minutes+'M';if(inDuration.seconds&&inDuration.seconds>0)str+=inDuration.seconds+'S';return str;}
function compareDateWeeks(inDate1,inDate2,inOptStartWeekday){var dates=new Array();var startWeekday=inOptStartWeekday||0;for(i=0;i<2;i++){var date=new Date(arguments[i].getTime());if(date.getDay()<startWeekday){date.setDate(date.getDate()-7);}
date.setDate(date.getDate()-(date.getDay()-startWeekday));dates.push(date);}
return(parseInt(dateObjToISO8601(dates[0],false,false))==parseInt(dateObjToISO8601(dates[1],false,false)));}
function fixSiteRelativeURLForIE(inURLString){if(!document.all||inURLString.indexOf('/')!=0)return inURLString;return window.location.protocol+'//'+window.location.host+inURLString;}
var IEFixes={isIE:(document.all&&!(/Opera/.test(navigator.userAgent))?true:false),isIE7:document.all&&/MSIE 7/.test(navigator.userAgent),isIE6:document.all&&/MSIE 6/.test(navigator.userAgent)}
if(IEFixes.isIE6){try{document.execCommand("BackgroundImageCache",false,true);}catch(err){}}
var SafariFixes={isMobileSafari:/ AppleWebKit\/.+Mobile\//.test(navigator.userAgent),isWebKit:/WebKit/.test(navigator.userAgent),isTigerSafari:(/WebKit\/\d+/.test(navigator.userAgent)&&(parseInt(navigator.userAgent.match(/WebKit\/(\d+)/)[1])<420))}
var MozillaFixes={isGecko:/Gecko\/\d*/.test(navigator.userAgent),isGecko1_9:/Gecko\/\d*/.test(navigator.userAgent)&&/rv:1.9/.test(navigator.userAgent),isCamino:/Gecko\/\d*.+Camino\/\d*/.test(navigator.userAgent)}
var OperaFixes={isOpera:/Opera/.test(navigator.userAgent)}
function bindEventListeners(inParentObj,inFnNameArray){inFnNameArray.each(function(f){inParentObj[f]=inParentObj[f].bindAsEventListener(inParentObj);});}
function observeEvents(inParentObj,inElement,inFnNameArray,inOptStopObserving){var elm=$(inElement);$H(inFnNameArray).each(function(handler){if(inOptStopObserving)Event.stopObserving(elm,handler.key,inParentObj[handler.value]);else Event.observe(elm,handler.key,inParentObj[handler.value]);});}
function stopObservingEvents(inParentObj,inElement,inFnNameArray){observeEvents(inParentObj,inElement,inFnNameArray,true);}
function removeAllChildNodes(inParent){inParent=$(inParent);while(inParent.childNodes.length>0){inParent.removeChild(inParent.firstChild);}}
function replaceElementContents(inElement,inStringOrObj,inEvaluate){var elm=$(inElement);if(typeof inStringOrObj=='string'&&inEvaluate){elm.innerHTML=inStringOrObj;}
else{removeAllChildNodes(elm);if(typeof inStringOrObj=='string'){elm.appendChild(elm.ownerDocument.createTextNode(inStringOrObj));}else if(inStringOrObj){elm.appendChild(inStringOrObj);}}}
function promoteElementChildren(inParent){while(inParent.childNodes.length>0){var currentChild=inParent.firstChild;inParent.removeChild(currentChild);inParent.parentNode.insertBefore(currentChild,inParent);}
inParent.parentNode.removeChild(inParent);}
function changeNodeName(inElement,inNodeName){var elm=$(inElement);var node=elm.ownerDocument.createElement(inNodeName);$A(elm.childNodes).each(function(child){elm.removeChild(child);node.appendChild(child);});elm.parentNode.insertBefore(node,elm);Element.remove(elm);return node;}
function insertAtBeginning(inElement,inParentElement){var elm=$(inParentElement);if(!elm)return false;if(elm.childNodes.length>0)elm.insertBefore($(inElement),elm.firstChild);else elm.appendChild($(inElement));}
function insertAfter(inElement,inSibling){var elm=$(inElement);var sibling=$(inSibling);var nextSibling=sibling.nextSibling;if(nextSibling)nextSibling.parentNode.insertBefore(elm,nextSibling);else sibling.parentNode.appendChild(inElement);}
Object.extend(String,{append:function(inOrig,inNew){var delimiter=arguments.length>2?arguments[2]:' ';if(inNew){if(inOrig!='')inOrig+=delimiter;inOrig+=inNew;}
return inOrig;},appendPathComponent:function(inString,inPathComponent){return inString.replace(/\/$/,'')+'/'+inPathComponent.replace(/^\//,'');},appendPathExtension:function(inString,inPathExtension){return inString.replace(/\.[^.]+$/,'')+'.'+inPathExtension.replace(/^\./,'');},addSlash:function(inString){return inString.replace(/([^\/])$/,'$1/');},removeSlash:function(inString){return inString.replace(/\/+$/,'');},lastPathComponent:function(inString){return inString.match(/\/([^\/]+)\/*$/)[1];},format:function(inFormatStr,inDictionary){return $H(inDictionary).inject(inFormatStr,function(str,cur){var r=new RegExp('%\\('+cur.key+'\\)[sdig]','gi');return str.replace(r,cur.value);});},hexValueForColorString:function(inColorString){var rgbColorMatch=inColorString.match(/rgba?\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\s*\)/);if(!rgbColorMatch)return inColorString;var colorStr='#';for(var colorMatchIdx=1;colorMatchIdx<4;colorMatchIdx++){colorStr+=padNumberStr(parseInt(rgbColorMatch[colorMatchIdx]).toString(16),2);}
return colorStr;}});Object.extend(Element,{childrenWithNodeName:function(inParent,inNodeName){var retList=[];var children=inParent.childNodes;for(var childIdx=0;childIdx<children.length;childIdx++){if(children.item(childIdx).nodeName==inNodeName)retList.push(children.item(childIdx));}
return retList;},elementWithSimpleXPath:function(inParent,inPath){return $A(inPath.split('.')).inject(inParent,function(currentParent,pathComponent){return currentParent?Element.firstChildWithNodeName(currentParent,pathComponent):null;});},firstChildWithNodeName:function(inParent,inNodeName){var children=inParent.childNodes;for(childIdx=0;childIdx<inParent.childNodes.length;childIdx++){if(children.item(childIdx).nodeName==inNodeName)return children.item(childIdx);}
return null;},firstNodeValue:function(inElement){var elm=(inElement&&inElement.constructor==String)?$(inElement):inElement;if(elm&&elm.firstChild)return elm.firstChild.nodeValue||'';return'';}});Object.extend(Array,{sortArrayUsingKey:function(inArray,inKey){var sortCallback=function(a,b){if(!(a[inKey]))return 0;if(a[inKey]>b[inKey])return 1;else if(a[inKey]<b[inKey])return-1;return 0;}
return inArray.sort(sortCallback);},removeDuplicateRows:function(inArray,inOptPreferenceTest){var keyedArray=inArray.clone();for(var rowIdx=0;rowIdx<keyedArray.length;rowIdx++){var row=keyedArray[rowIdx];if(!row.uid)continue;if(keyedArray[row.uid]){keyedArray.splice(rowIdx--,1);if(inOptPreferenceTest&&inOptPreferenceTest(keyedArray[row.uid],row)){var earlierIndex=keyedArray.indexOf(keyedArray[row.uid]);keyedArray.splice(earlierIndex,1,row);}}
keyedArray[row.uid]=row;}
return keyedArray.clone();}});Element.addClassName=function(element,className){if(!(element=$(element)))return;if(!Element.hasClassName(element,className))
element.className+=(element.className?' ':'')+className;return element;};if(window.Builder&&IEFixes.isIE){Builder.unpatched_node=Builder.node;Builder.node=function(){return $(Builder.unpatched_node.apply(this,arguments));}}
var gPrepareIteration=0;var d=document||'';if(!window.gDebug)gDebug=false;if(window.loaded)loaded('widgets_core.js');

/* wikiserver_api.js */

var AppleCollaborationServer=Class.createWithSharedInstance('server',true);AppleCollaborationServer.prototype={mCookieExpireDays:14,initialize:function(inOptionalURL){this.mPlainTextLogin=getMetaTagValue('apple_use_plaintext_login');this.url=fixSiteRelativeURLForIE(inOptionalURL||'/RPC2');this.getSessionIDFromCookie();this.setTimezoneCookie();Object.extend(this,{wiki:new CollaborationService(this,'wiki',['getSidebarEntries','filterText']),weblog:new CollaborationService(this,'weblog'),calendar:new CollaborationService(this,'calendar'),discussion:new CollaborationService(this,'discussion',['addDiscussionEntry','approveDiscussionEntry','commentAllowedOnEntryUID','deleteDiscussionEntry','getDiscussionEntries']),mailinglist:new CollaborationService(this,'mailinglist'),email:new CollaborationService(this,'email',['welcomeShortNamesToGroup']),versions:new CollaborationService(this,'versions'),search:new CollaborationService(this,'search',['getEntriesForQuickSearch','getEntriesForAllEntities','markAllAsRead','getUnreadFlagsForMyPage','getEntriesForMyPage','getEntities']),settings:new CollaborationService(this,'settings',['getSettings','setSettings','setUserSettings','manageTags','getThemes']),tags:new CollaborationService(this,'tags'),preferences:new CollaborationService(this,'preferences',['getUserPreference','setUserPreference','getUsersRelevantTags','getUsersRecentPages','addQueryForUser','removeQueryForUserByName','addUsersFavorite','removeUsersFavorite','markEntriesAsRead','markEntriesAsUnread','watchEntityForUser','hideEntityForUser']),whitepages:new CollaborationService(this,'whitepages',['getRecordsStartingWith'])});},login:function(inCallback,inUsername,inPassword,inOptAuthorizePath,inOptPersistent){var checkSuccess=function(q,r){if(r.success){this.rememberSessionID(r.session_id,inOptPersistent);publisher().publish('AUTHENTICATED',this);if(r.accessLevel&&r.accessLevel!='none'){publisher().publish('AUTHORIZED',this,{action:r.accessLevel,path:(inOptAuthorizePath||''),persistent:(inOptPersistent==true)});}
if(inCallback)inCallback();}
else{this.rememberSessionID('unauthenticated');var caught=publisher().publish('AUTHENTICATION_FAILED',this,inUsername);if(!caught)alert('Uncaught authentication failure for user: '+inUsername);}}
var performLoginRequest=function(){var method=this.mPlainTextLogin?'login':'digestLogin';var args=this.mPlainTextLogin?[inUsername,inPassword]:[digestResponse(inUsername,inPassword,this.mCachedChallenge)];this.mCachedChallenge=null;if(inOptAuthorizePath)args.push(inOptAuthorizePath);if(inOptAuthorizePath&&inOptPersistent)args.push(true);var req=new XMLRPCServiceRequest(this,method,checkSuccess.bind(this),args);}.bind(this);if(this.mCachedChallenge){performLoginRequest();}
else{this.cacheDigestChallenge(performLoginRequest);}},checkSessionAuthorization:function(inCallback,inOptAction,inOptPath){var action=inOptAction||'write';var authorizedCallback=function(){var userInfo={};if(inOptAction)userInfo['action']=inOptAction;if(inOptPath)userInfo['path']=inOptPath;publisher().publish('AUTHORIZED',this,userInfo);if(inCallback&&inCallback.constructor==Array)inCallback[0]();else if(inCallback)inCallback();}
var callback=authorizedCallback;if(inCallback&&inCallback.constructor==Array){callback=[authorizedCallback,inCallback[1]];}
return new XMLRPCRequest(this,'checkSessionAuthorization',callback,action,inOptPath);},logout:function(inCallback){var logoutCallback=function(){this.rememberSessionID('unauthenticated');this.flushExternalSessionIDs();if(inCallback)inCallback();publisher().publish('LOGGED_OUT',this,{reload:true});}
return new XMLRPCRequest(this,'logout',logoutCallback.bind(this));},getUploadProgress:function(inCallback,inUploadID){return new XMLRPCRequest(this,'getUploadProgress',inCallback,inUploadID);},adminKickServer:function(inCallback){return new XMLRPCRequest(this,'adminKickServer',inCallback);},groupsForSession:function(inCallback){return new XMLRPCRequest(this,'groupsForSession',inCallback);},groupShortNameFromLongName:function(inCallback,longname){return new XMLRPCRequest(this,'groupShortNameFromLongName',inCallback,longname);},provisionGroup:function(inCallback,settings,inOptScheme,inOptLang){return new XMLRPCRequest(this,'provisionGroup',inCallback,settings,inOptScheme,inOptLang);},unprovisionGroup:function(inCallback,shortname){return new XMLRPCRequest(this,'unprovisionGroup',inCallback,shortname);},provisionBlog:function(inCallback,shortname){return new XMLRPCRequest(this,'provisionUser',inCallback,shortname);},unprovisionBlog:function(inCallback,shortname){return new XMLRPCRequest(this,'unprovisionUser',inCallback,shortname);},cacheDigestChallenge:function(inCallback){if(this.mPlainTextLogin){if(inCallback)inCallback();return true;}
var callback=function(q,r){if(r.success){alert('Got a session id already: '+r.session_id);}
else{this.mCachedChallenge=r.challenge;if(inCallback)inCallback();}}
var req=new XMLRPCRequest(this,'digestLogin',callback.bind(this));},isSavingSomething:function(){return XMLRPCRequest.allRequests&&XMLRPCRequest.allRequests.detect(function(r){return r.required&&(!r.responseObj)});},getNextUploadID:function(){var uploadID=Math.floor(Math.random()*1000000);document.cookie='uploadID='+uploadID+'; path=/';return uploadID;},getSessionIDFromCookie:function(){var results=document.cookie.match('\\bsessionID=([^;]+)\\b');if(results){this.sessionID=results[1];}
else{this.rememberSessionID('unauthenticated');}},rememberSessionID:function(inSessionID,inOptPersistent){this.sessionID=inSessionID;var paths=['/updates','/groups','/users','/search','/ical','/settings','/media','/principals','/calendars','/timezones'];if(inOptPersistent)
{var expireDate=new Date();expireDate.setDate(expireDate.getDate()+this.mCookieExpireDays);}
for(var i=0;i<paths.length;i++)
{var parts=['sessionID='+inSessionID,'path='+paths[i]];if(inOptPersistent)
{parts.push('expires='+expireDate.toGMTString());}
if(window.location.protocol=='https:')
{parts.push('secure');}
document.cookie=parts.join(';');}
if(this.sessionID=="unauthenticated")
{document.cookie="sessionID=unauthenticated; path=/; expires=Fri, 27 Jul 2001 02:47:11 UTC";}},flushExternalSessionIDs:function(){var services=['com.apple.emailrules','com.apple.passwordreset'];services.each(function(service){document.cookie=service+'.sessionID=unauthenticated;path=/;';});},setTimezoneCookie:function(){var dt=new Date();var offset=dt.getTimezoneOffset()/(-60);dt.setFullYear(dt.getFullYear()+2);document.cookie='utcOffset='+offset+'; expires='+dt.toGMTString()+'; path=/';}}
var CollaborationService=Class.create();CollaborationService.prototype={mBaseMethods:['getEntries','getEntryWithUID','addEntry','updateEntry','deleteEntry','permanentlyDeleteEntry','undeleteEntry','addTagToEntry','removeTagFromEntry','removeVersionFromEntry','OLDgetEntries','getQuickLookSupportedAttachmentExtensions','getQuickLookPreviewPropertiesForAttachment'],initialize:function(inParent,inServiceName,inOptMethods){this.mParent=inParent;this.mServiceName=inServiceName;$A(this.mBaseMethods).concat(inOptMethods||[]).each(function(methodName){this[methodName]=function(){var args=$A(arguments);var cb=args.splice(0,1)[0];return new XMLRPCServiceRequest(this.mParent,this.mServiceName+'.'+methodName,cb,args);}.bind(this);}.bind(this));}}
var CollabUID=Class.createWithSharedInstance('uid');CollabUID.prototype={mMetaTagName:'apple_collab_uid',mSlash:'/',initialize:function(inOptValue){this.setValue(inOptValue||getMetaTagValue(this.mMetaTagName)||'');},setValue:function(inValue){var splitValue=inValue.split('/');while(splitValue.length<4)splitValue.push('');this.mValue=inValue;this.mOwnerType=splitValue[0];this.mOwnerName=splitValue[1];this.mService=splitValue[2];this.mItemName=splitValue[3];this.mBasePath=this.mOwnerType+'/'+this.mOwnerName;this.mBaseLocation='/'+this.mBasePath+'/';this.mBaseLocation=this.mBaseLocation.replace('//','/');this.mParentPath=this.mBasePath+'/'+this.mService;this.mParentLocation='/'+this.mParentPath+'/';},toString:function(){return this.mValue;}}
function _ucs4Ordinal(ch){var ucs4Ordinal="";ucs4Ordinal+=String.fromCharCode(240|(ch>>18));ucs4Ordinal+=String.fromCharCode(127|((ch>>12)&63));ucs4Ordinal+=String.fromCharCode(127|((ch>>6)&63));ucs4Ordinal+=String.fromCharCode(127|(ch&63));return ucs4Ordinal;}
function utf8Encode(string){var utf8Text="";for(var i=0;i<string.length;i++){var ch=string.charCodeAt(i);if(ch<128){utf8Text+=String.fromCharCode(ch);}
else if((ch>127)&&(ch<2048)){utf8Text+=String.fromCharCode(192|(ch>>6));utf8Text+=String.fromCharCode(128|(ch&63));}
else{if(ch<65536){if((55296<=ch)&&(ch<=57343)&&i!=string.length){var ch2=string.charCodeAt(i+1);if((56320<=ch2)&&(ch2<57343)){ch=((ch-55296)<<10|(ch2-56320))+65536;i++;utf8Text+=_ucs4Ordinal(ch);}}
utf8Text+=String.fromCharCode(224|(ch>>12));utf8Text+=String.fromCharCode(128|((ch>>6)&63));utf8Text+=String.fromCharCode(128|(ch&63));continue;}
utf8Text+=_ucs4Ordinal(ch);}}
return utf8Text;}
function digestResponse(username,password,challenge){var HA1=new Array(username,challenge.realm,password);HA1=utf8Encode(HA1.join(':'));HA1=hex_md5(HA1,HA1.length+chrsz);HA2="POST:/RPC2";HA2=hex_md5(HA2,HA2.length+chrsz);var response=new Array(HA1,challenge.nonce,HA2);response=response.join(':');response=hex_md5(response,response.length+chrsz);var responseObj={realm:challenge.realm,username:username,response:response,nonce:challenge.nonce,opaque:challenge.opaque,algorithm:challenge.algorithm,qop:challenge.qop,uri:'/RPC2',nc:'00000001'};return responseObj;}
Ajax.UnloadResponder=Class.create({initialize:function()
{this.requests=[];this.onCreate=this.onCreate.bind(this);this.onComplete=this.onComplete.bind(this);this.onUnload=this.onUnload.bind(this);},onCreate:function(request,transport)
{this.requests.push(request);},onComplete:function(request,transport)
{this.requests=this.requests.without(request);},onUnload:function()
{this.requests.each(function(r){if(r.transport){r.transport.onreadystatechange=function(){};r.transport.abort();}});}});var responder=new Ajax.UnloadResponder();Event.observe(window,'beforeunload',responder.onUnload);Ajax.Responders.register(responder);var XMLRPCMessage=Class.create();XMLRPCMessage.prototype={initialize:function(methodname){this.method=methodname||'system.listMethods';this.params=$A([]);},addParameter:function(data){if(arguments.length==0)return false;this.params.push(data);},xml:function(){return'<?xml version="1.0"?>\n<methodCall>\n<methodName>'+this.method+'</methodName>\n<params>\n'+this.params.collect(function(param){var s=new XMLRPCSerializer(param);return'<param>\n<value>'+s.xml()+'</value>\n</param>\n';}).join('')+'</params>\n</methodCall>\n';}}
var XMLRPCSerializer=Class.create();XMLRPCSerializer.prototype={initialize:function(inData){this.mData=inData;},xml:function(){var type=(''+typeof(this.mData)).toLowerCase();if(this['_'+type])return this['_'+type]();return'';},_array:function(){return'<array><data>\n'+$A(this.mData).collect(function(cur){var s=new XMLRPCSerializer(cur);return'<value>'+s.xml()+'</value>\n';}.bind(this)).join('')+'</data></array>\n';},_boolean:function(){return'<boolean>'+(this.mData?1:0)+'</boolean>';},_date:function(){return'<dateTime.iso8601>'+dateObjToISO8601(this.mData)+'</dateTime.iso8601>';},_function:function(){return'';},_number:function(){if(Math.round(this.mData)==this.mData)return'<i4>'+this.mData+'</i4>';return'<double>'+this.mData+'</double>';},_object:function(){if(this.mData.constructor==Date)return this._date();if(Object.isArray(this.mData))return this._array();return this._struct();},_string:function(){var strVal=this.mData.escapeHTML();try{var rx=new RegExp('[\\ca\\cb\\cc\\cd\\ce\\cf\\cg\\ch\\ck\\cl\\cn\\co\\cp\\cq\\cr\\cs\\ct\\cu\\cv\\cw\\cx\\cy\\cz]','g');if(!('a'.match(/[\ca]/)))strVal=strVal.replace(rx,'');}
catch(e){}
return'<string>'+strVal+'</string>';},_struct:function(){return'<struct>\n'+$H(this.mData).collect(function(cur){var s=new XMLRPCSerializer(cur.value);return'<member>\n<name>'+cur.key.escapeHTML()+'</name>\n<value>'+s.xml()+'</value>\n</member>\n';}.bind(this)).join('')+'</struct>\n';}}
var XMLRPCRequest=Class.create();XMLRPCRequest.prototype={initialize:function(inServerObj,inMethodNameStr,inCallback){this.setupRequest(inServerObj,inMethodNameStr,inCallback);for(var i=3;i<arguments.length;i++){if(arguments[i]!=null)this.requestMessageObj.addParameter(arguments[i]);}
this.sendRequest();},setupRequest:function(inServerObj,inMethodNameStr,inCallback){if(inCallback.constructor==Array){this.callbackFunction=inCallback[0];this.errorFunction=inCallback[1];}
else{this.callbackFunction=inCallback;}
this.serverObj=inServerObj;this.methodNameStr=inMethodNameStr;this.requestMessageObj=new XMLRPCMessage(inMethodNameStr);this.ajaxSocketObj=null;if(inServerObj.sessionID&&(inMethodNameStr!='login')&&(inMethodNameStr!='digestLogin'))this.requestMessageObj.addParameter(inServerObj.sessionID);},sendRequest:function(){if(!XMLRPCRequest.allRequests)XMLRPCRequest.allRequests=$A([]);XMLRPCRequest.allRequests.push(this);this.ajaxSocketObj=new Ajax.Request(this.serverObj.url,{method:'post',postBody:this.requestMessageObj.xml(),onComplete:this.handleCompleted.bind(this),asynchronous:true});},makeRequired:function(){this.required=true;return this;},handleCompleted:function(inTransportObj){if(inTransportObj.status==200){this.responseObj=new XMLRPCResponse(inTransportObj);if(this.responseObj.deserializedResponse.faultCode&&this.responseObj.deserializedResponse.faultString){this.handleError(this,this.responseObj.deserializedResponse.faultCode,this.responseObj.deserializedResponse.faultString);}
else{if(this.callbackFunction)this.callbackFunction(this,this.responseObj.deserializedResponse);}}
else{this.handleError(this,inTransportObj.status,inTransportObj.statusText);}
XMLRPCRequest.allRequests=XMLRPCRequest.allRequests.without(this);},handleError:function(inRequestObj,inFaultCode,inFaultString){if(inFaultCode==2){if(this.serverObj.sessionID!='unauthenticated'&&this.requestMessageObj.params.length>0&&this.requestMessageObj.params[0]==this.serverObj.sessionID){this.serverObj.rememberSessionID('unauthenticated');this.requestMessageObj.params[0]=this.serverObj.sessionID;this.sendRequest();publisher().publish('LOGGED_OUT',this,{reload:false});}
else{var caught=publisher().publish('BAD_SESSION_ID',this);if(!caught)alert('Uncaught error from server: bad session ID');}}
else if(this.errorFunction){this.errorFunction(inRequestObj,inFaultCode,inFaultString);}
else if(inFaultCode==3){var caught=publisher().publish('AUTHORIZATION_FAILED',this);if(!caught)alert('Uncaught error from server: unauthorized');}
else{var caught=publisher().publish('MISC_SERVER_ERROR',this,{faultCode:inFaultCode,faultString:inFaultString});if(!caught)alert('Uncaught error from server: '+inFaultString+' ('+inFaultCode+')');}},toString:function(){return this.requestMessageObj.xml();}}
var XMLRPCServiceRequest=Class.create();Object.extend(Object.extend(XMLRPCServiceRequest.prototype,XMLRPCRequest.prototype),{initialize:function(inServerObj,inMethodNameStr,inCallback,inOptArgumentsArray){this.setupRequest(inServerObj,inMethodNameStr,inCallback);$A(inOptArgumentsArray||[]).each(function(arg){this.requestMessageObj.addParameter(arg);}.bind(this));this.sendRequest();}});var XMLRPCResponse=Class.create();XMLRPCResponse.prototype={initialize:function(inTransportObj){var returnedValueNode=inTransportObj.responseXML.getElementsByTagName('value').item(0).firstChild;this.responseText=inTransportObj.responseText;this.deserializedResponse=this.deserializeNode(returnedValueNode);},deserializeNode:function(inNode){switch(inNode.nodeName.toLowerCase()){case"#text":return inNode.nodeValue;break;case"string":return $A(inNode.childNodes).inject('',function(str,node){return(node.nodeName.toLowerCase()=="#text"?str+node.nodeValue:str);});break;case"i4":case"int":return parseInt(inNode.firstChild.nodeValue);break;case"double":return parseFloat(inNode.firstChild.nodeValue);break;case"dateTime.iso8601":return createDateObjFromISO8601(inNode.firstChild.nodeValue);break;case"struct":return this.deserializeStructNode(inNode);break;case"array":return this.deserializeArrayNode(inNode.getElementsByTagName('data').item(0));break;case"boolean":return(inNode.firstChild.nodeValue=="1");break;}},deserializeStructNode:function(inNode){var deserializedStruct=new Object();var childNodesLength=inNode.childNodes.length;for(var i=0;i<childNodesLength;i++){var currentChildNode=inNode.childNodes[i];if(currentChildNode.nodeName=='member'){var currentKeyStr=currentChildNode.getElementsByTagName('name').item(0).firstChild.nodeValue;var currentValueNode=currentChildNode.getElementsByTagName('value').item(0).firstChild;var currentValue=this.deserializeNode(currentValueNode);deserializedStruct[currentKeyStr]=currentValue;}}
return deserializedStruct;},deserializeArrayNode:function(inNode){var deserializedArray=new Array();var childNodesLength=inNode.childNodes.length;for(var i=0;i<childNodesLength;i++){var currentChildNode=inNode.childNodes[i];if(!document.all)Element.cleanWhitespace(currentChildNode);if(currentChildNode.nodeName=='value'){var currentValueNode=currentChildNode.firstChild;var currentValue=this.deserializeNode(currentValueNode);deserializedArray[deserializedArray.length]=currentValue;}}
return deserializedArray;},toString:function(){return this.responseText;}}
if(window.loaded)loaded('wikiserver_api.js');

/* locUtils.js */

if(!window.Loc)Loc={};Loc.getBrowserLocale=function()
{return(navigator.language?navigator.language:navigator.browserLanguage||'en').split('-')[0];};Loc.getTimeRangeDisplayString=function(inStartDate,inDuration){if(inDuration.days>0&&inDuration.hours==0&&inDuration.minutes==0){var str=inStartDate.formatDate(Loc.dateFormats.mediumDate);if(inDuration.days>1){var endDate=getEndDateUsingDuration(inStartDate,inDuration);endDate.setDate(endDate.getDate()-1);str+=' - '+endDate.formatDate(Loc.dateFormats.mediumDate);}
return str;}
var time_string=Loc.getLocalizedHourKey(inStartDate.getHours(),inStartDate.getMinutes());var endDate=getEndDateUsingDuration(inStartDate,inDuration);return inStartDate.formatDate(Loc.dateFormats.mediumDate)+'; '+time_string+' - '+Loc.getLocalizedHourKey(endDate.getHours(),endDate.getMinutes());};Loc.getDurationDisplayString=function(inDuration){if(!inDuration)return'';var daysString='';var hoursString='';var minutesString='';var andString='';if(inDuration.days&&inDuration.days>0){var pluralString=Loc.durationFormats[inDuration.days>1?'days':'day'];daysString=String.format(Loc.durationFormats.daysFormat,{days:inDuration.days,pluralString:pluralString});}
var hours=0;if(inDuration.hours>0||inDuration.minutes>0){if(inDuration.hours>0){var pluralString=Loc.durationFormats[inDuration.hours>1?'hours':'hour'];hoursString=String.format(Loc.durationFormats.hoursFormat,{hours:inDuration.hours,pluralString:pluralString});}
if(inDuration.minutes>0){var pluralString=Loc.durationFormats[inDuration.minutes>1?'minutes':'minute'];minutesString=String.format(Loc.durationFormats.minutesFormat,{minutes:inDuration.minutes,pluralString:pluralString});}
if((inDuration.minutes>0)&&((inDuration.hours>0)||(inDuration.days>0))){andString=Loc.durationFormats['and'];}}
var subStrs={daysString:daysString,minutesString:minutesString,hoursString:hoursString};subStrs['and']=andString;return String.format(Loc.durationFormats.mainFormat,subStrs);};Loc.getRelativeDateString=function(d)
{if(!d)return'';var now=new Date();if((d.getDate()==now.getDate())&&(d.getMonth()==now.getMonth())&&(d.getFullYear()==now.getFullYear())){return Loc.today;}else if(d.getFullYear()==now.getFullYear()){return d.formatDate(Loc.dateFormats.shortDate);}else{return d.formatDate(Loc.dateFormats.mediumDate);}};Loc.getRelativeDatetimeString=function(d)
{if(!d)return'';var now=new Date();if((d.getDate()==now.getDate())&&(d.getMonth()==now.getMonth())&&(d.getFullYear()==now.getFullYear())){return String.format(Loc.dateFormats.todayDateAndTime,{'time':d.formatDate(Loc.dateFormats.hourAndMinutes)});}else{return d.formatDate(Loc.dateFormats.mediumDate);}};Loc.getLongDateString=function(inDateObj){return inDateObj?inDateObj.formatDate(Loc.dateFormats.mediumDateAndShortTime):'';};Loc.getExtraLongDateString=function(inDateObj){return inDateObj?inDateObj.formatDate(Loc.dateFormats.longDateAndLongTime):'';};Loc.getDateString=function(inDateObj){return inDateObj?inDateObj.formatDate(Loc.dateFormats.mediumDate):'';};Loc.getTimeString=function(inDateObj){return inDateObj?inDateObj.formatDate(Loc.dateFormats.hourAndMinutes):'';};Loc.getLocalizedHourKey=function(inHours,inOptMinutes){var dt=new Date();dt.setHours(inHours);dt.setMinutes(inOptMinutes||0);return dt.formatDate(Loc.dateFormats[(inOptMinutes&&inOptMinutes>0)?'hourAndMinutes':'hour']);};if(window.loaded)loaded('locUtils.js');

/* widgets.js */

var gAnimate=true;var gDoubleClickDelay=300;function loggedIn(sessionID){dialogManager().mOKCallback();}
var Notifier=Class.createWithSharedInstance('notifier');Notifier.prototype={initialize:function(){bindEventListeners(this,['handleMouseDown']);this.mTimeout=8000;this.mElement=Builder.node('div',{id:'system_message',style:(IEFixes.isIE6?"position:absolute;top:0;float:right;filter:alpha(opacity='70');display:none":'display:none')});d.body.appendChild(this.mElement);if(arguments.length>0)Object.extend(this,arguments[0]);var results=d.cookie.match(/notify=([^;]+)/);if(results){var callback=function(){this.mTimer=null;this.print(results[1]);}
this.mTimer=setTimeout(callback.bind(this),1000);d.cookie='notify=; path=/';}},print:function(inStr){if(typeof(Loc)!='undefined')inStr=((Loc&&Loc[inStr])?Loc[inStr]:inStr);removeAllChildNodes(this.mElement);this.mElement.appendChild(d.createTextNode(inStr));if(gAnimate){if(this.mEffect)this.mEffect.cancel();this.mEffect=new Effect.Appear(this.mElement);}
else{Element.show(this.mElement);}
if(this.mTimer)clearTimeout(this.mTimer);this.mTimer=setTimeout(this.hide.bind(this),this.mTimeout);observeEvents(this,d,{mousedown:'handleMouseDown'});if(window.unitTestHandler)unitTestHandler.messageFromJS_(inStr);},printAtPage:function(inStr,inPage){d.cookie='notify='+inStr+'; path=/';if(inPage){if(SafariFixes.isWebKit){var a=Builder.node('a',{href:inPage,display:'none'});d.body.appendChild(a);var evt=document.createEvent('MouseEvents');evt.initEvent('click',true,true);a.dispatchEvent(evt);}
else{location.href=inPage;}}
else{location.reload(true);}},hide:function(){var inFade=(arguments.length>0?arguments[0]:gAnimate);Event.stopObserving(d,'mousedown',this.handleMouseDown);if(this.mEffect)this.mEffect.cancel();if(inFade){this.mEffect=new Effect.Fade(this.mElement);}
else{Element.hide(this.mElement);}
this.mTimer=null;},handleMouseDown:function(e){if(this.mTimer)clearTimeout(this.mTimer);this.hide(false);}}
var TooltipManager=Class.createWithSharedInstance('tooltipManager',true);TooltipManager.prototype={mShowTimeout:2000,mHideTimeout:20000,mEnabled:true,initialize:function(){bindEventListeners(this,['handleMouseDown','handleMouseOver','handleMouseOut']);},show:function(inElement,inValues){this.mElement=$(inElement);var prefix=this.mElement.id+'_';this.mPopulatedKeys=[];for(var key in inValues){if($(prefix+key)){this.mPopulatedKeys.push(prefix+key);replaceElementContents(prefix+key,(inValues[key].constructor==Function?inValues[key]():inValues[key])||'');}}
this.mElement.style.visibility='hidden';Element.show(inElement);var leftPos=Math.min(this.mPos[0],d.viewport.getWidth()-this.mElement.offsetWidth-8);var topPos=Math.min(this.mPos[1],d.viewport.getHeight()-this.mElement.offsetHeight-8);Element.hide(inElement);Element.setStyle(inElement,{left:leftPos+'px',top:topPos+'px',visibility:''});this.mEffect=new Effect.Appear(inElement,{duration:0.5});if(this.mTimer)clearTimeout(this.mTimer);this.mTimer=setTimeout(this.hide.bind(this),this.mHideTimeout);observeEvents(this,d,{mousedown:'handleMouseDown'});},hide:function(){var afterFinish=function(){this.mPopulatedKeys.each(function(key){replaceElementContents(key,"\u00A0");});}.bind(this);var inFade=(arguments.length>0?arguments[0]:gAnimate);Event.stopObserving(d,'mousedown',this.handleMouseDown);if(this.mActiveElement)Event.stopObserving(this.mActiveElement,'mouseout',this.handleMouseOut);this.mActiveElement=null;if(this.mEffect)this.mEffect.cancel();if(inFade&&this.mElement){this.mEffect=new Effect.Fade(this.mElement,{from:0.9,afterFinish:afterFinish});}
else if(this.mElement){Element.hide(this.mElement);afterFinish();}
if(this.mTimer)clearTimeout(this.mTimer);this.mTimer=null;},handleMouseDown:function(e){this.mActiveElement=null;if(this.mTimer)clearTimeout(this.mTimer);this.hide(false)},handleMouseOver:function(e){if(this.mEnabled){this.mPos=new Array(Event.pointerX(e)+2,Event.pointerY(e)+10);this.mActiveElement=Event.element(e);while(this.mActiveElement.parentNode&&!this.mActiveElement.tooltipElement){this.mActiveElement=$(this.mActiveElement.parentNode);}
if(this.mTimer)clearTimeout(this.mTimer);this.mTimer=setTimeout(this.getValues.bind(this),this.mShowTimeout);observeEvents(this,this.mActiveElement,{mouseout:'handleMouseOut'});}},handleMouseOut:function(e){if(this.mTimer)clearTimeout(this.mTimer);try{this.hide(false)}
catch(e){}},observe:function(inElement){observeEvents(this,inElement,{mouseover:'handleMouseOver'});},stopObserving:function(inElement){if(this.mActiveElement==inElement){this.hide(false);if(this.mTimer)clearTimeout(this.mTimer);this.mTimer=null;this.mActiveElement=null;}
Event.stopObserving(inElement,'mouseover',this.handleMouseOver);},getValues:function(){if(this.mActiveElement&&this.mActiveElement.tooltipValues){this.show(this.mActiveElement.tooltipElement,this.mActiveElement.tooltipValues);}
else if(this.mActiveElement&&this.mActiveElement.tooltipCallback){this.mActiveElement.tooltipCallback(this.mActiveElement);}}}
var ModalDialogManager=Class.createWithSharedInstance('dialogManager');ModalDialogManager.prototype={mSlideFromElement:null,mProgressMessageDelay:700,mProgressMessageHideDelay:850,initialize:function(){bindEventListeners(this,['handleKeyPress','handleCancelClick','handleOKClick','handleDialogMouseDown','handleDialogDrag','handleDialogEndDrag']);if($('dialog_mask')){this.mMaskWidget=$('dialog_mask');}else{this.mMaskWidget=Builder.node('div',{id:'dialog_mask',style:(IEFixes.isIE6?"position:absolute;top:0;left:0;width:100%;filter:alpha(opacity='50');display:none":'display:none')});d.body.appendChild(this.mMaskWidget);}
if(arguments.length>0)Object.extend(this,arguments[0]);},drawDialog:function(inID,inFields,inOKTitle,inOptFormAction){var tbody=Builder.node('tbody');var dialog=Builder.node('div',{id:inID,className:'dialog',style:'display:none','role':'dialog'},[Builder.node('div',{className:'dialog_contents'},[Builder.node('form',{id:inID+'_form',method:(inOptFormAction?'post':'get'),action:inOptFormAction||'#',enctype:(inOptFormAction?'multipart/form-data':'application/x-www-form-urlencoded'),target:(inOptFormAction?'image_upload_iframe':'_self')},[Builder.node('table',[Builder.node('thead',[Builder.node('tr',[Builder.node('td',{colSpan:'2'},(Loc[inID+'_header']||''))])]),tbody])])])]);for(index=0;index<inFields.length;index++){var field=inFields[index];var td=Builder.node('td');var labelText=Loc[field.label]||field.label;var label=Builder.node('label',labelText);var headerArgs=(labelText==''?{className:'dialog_empty_header'}:{});if((field.label||field.label=='')&&field.contents){tbody.appendChild(Builder.node('tr',[Builder.node('th',headerArgs,label),td]));replaceElementContents(td,field.contents,true);if(field.id)td.id=field.id;var inputs=td.getElementsByTagName('input');if(inputs.length)label.setAttribute('for',inputs.item(0).getAttribute('id'));}
else{var fieldValue=field.contents||field;Element.addClassName(td,'dialog_description');td.colSpan='2';if(field.id)td.id=field.id;tbody.appendChild(Builder.node('tr',[td]));replaceElementContents(td,Loc[fieldValue]||fieldValue,field.contents);}}
tbody.appendChild(Builder.node('tr',[Builder.node('td',{colSpan:'2',className:'form_buttons'},[Builder.node('div',{className:'submit'},[Builder.node('input',{type:'submit',className:'primaryaction',id:inID+'_ok',value:(Loc[inOKTitle]||inOKTitle),name:'ok_button'}),Builder.node('input',{type:'button',className:'secondaryaction',id:inID+'_cancel',value:Loc.cancel,name:'cancel_button'})])])]));d.body.appendChild(dialog);if(!inOptFormAction)$(inID+'_form').onsubmit=invalidate;return dialog;},focus:function(){if(this.mFocusField){if(this.mFocusField.activate)this.mFocusField.activate();}
else{var inputs=this.mActiveElement.getElementsByTagName('input');$A(inputs).detect(function(elm){if(elm.type&&elm.focus&&(elm.type.toLowerCase()=='text'||elm.type.toLowerCase()=='search')&&(!Element.hasClassName(elm,'search_field'))&&(!elm.disabled)){$(elm).activate();return true;}
return false;});}
if(window.unitTestHandler)unitTestHandler.messageFromJS_('dialog');publisher().publish('DIALOG_FOCUS',this.mActiveElement);},prepareToShow:function(inElement,inCancelCallback,inOKCallback,inOptSlideFrom,inOptShowSpinner,inOptFocusField,inOptAllowSubmission){this.hide();this.mShowSpinner=inOptShowSpinner;this.mFocusField=$(inOptFocusField);this.mAllowSubmission=inOptAllowSubmission;inOptSlideFrom=inOptSlideFrom||this.mSlideFromElement;this.mActiveParent=(inOptSlideFrom?$(inOptSlideFrom):null);if(this.mTimer){clearTimeout(this.mTimer);delete this.mTimer;}
this.mActiveElement=$(inElement);this.mCancelCallback=inCancelCallback;this.mOKCallback=inOKCallback;if(IEFixes.isIE6)this.mMaskWidget.style.height=(d.viewport.getHeight()+d.viewport.getScrollOffsets().top)+'px';publisher().publish('DIALOG_WILL_SHOW',this.mActiveElement);Element.show(this.mMaskWidget);},finishShowing:function(){this.mCancelElement=$(this.mActiveElement.id+'_cancel');if(this.mCancelElement){Event.observe(this.mCancelElement,'click',this.handleCancelClick);}
Event.observe(d,'keydown',this.handleKeyPress);this.mFormElement=$(this.mActiveElement.id+'_form');if(this.mFormElement){if(SafariFixes.isWebKit&&(this.mFormElement.enctype=='multipart/form-data')&&$(this.mActiveElement.id+'_ok')){$(this.mActiveElement.id+'_ok').type='button';this.mObservingInfo={elm:this.mActiveElement.id+'_ok',evt:'click'};Event.observe(this.mActiveElement.id+'_ok','click',this.handleOKClick);}
else{this.mObservingInfo={elm:this.mFormElement,evt:'submit'};Event.observe(this.mFormElement,'submit',this.handleOKClick);}}
if(this.mCancelElement)this.mCancelElement.disabled=false;if($(this.mActiveElement.id+'_ok'))$(this.mActiveElement.id+'_ok').disabled=false;Event.observe(this.mActiveElement,'mousedown',this.handleDialogMouseDown);},show:function(inElement,inCancelCallback,inOKCallback,inOptSlideFrom,inOptShowSpinner,inOptFocusField,inOptAllowSubmission){this.prepareToShow(inElement,inCancelCallback,inOKCallback,inOptSlideFrom,inOptShowSpinner,inOptFocusField,inOptAllowSubmission);if(this.mActiveParent&&(inElement!=this.mProgressElement)){window.scrollTo(0,0);this.mActiveElement.style.height='';Element.setStyle(this.mActiveParent,{position:'relative',zIndex:'504'});Element.addClassName(this.mActiveParent,'dialog_parent');this.mActiveElement.style.visibility='hidden';Element.show(this.mActiveElement);var cloneOptions={setWidth:false,setHeight:false,offsetLeft:(this.mActiveParent.offsetWidth/2)-(this.mActiveElement.offsetWidth/2),offsetTop:Element.getHeight(this.mActiveParent)};Position.clone(this.mActiveParent,this.mActiveElement,cloneOptions);}
else{this.mActiveElement.style.visibility='hidden';Element.show(this.mActiveElement);var elementBounds=offsetBoundsForDiv(this.mActiveElement.down('table')||this.mActiveElement);var leftd=((window.innerWidth||d.body.offsetWidth)/2)-(elementBounds[2]/2);var topd=((window.innerHeight||d.documentElement.offsetHeight)/3)-(elementBounds[3]/2);leftd=Math.max(leftd,0);topd=Math.max(topd,0)+d.viewport.getScrollOffsets().top;this.mActiveElement.style.left=leftd+'px';this.mActiveElement.style.top=topd+'px';}
if(MozillaFixes.isGecko)this.mActiveElement.style.position='fixed';Element.hide(this.mActiveElement);this.mActiveElement.style.visibility='visible';this.mEffect=new Effect.Appear(this.mActiveElement,{duration:0.3,afterFinish:this.focus.bind(this)});if(IEFixes.isIE){Element.setStyle(this.mMaskWidget,{width:d.body.offsetWidth+'px',height:d.documentElement.offsetHeight+'px'});}
this.finishShowing();},handleDialogMouseDown:function(inEvent){if(inEvent.findElement('thead')||inEvent.findElement('h2')){if(Element.hasClassName(inEvent.findElement('table'),'tableEditor')){return;}else if(inEvent.findElement('h2')&&!inEvent.findElement('h2').up('div.dialog').id=='tableDialog'){return;}
Event.stop(inEvent);this.mDragPos=[inEvent.pointerX(),inEvent.pointerY()];observeEvents(this,d,{mousemove:'handleDialogDrag',mouseup:'handleDialogEndDrag'});}},handleDialogDrag:function(inEvent){Event.stop(inEvent);this.mActiveElement.style.left=(parseFloat(this.mActiveElement.style.left)+(inEvent.pointerX()-this.mDragPos[0]))+'px';this.mActiveElement.style.top=(parseFloat(this.mActiveElement.style.top)+(inEvent.pointerY()-this.mDragPos[1]))+'px';this.mDragPos=[inEvent.pointerX(),inEvent.pointerY()];return false;},handleDialogEndDrag:function(inEvent){stopObservingEvents(this,d,{mousemove:'handleDialogDrag',mouseup:'handleDialogEndDrag'});},showProgressMessage:function(inMessage,inOptShowProgressBar,inOptCancelCallback){dialogManager().showingProgressMessage=true;if(!this.mProgressElement){this.mProgressElement=this.drawDialog('progress_message_dialog',[{id:'progress_spinner',contents:"<span>\u00A0</span>"},{id:'progress_message',contents:"\u00A0"}],'cancel');$('progress_message_dialog_ok').remove();}
if(inOptShowProgressBar){Element.removeClassName(this.mProgressElement,'indeterminate');this.mProgressBar=Builder.node('div',{className:'progress_bar'},[Builder.node('div',{style:'width:0'},"\u00A0")]);replaceElementContents(this.mProgressElement.down('thead td'),Loc[inMessage]||inMessage);replaceElementContents('progress_message',this.mProgressBar);}
else{replaceElementContents('progress_message',(Loc[inMessage]||inMessage));Element.addClassName(this.mProgressElement,'indeterminate');removeAllChildNodes(this.mProgressElement.down('thead td'));}
this.hide(null,true);this.mTimer=setTimeout(function(){if(this.mHideDelayTimer){clearTimeout(this.mHideDelayTimer);delete this.mHideDelayTimer;}
this.mHideDelayTimer=setTimeout(function(){delete this.mHideDelayTimer;if(this.mShouldHideLater){this.mShouldHideLater=false;this.hideProgressMessage();}}.bind(this),this.mProgressMessageHideDelay);this.show(this.mProgressElement,inOptCancelCallback,invalidate);}.bind(this),this.mProgressMessageDelay);delete dialogManager().showingProgressMessage;},hide:function(inOptElement,inPerformFakeHide){if(!this.mTargeted)targetedDialogManager().hide(inOptElement,inPerformFakeHide);if(this.mObservingInfo){Event.stopObserving(this.mObservingInfo.elm,this.mObservingInfo.evt,this.handleOKClick);delete this.mObservingInfo;}
if(SafariFixes.isWebKit&&this.mProgressElement&&(this.mActiveElement==this.mProgressElement)){$$('div.dialog').each(function(dialogDiv){if(dialogDiv.style.visibility=='hidden'){Element.hide(dialogDiv);dialogDiv.style.visibility='';}});}
if(inOptElement&&(this.mActiveElement!=inOptElement))return false;if(this.mTimer){clearTimeout(this.mTimer);delete this.mTimer;}
Event.stopObserving(d,'keydown',this.handleKeyPress);if(this.mCancelElement){if(this.mShowSpinner)this.mCancelElement.disabled=false;Event.stopObserving(this.mCancelElement,'click',this.handleCancelClick);delete this.mCancelElement;}
if(this.mShowSpinner){$(this.mActiveElement.id+'_ok').disabled=false;$A(this.mActiveElement.getElementsByClassName('dialog_progress_row')).invoke('removeClassName','dialog_progress_row');this.mShowSpinner=false;}
if(this.mActiveElement){Event.stopObserving(this.mActiveElement,'mousedown',this.handleDialogMouseDown);if(this.mEffect)this.mEffect.cancel();var elementForm=$(this.mActiveElement).down('form');if(SafariFixes.isWebKit&&dialogManager().showingProgressMessage&&elementForm&&elementForm.method=='post'){this.mActiveElement.style.visibility='hidden';}
else{Element.hide(this.mActiveElement);}
Element.hide(this.mMaskWidget);publisher().publish('DIALOG_HIDDEN',this.mActiveElement);delete this.mActiveElement;}
if(this.mActiveParent){Element.setStyle(this.mActiveParent,{position:'',zIndex:''});Element.removeClassName(this.mActiveParent,'dialog_parent');}},shakeDialog:function(){var element=$(this.mActiveElement);element=$(element);var oldStyle={left:element.getStyle('left')};return new Effect.Move(element,{x:10,y:0,duration:0.05,afterFinishInternal:function(effect){new Effect.Move(effect.element,{x:-20,y:0,duration:0.1,afterFinishInternal:function(effect){new Effect.Move(effect.element,{x:20,y:0,duration:0.1,afterFinishInternal:function(effect){new Effect.Move(effect.element,{x:-20,y:0,duration:0.1,afterFinishInternal:function(effect){new Effect.Move(effect.element,{x:20,y:0,duration:0.1,afterFinishInternal:function(effect){new Effect.Move(effect.element,{x:-10,y:0,duration:0.05,afterFinishInternal:function(effect){effect.element.setStyle(oldStyle);}})}})}})}})}})}});},willResize:function(){if(!this.mActiveElement)return;var contentsTable=this.mActiveElement.down('table');this.mOldStyles={top:parseInt(this.mActiveElement.style.top),left:parseInt(this.mActiveElement.style.left),width:this.mActiveElement.getWidth(),height:this.mActiveElement.getHeight()};if(contentsTable){this.mOldStyles.tableWidth=contentsTable.getWidth();this.mOldStyles.tableHeight=contentsTable.getHeight();}
this.mActiveElement.setStyle({left:'0',top:'0'});},didResize:function(){if(!this.mActiveElement)return;if(!this.mOldStyles)return;Element.setOffsetWidth(this.mActiveElement,this.mActiveElement.getWidth());Element.setOffsetHeight(this.mActiveElement,this.mActiveElement.getHeight());var changedWidth=parseInt(this.mActiveElement.style.width);var changedHeight=parseInt(this.mActiveElement.style.height);var contentsTable=this.mActiveElement.down('table');var changedTableWidth=0;var changedTableHeight=0;if(contentsTable&&this.mOldStyles.tableWidth){Element.setOffsetWidth(contentsTable,contentsTable.getWidth());Element.setOffsetHeight(contentsTable,contentsTable.getHeight());changedTableWidth=parseInt(contentsTable.style.width);changedTableHeight=parseInt(contentsTable.style.height);}
this.mActiveElement.setStyle({left:this.mOldStyles.left+'px',top:this.mOldStyles.top+'px'});if(contentsTable&&this.mOldStyles.tableWidth){Element.setOffsetWidth(contentsTable,this.mOldStyles.tableWidth);Element.setOffsetHeight(contentsTable,this.mOldStyles.tableHeight);}
Element.setOffsetWidth(this.mActiveElement,this.mOldStyles.width);Element.setOffsetHeight(this.mActiveElement,this.mOldStyles.height);var delta=changedWidth-parseInt(this.mActiveElement.style.width);var changedLeft=Math.round(this.mOldStyles.left-(delta/2));changedLeft=Math.max(Math.min(changedLeft,d.viewport.getWidth()-changedWidth-30),10);var resizedStyleString='left:'+changedLeft+'px;width:'+changedWidth+'px;height:'+changedHeight+'px';if(this.mResizeEffect)this.mResizeEffect.cancel();var effects=$A([new Effect.Morph(this.mActiveElement,{style:resizedStyleString})]);if(contentsTable){effects.push(new Effect.Morph(contentsTable,{style:'width:'+changedTableWidth+'px;height:'+changedTableHeight+'px'}));}
this.mResizeEffect=new Effect.Parallel(effects,{duration:0.20,afterFinish:function(eff){this.mActiveElement.setStyle({width:'',height:''});if(contentsTable)contentsTable.setStyle({width:'',height:''});}.bind(this)});delete this.mOldStyles;},hideProgressMessage:function(){if(this.mTimer){clearTimeout(this.mTimer);delete this.mTimer;}
if(this.mActiveElement==this.mProgressElement){if(this.mHideDelayTimer){this.mShouldHideLater=true;}
else{this.hide();}}},handleKeyPress:function(inEvent){if(inEvent.keyCode==Event.KEY_ESC){this.handleCancelClick(inEvent);}},handleCancelClick:function(inEvent){this.hide();if(this.mCancelCallback)this.mCancelCallback();},handleOKClick:function(inEvent){var elm=Event.element(inEvent);if(!this.mAllowSubmission)Event.stop(inEvent);if(elm&&elm.type&&elm.form&&(elm.type=='button')&&this.mAllowSubmission)elm.form.submit();if(this.mShowSpinner){if(this.mCancelElement)this.mCancelElement.disabled=true;$(this.mActiveElement.id+'_ok').disabled=true;$A(this.mActiveElement.getElementsByClassName('form_buttons')).invoke('addClassName','dialog_progress_row');}
else{this.hide();}
if(this.mOKCallback)this.mOKCallback();if(!this.mAllowSubmission)return false;}}
var TargetedDialogManager=Class.createWithSharedInstance('targetedDialogManager');Object.extend(Object.extend(TargetedDialogManager.prototype,ModalDialogManager.prototype),{mTargeted:true,show:function(inElement,inCancelCallback,inOKCallback,inSlideFrom,inOptShowSpinner,inOptFocusField,inOptAllowSubmission){this.prepareToShow(inElement,inCancelCallback,inOKCallback,inSlideFrom,inOptShowSpinner,inOptFocusField,inOptAllowSubmission);Element.addClassName(this.mActiveElement,'targeted_dialog');if(MozillaFixes.isGecko)this.mActiveElement.style.position='fixed';this.mActiveElement.style.visibility='hidden';Element.show(this.mActiveElement);Element.setStyle(this.mActiveElement,{width:'',height:''});var origSize=Element.getInvisibleSize(this.mActiveElement);if(IEFixes.isIE&&$('toolbars')&&Element.descendantOf(inSlideFrom,'toolbars'))Position.absolutize('toolbars');var editorElement=$('editable_content');if(editorElement&&editorElement.tagName.toLowerCase()=='iframe'&&Element.descendantOf(inSlideFrom,window.frames['editable_content'].document.body)){Position.clone(editorElement,this.mActiveElement,{limitWithScrollbars:true});if(IEFixes.isIE&&$('toolbars')&&Element.descendantOf(inSlideFrom,'toolbars'))Position.relativize('toolbars');var clonedSize=Element.getInvisibleSize(this.mActiveElement);Element.setStyle(this.mActiveElement,{width:Math.min(origSize[0],clonedSize[0])+'px',height:Math.min(origSize[1],clonedSize[1])+'px'});var originalTop=parseInt(this.mActiveElement.style.top);var originalLeft=parseInt(this.mActiveElement.style.left);var top=originalTop+inSlideFrom.offsetTop-window.frames['editable_content'].scrollY;var left=originalLeft+inSlideFrom.offsetLeft;if(top<originalTop){top=originalTop;}else if(top+this.mActiveElement.getHeight()>originalTop+editorElement.getHeight()){top=originalTop+editorElement.getHeight()-this.mActiveElement.getHeight();}
this.mActiveElement.style.top=top+'px';this.mActiveElement.style.left=left+'px';}else{Position.clone(inSlideFrom,this.mActiveElement,{limitWithScrollbars:true});if(IEFixes.isIE&&$('toolbars')&&Element.descendantOf(inSlideFrom,'toolbars'))Position.relativize('toolbars');var clonedSize=Element.getInvisibleSize(this.mActiveElement);Element.setStyle(this.mActiveElement,{width:Math.min(origSize[0],clonedSize[0])+'px',height:Math.min(origSize[1],clonedSize[1])+'px'});}
var diffs=[this.mActiveElement.offsetWidth-parseInt(this.mActiveElement.style.width),this.mActiveElement.offsetHeight-parseInt(this.mActiveElement.style.height)];origSize[0]-=diffs[0];origSize[1]-=diffs[1];Element.hide(this.mActiveElement);this.mActiveElement.style.visibility='';var leftOffset1='';var leftOffset2='';if(parseInt(this.mActiveElement.style.left)>(d.viewport.getWidth()/2)){this.mActiveElement.style.left=(parseInt(this.mActiveElement.style.left)-6)+'px';var leftOffset=parseInt(this.mActiveElement.style.left)+parseInt(this.mActiveElement.style.width)-origSize[0]-diffs[0]-diffs[0];leftOffset1='left:'+(leftOffset-13)+'px;';leftOffset2='left:'+leftOffset+'px;';}
else{this.mActiveElement.style.left=(parseInt(this.mActiveElement.style.left)+6)+'px';}
var topOffset1='';var topOffset2='';if(parseInt(this.mActiveElement.style.top)>(d.viewport.getHeight()/2)){this.mActiveElement.style.top=(parseInt(this.mActiveElement.style.top)-6)+'px';var topOffset=parseInt(this.mActiveElement.style.top)+parseInt(this.mActiveElement.style.height)-origSize[1]-diffs[1];topOffset1='top:'+(topOffset-13)+'px;';topOffset2='top:'+topOffset+'px;';}
else{this.mActiveElement.style.top=(parseInt(this.mActiveElement.style.top)+6)+'px';}
Element.show(this.mActiveElement);this.mEffect=new Effect.Morph(inElement,{style:leftOffset1+topOffset1+'width:'+(origSize[0]+13)+'px;height:'+(origSize[1]+13)+'px',duration:0.14,afterFinish:function(eff){new Effect.Morph(eff.element,{style:leftOffset2+topOffset2+'width:'+origSize[0]+'px;height:'+origSize[1]+'px',duration:0.08,afterFinish:function(eff){eff.element.style.width='';eff.element.style.height='';this.focus();}.bind(this)});}.bind(this)});this.finishShowing();}});var NiftyDatePicker=Class.create();NiftyDatePicker.prototype={mSelectedDate:new Date(),mShownDate:new Date(),mDateLinks:$A([]),mStartWeekday:0,mEnabled:true,initialize:function(){bindEventListeners(this,['handleParentElementClick','handleWindowClick','handleMonthSkipButtonClick','handleDateCellClick']);this.mParentDateFormat=Loc.dateFormats.mediumDate;if(arguments.length>0)Object.extend(this,arguments[0]);if(this.mElement)this.mElement=$(this.mElement);if(!this.mElement){this.mElement=Builder.node('div',{className:'niftydate_popup',style:'visibility:hidden'});d.body.appendChild(this.mElement);}
if(!this.mElement.id){this.mElement.id='niftydate_'+Math.floor(Math.random()*1000000);}
Element.addClassName(this.mElement,'niftydate');replaceElementContents(this.mElement,Builder.node('h2',[Builder.node('a',{href:'#',className:'niftydate_prev_month'},'<'),Builder.node('span',{className:'niftydate_header'},this.mShownDate.formatDate(Loc.dateFormats.longMonthAndYear)),Builder.node('a',{href:'#',className:'niftydate_next_month'},'>')]));var calendarHeaderElm=Builder.node('ul',{className:'niftydate_headers'});this.mElement.appendChild(calendarHeaderElm);for(var i=0;i<7;i++){calendarHeaderElm.appendChild(Builder.node('li',"\u00A0"));}
this.drawWeekdayHeaders();this.mHeaderBlockSpacer=new BlockSpacer(calendarHeaderElm,this.mElement);var calendarDaysElm=Builder.node('ul',{className:'niftydate_days'});for(var weekday=0;weekday<7;weekday++){calendarDaysElm.appendChild(Builder.node('li',{className:(weekday==0?'niftydate_column niftydate_first_column':'niftydate_column')}));}
this.mElement.appendChild(calendarDaysElm);this.setShownDate(this.mShownDate);this.mCellBlockSpacer=new BlockSpacer(calendarDaysElm,this.mElement);var width=calendarDaysElm.down('ul').offsetWidth;$$('#'+this.mElement.id+' ul.niftydate_days ul li').each(function(li){li.style.lineHeight=width+'px';});$$('#'+this.mElement.id+' .niftydate_prev_month_cells').invoke('hide');$$('#'+this.mElement.id+' .niftydate_next_month_cells').invoke('hide');Event.observe(this.mElement.down('a.niftydate_prev_month'),'click',this.handleMonthSkipButtonClick);Event.observe(this.mElement.down('a.niftydate_next_month'),'click',this.handleMonthSkipButtonClick);if(this.mParentElement)Event.observe(this.mParentElement,'click',this.handleParentElementClick);if(this.mParentElement)replaceElementContents(this.mParentElement,this.mSelectedDate.formatDate(this.mParentDateFormat));publisher().subscribe(this.handleOtherDatePickerShown.bind(this),'DATE_PICKER_SHOWN');},drawWeekdayHeaders:function(){var calendarHeaderElm=this.mElement.down('ul.niftydate_headers');$$('#'+this.mElement.id+' ul.niftydate_headers li').each(function(li,i){replaceElementContents(li,Loc.weekdays[(this.mStartWeekday+i)%7]);},this);},handleParentElementClick:function(inEvent){Event.stop(inEvent);this.show();return false;},handleWindowClick:function(inEvent){if(!Position.within(this.mElement,Event.pointerX(inEvent),Event.pointerY(inEvent)))this.hide();},handleOtherDatePickerShown:function(inMessage,inObject,inUserInfo){if(inObject!=this)this.hide();},show:function(){if(!this.mParentElement)return;Position.clone(this.mParentElement,this.mElement,{setWidth:false,setHeight:false});Element.show(this.mElement);Event.observe(window,'click',this.handleWindowClick);publisher().publish('DATE_PICKER_SHOWN',this);},hide:function(){if(!this.mParentElement)return;Event.stopObserving(window,'click',this.handleWindowClick);Element.hide(this.mElement);},setShownDate:function(inNewShownDate){var dt=new Date(inNewShownDate.getTime());dt.setDate(1);dt.setDate(1-(dt.getDay()-this.mStartWeekday));if(1<dt.getDate()&&dt.getDate()<8){dt.setDate(dt.getDate()-7);}
var cellHeight=$$('#'+this.mElement.id+' ul.niftydate_days li')[0].offsetWidth;if(cellHeight==0)cellHeight=$$('#'+this.mElement.id+' ul.niftydate_headers li')[0].offsetWidth;var isFirstSetup=$$('#'+this.mElement.id+' ul.niftydate_days li ul').length<=0;var direction=(inNewShownDate>this.mShownDate)?1:(-1);var columns=$$('#'+this.mElement.id+' li.niftydate_column');var oldDateLists=$$('#'+this.mElement.id+' li.niftydate_column ul');var dateLists=$R(0,6).collect(function(i){var ul=Builder.node('ul',{className:(isFirstSetup?'':'animatedheight')});if(isFirstSetup||direction==1){columns[i].appendChild(ul);}
else{insertAtBeginning(ul,columns[i]);}
return ul;});var now=new Date();var todayDateISO=parseInt(dateObjToISO8601(now));var selectedDateISO=parseInt(dateObjToISO8601(this.mSelectedDate));for(var i=0;i<(7*6);i++){var dtISO=parseInt(dateObjToISO8601(dt));var li=Builder.node('li',{style:'line-height:'+cellHeight+'px'},[Builder.node('a',{href:'#',className:'niftydate_datecell_'+dtISO},''+dt.getDate())]);Event.observe(li.down('a'),'click',this.handleDateCellClick);if(dt.getMonth()!=inNewShownDate.getMonth()){Element.addClassName(li,'niftydate_other_month')}
else if(dtISO==todayDateISO){Element.addClassName(li,(dtISO==selectedDateISO?'niftydate_today_selected_date':'niftydate_today'));}
else if(dtISO==selectedDateISO){Element.addClassName(li,'niftydate_selected_date');}
else if(compareDateWeeks(dt,this.mSelectedDate,this.mStartWeekday)){Element.addClassName(li,'niftydate_selected_week');}
dateLists[i%7].appendChild(li);dt.setDate(dt.getDate()+1);}
if(isFirstSetup){var callback=function(){var listHeight=Element.getHeight(dateLists[0]);dateLists.invoke('setStyle',{height:listHeight+'px'});this.mElement.style.height=(Element.getHeight(this.mElement)-1)+'px';dateLists.invoke('addClassName','animatedheight');if(this.mElement.style.visibility=='hidden'){Element.hide(this.mElement);this.mElement.style.visibility='';}}
setTimeout(callback.bind(this),10);}
else{var listHeight=Element.getHeight(dateLists[0]);dateLists.invoke('setStyle',{height:'0'});var callback=function(){oldDateLists.invoke('setStyle',{height:'0'});dateLists.invoke('setStyle',{height:listHeight+'px'});}
setTimeout(callback,10);}
this.mShownDate=inNewShownDate;replaceElementContents(this.mElement.down('span.niftydate_header'),this.mShownDate.formatDate(Loc.dateFormats.longMonthAndYear));this.mDateLinks=$$('#'+this.mElement.id+' ul.niftydate_days a');var cleanupCallback=function(){oldDateLists.each(function(elm){if(elm.parentNode)elm.remove();});this.mDateLinks=$$('#'+this.mElement.id+' ul.niftydate_days a');}
setTimeout(cleanupCallback.bind(this),1100);},setSelectedDate:function(inNewSelectedDate,inOptShouldNotify){var shouldNotify=(inOptShouldNotify!=undefined)?inOptShouldNotify:true;publisher().publish('SELECTED_DATE_WILL_CHANGE',this);if(!inNewSelectedDate){this.mWeekStartDate=new Date(this.mSelectedDate.getTime());this.mWeekStartDate.setDate(this.mWeekStartDate.getDate()-(this.mWeekStartDate.getDay()-this.mStartWeekday));if(parseInt(dateObjToISO8601(this.mWeekStartDate))>parseInt(dateObjToISO8601(this.mSelectedDate))){this.mWeekStartDate.setDate(this.mWeekStartDate.getDate()-7);}
if(shouldNotify)publisher().publish('SELECTED_DATE_CHANGED',this,{selectedDate:this.mSelectedDate,weekStartDate:this.mWeekStartDate,oldSelectedDate:this.mSelectedDate});return;}
if(inNewSelectedDate.getYear()!=this.mShownDate.getYear()||inNewSelectedDate.getMonth()!=this.mShownDate.getMonth()){this.mSelectedDate=inNewSelectedDate;this.setShownDate(new Date(inNewSelectedDate.getTime()));}
var now=new Date();var todayDateISO=parseInt(dateObjToISO8601(now));var selectedDateISO=parseInt(dateObjToISO8601(inNewSelectedDate));var startWeekday=this.mStartWeekday;this.mDateLinks.each(function(a){var dtISO=a.className.match(/niftydate_datecell_(\d{8})/)[1];var dt=createDateObjFromISO8601(dtISO);var li=a.up('li');li.className='';if(dt.getMonth()!=inNewSelectedDate.getMonth()){Element.addClassName(li,'niftydate_other_month')}
else if(dtISO==todayDateISO){Element.addClassName(li,(dtISO==selectedDateISO?'niftydate_today_selected_date':'niftydate_today'));}
else if(dtISO==selectedDateISO){Element.addClassName(li,'niftydate_selected_date');}
else if(compareDateWeeks(dt,inNewSelectedDate,startWeekday)){Element.addClassName(li,'niftydate_selected_week');}});var oldSelectedDate=this.mSelectedDate;this.mSelectedDate=inNewSelectedDate;this.mShownDate=inNewSelectedDate;if(this.mParentElement)replaceElementContents(this.mParentElement,inNewSelectedDate.formatDate(this.mParentDateFormat));this.mWeekStartDate=new Date(inNewSelectedDate.getTime());this.mWeekStartDate.setDate(this.mWeekStartDate.getDate()-(this.mWeekStartDate.getDay()-this.mStartWeekday));if(this.mWeekStartDate>inNewSelectedDate){this.mWeekStartDate.setDate(this.mWeekStartDate.getDate()-7);}
if(shouldNotify)publisher().publish('SELECTED_DATE_CHANGED',this,{selectedDate:new Date(this.mSelectedDate.getTime()),weekStartDate:this.mWeekStartDate,oldSelectedDate:oldSelectedDate});},setStartWeekday:function(inWeekdayInt){this.mStartWeekday=inWeekdayInt;this.drawWeekdayHeaders();this.setShownDate(new Date(this.mShownDate.getTime()));},handleMonthSkipButtonClick:function(inEvent){Event.stop(inEvent);var direction=Element.hasClassName(Event.findElement(inEvent,'a'),'niftydate_prev_month')?(-1):1;var dt=new Date(this.mShownDate.getTime());dt.setMonth(dt.getMonth()+direction);this.setShownDate(dt);return false;},handleDateCellClick:function(inEvent){Event.stop(inEvent);var elm=Event.findElement(inEvent,'a');var dtISO=elm.className.match(/niftydate_datecell_(\d{8})/)[1];var dt=createDateObjFromISO8601(dtISO);this.setSelectedDate(dt);this.hide();return false;},enableParentElement:function(){if(this.mParentElement)Event.observe(this.mParentElement,'click',this.handleParentElementClick);$(this.mParentElement).removeClassName('disabled');this.mEnabled=true;},disableParentElement:function(){if(this.mParentElement)Event.stopObserving(this.mParentElement,'click',this.handleParentElementClick);$(this.mParentElement).addClassName('disabled');this.mEnabled=false;}}
var BlockSpacer=Class.create();BlockSpacer.prototype={initialize:function(inElement,inParent,inOptVertical){this.mElement=$(inElement);this.mParent=inParent.mElement?inParent:$(inParent);this.mVertical=inOptVertical;Element.cleanWhitespace(this.mElement);this.zoomOut();},space:function(inOptTotalSize){if(!this.mElement.offsetParent||(IEFixes.isIE&&this.mElement.offsetWidth==0&&this.mElement.offsetHeight==0)){return false;}
if(this.mParent.mElement){if(!this.mParent.mSpacedBlocks){return false;}
if(this.mVertical){Element.setOffsetHeight(this.mElement,this.mParent.mElement.offsetHeight);}
else{Element.setOffsetWidth(this.mElement,this.mParent.mElement.offsetWidth);}
var nodes=$A(this.mParent.mElement.childNodes);if(nodes.length!=this.mParent.mElement.childNodes.length)return false;$A(this.mElement.childNodes).each(function(elm,i){if(nodes[i]){if(!Element.visible(nodes[i])){Element.hide(elm);}
else if(this.mVertical){Element.show(elm);Element.setOffsetHeight(elm,nodes[i].offsetHeight);}
else{Element.show(elm);Element.setOffsetWidth(elm,nodes[i].offsetWidth);}}}.bind(this));return true;}
if(!this.mSpacedBlocks){this.mSpacedBlocks=[];this.mSkippedBlocks=[];$A(this.mElement.childNodes).each(function(elm){if(elm.className&&Element.hasClassName(elm,'use_content_size')){this.mSkippedBlocks.push(elm);}
else if(elm.nodeName.toLowerCase()=='li'||elm.nodeName.toLowerCase()=='div'){this.mSpacedBlocks.push(elm);}}.bind(this));}
var pos=0;if(this.mVertical){pos=Element.getTop(this.mElement,this.mParent);}
else{pos=Element.getLeft(this.mElement,this.mParent);}
var parentSize=this.mParent[this.mVertical?'offsetHeight':'offsetWidth'];var totalSize=inOptTotalSize?inOptTotalSize:(parentSize-pos);if(!inOptTotalSize)this.mElement.style[this.mVertical?'height':'width']=(totalSize+2)+'px';this.mSkippedBlocks.each(function(elm){totalSize-=elm[this.mVertical?'offsetHeight':'offsetWidth'];}.bind(this));if(this.mZoomedItem>=0){this.mSpacedBlocks.each(function(elm,i){if(i==this.mZoomedItem){elm.style.display='';if(this.mVertical){Element.setOffsetHeight(elm,totalSize);}
else{Element.setOffsetWidth(elm,totalSize);}}
else{elm.style.display='none';}}.bind(this));return true;}
var columnSize=Math.floor(totalSize/this.mSpacedBlocks.length);var remainder=totalSize%this.mSpacedBlocks.length;var r=remainder;this.mSpacedBlocks.each(function(elm){var w=columnSize;if(r>0){w++;r--;}
if(this.mVertical){Element.setOffsetHeight(elm,w);}
else{Element.setOffsetWidth(elm,w);}}.bind(this));if((!this.mVertical)&&totalSize>100&&Math.abs(this.mSpacedBlocks[0].offsetTop-this.mSpacedBlocks.last().offsetTop)>10){this.space(--totalSize);}
return true;},zoomInOnItem:function(inItemIndex){this.mZoomedItem=inItemIndex;this.space();},zoomOut:function(){if(this.mSpacedBlocks)this.mSpacedBlocks.invoke('setStyle',{display:''});this.mZoomedItem=(-1);this.space();}}
var Button=Class.create({initialize:function(element,params)
{var params=arguments[1]||{};if(params.type)this.type=params.type;if(params.options)this.options=params.options;if(params.onExecute)this.onExecute=params.onExecute;if(!this.type)this.type='trigger';if(!this.options)this.options=[];this.element=$(element);this.element.observe('click',this.onElementClick.bind(this));if(params.value===undefined){for(var i=0,n=this.options.length;i<n;i++)
{var key=this.options[i];if(key&&this.hasClassName(key))this._value=key;}}else{this.setValue(params.value);}},onElementClick:function(e)
{e.stop();if(this.hasClassName('disabled'))return;this[this.type]();},onExecute:function()
{},getValue:function()
{return this._value;},setValue:function(value)
{this._value=value;var options=this.options;for(var i=0,n=options.length;i<n;i++)
{var option=options[i];if(option)this.setClassName(option,(option==value));}},hasClassName:function(key)
{return this.element.hasClassName(key);},setClassName:function(key,value)
{this.element[value?'addClassName':'removeClassName'](key);},trigger:function()
{this.onExecute(this);},toggle:function()
{var options=this.options;if(options.length==0)return;var idx=options.indexOf(this.getValue());if(idx==-1)idx=0;idx++;if(idx>=options.length)idx=0;this.setValue(options[idx]);this.onExecute(this);}});var InlineDeleteButton=Class.create();InlineDeleteButton.prototype={initialize:function(inParent,inCallback,optConfirm,optShowPoofs){bindEventListeners(this,['handleParentHover','handleParentOut','handleButtonClick']);this.mParent=$(inParent);this.mCallback=inCallback;this.mConfirm=(optConfirm!==undefined)?optConfirm:true;this.mShowPoofs=(optShowPoofs!==undefined)?optShowPoofs:true;observeEvents(this,this.mParent,{mouseover:'handleParentHover',mouseout:'handleParentOut'});},show:function(){if(!this.mElement){this.mElement=Builder.node('a',{href:'#',className:'inline_delete_button',style:'display:none',title:Loc.tags_remove_tag_dialog_ok},Loc.tags_remove_tag_dialog_ok);this.mElement.onclick=this.handleButtonClick;d.body.appendChild(this.mElement);observeEvents(this,this.mElement,{mouseover:'handleParentHover',mouseout:'handleParentOut'});}
Position.clone(this.mParent,this.mElement,{setWidth:false,setHeight:false,offsetLeft:(-9),offsetTop:(-10)});Element.show(this.mElement);Element.addClassName(this.mParent,'inlinedeletefocus');},hide:function(){Element.hide(this.mElement);Element.removeClassName(this.mParent,'inlinedeletefocus');},handleParentHover:function(inEvent){if(this.mTimer){clearTimeout(this.mTimer);delete this.mTimer;}
this.show();},handleParentOut:function(inEvent){if(this.mTimer){clearTimeout(this.mTimer);delete this.mTimer;}
this.mTimer=setTimeout(this.hide.bind(this),200);},handleButtonClick:function(inEvent){Event.stop(inEvent);if(this.mConfirm){if(!InlineDeleteButton.mConfirmDialog){InlineDeleteButton.mConfirmDialog=dialogManager().drawDialog('tags_remove_tag_dialog',['tags_remove_tag_dialog_description'],'tags_remove_tag_dialog_ok');}
targetedDialogManager().show(InlineDeleteButton.mConfirmDialog,null,this.handleConfirmDialogOK.bind(this),this.mParent);}else{this.handleConfirmDialogOK();}
return false;},handleConfirmDialogOK:function(){var callback=function(){this.hide(false);if(this.mCallback)this.mCallback(this.mParent);}.bind(this);if(this.mShowPoofs)
poof().showOverElement(this.mParent,callback);else
callback();},destroy:function(){Event.stopObserving(this.mParent,'mouseover',this.handleParentHover);Event.stopObserving(this.mParent,'mouseout',this.handleParentOut);if(this.mElement){Event.stopObserving(this.mElement,'mouseover',this.handleParentHover);Event.stopObserving(this.mElement,'mouseout',this.handleParentOut);}}}
var UploadProgressPlaceholder=Class.create();UploadProgressPlaceholder.prototype={mCheckInterval:1000,initialize:function(inElement,inUpdateID,inCallback){if(!UploadProgressPlaceholder.allPlaceholders)UploadProgressPlaceholder.allPlaceholders={};UploadProgressPlaceholder.allPlaceholders[inUpdateID]=this;this.mElement=$(inElement);this.mCallback=inCallback;this.mUpdateID=inUpdateID;if(arguments.length>1)Object.extend(this,arguments[1]);this.mTimer=setTimeout(this.sendUpdateRequest.bind(this),500);},sendUpdateRequest:function(){server().getUploadProgress(this.gotUpdateResponse.bind(this),this.mUpdateID);},gotUpdateResponse:function(q,r){if(!this.mTimer)return false;if(r.done){if(this.mCallback)this.mCallback(this,r);this.destroy();}
else if(SafariFixes.isWebKit&&this.mFrameFinishedLoading){if(this.mCallback)this.mCallback(this,{retry:true});}
else if(this.mFileSizeError||(r.error=='2')){if(this.mCallback)this.mCallback(this,{fileSizeError:true,maxFileSize:r.maxFileSizeInBytes||this.mMaxFileSize});}
else{if(this.mElement&&r['size']&&r.uploaded){if(Element.hasClassName(this.mElement,'progress_bar')){if(gDebug)notifier().print('File upload: '+Math.floor((r.uploaded/r['size'])*100)+'%');this.mElement.firstChild.style.width=((r.uploaded/r['size'])*this.mElement.offsetWidth)+'px';}
else{if(gDebug)notifier().print('File upload: '+Math.floor((r.uploaded/r.size)*100)+'%');var offset=Math.min(Math.floor((r.uploaded/r.size)*10),8)*this.mElement.offsetWidth;this.mElement.style.backgroundPosition=(offset*(-1))+'px 0';}}
else if(this.mElement){if(Element.hasClassName(this.mElement,'progress_bar'))this.mElement.firstChild.style.width='0';else this.mElement.style.backgroundPosition='0 0';}
this.mTimer=setTimeout(this.sendUpdateRequest.bind(this),this.mCheckInterval);}},cancel:function(){if(this.mTimer){clearTimeout(this.mTimer);this.mTimer=null;}},destroy:function(){this.cancel();delete UploadProgressPlaceholder.allPlaceholders[this.mUpdateID];}}
UploadProgressPlaceholder.handleUploadFrameLoad=function(){if(!UploadProgressPlaceholder.allPlaceholders)return true;$H(UploadProgressPlaceholder.allPlaceholders).each(function(ph){ph.value.mFrameFinishedLoading=true;});}
UploadProgressPlaceholder.handleFileSizeError=function(inMaxFileSizeString){if(!UploadProgressPlaceholder.allPlaceholders)return true;$H(UploadProgressPlaceholder.allPlaceholders).each(function(ph){ph.value.mFileSizeError=true;ph.value.mMaxFileSize=inMaxFileSizeString;});}
function addUploadFrame(){if(!$('image_upload_iframe')){d.body.appendChild(Builder.node('iframe',{name:'image_upload_iframe',id:'image_upload_iframe',src:'about:blank',style:'position:absolute;top:0;left:0;width:1px;height:1px;visibility:hidden'}));}
$('image_upload_iframe').show();}
function removeUploadFrame(){if($('image_upload_iframe'))Element.remove('image_upload_iframe');}
var BackgroundAnimator=Class.create();BackgroundAnimator.prototype={initialize:function(inElement,inFrameWidth,inTotalFrames,inFrameTimerLength){this.handleTimerFired=this.handleTimerFired.bind(this);this.mElement=$(inElement);this.mFrameWidth=inFrameWidth;this.mTotalFrames=inTotalFrames;this.mFrameTimerLength=inFrameTimerLength;this.mCurrentFrame=0;},start:function(){this.mElement.style.backgroundPosition='0 0';if(this.mTimer)clearTimeout(this.mTimer);this.mTimer=setTimeout(this.handleTimerFired,this.mFrameTimerLength);},stop:function(){if(this.mTimer){clearTimeout(this.mTimer);delete this.mTimer;}},handleTimerFired:function(){if(this.mTimer)clearTimeout(this.mTimer);this.mTimer=setTimeout(this.handleTimerFired,this.mFrameTimerLength);this.mCurrentFrame=(++this.mCurrentFrame%this.mTotalFrames);this.mElement.style.backgroundPosition='-'+(this.mCurrentFrame*this.mFrameWidth)+'px 0';}}
var PoofManager=Class.createWithSharedInstance('poof');PoofManager.prototype={mFrameDelay:100,mWidth:42,mHeight:52,initialize:function(){this.mElement=Builder.node('div',{id:'poof',style:'display:none'},["\u00A0"]);d.body.appendChild(this.mElement);if(arguments.length>0)Object.extend(this,arguments[0]);},showOverElement:function(inElement,inOptFinishedFunc){if(!inElement)return null;var elm=$(inElement);if(!elm)return null;Position.clone(elm,this.mElement,{setWidth:false,setHeight:false,offsetLeft:(elm.offsetWidth/2)-(this.mWidth/2),offsetTop:(elm.offsetHeight/2)-(this.mHeight/2)});this.showAtPoint(null,inOptFinishedFunc);},showAtPoint:function(inPoint,inOptFinishedFunc){if(window.unitTestHandler)unitTestHandler.messageFromJS_('poof');this.mFinishedFunc=inOptFinishedFunc;Element.setStyle(this.mElement,{backgroundPosition:'0px 0px',display:''});if(inPoint)Element.setStyle(this.mElement,{left:inPoint[0]+'px',top:inPoint[1]+'px'});this.mCurrentFrame=0;if(this.mTimer)clearTimeout(this.mTimer);this.mTimer=setTimeout(this.handleTimerFired.bind(this),this.mFrameDelay);},handleTimerFired:function(){if(this.mCurrentFrame<4){this.mCurrentFrame++;var x=this.mCurrentFrame*this.mWidth*(-1);this.mElement.style.backgroundPosition=x+'px 0px';this.mTimer=setTimeout(this.handleTimerFired.bind(this),this.mFrameDelay);}
else{Element.hide(this.mElement);if(this.mFinishedFunc)this.mFinishedFunc();delete this.mTimer;}}}
var ImageThumbnailManager=Class.createWithSharedInstance('imageThumbnailManager',true);ImageThumbnailManager.prototype={mImageThumbnails:[],initialize:function(){this.findThumbnails();},findThumbnails:function(){var thumbnailImages=$$('img.thumbnail');for(var i=0;i<thumbnailImages.length;i++){this.mImageThumbnails.push(new ImageThumbnail(thumbnailImages[i]));}},prepareForEditing:function(){this.mImageThumbnails.each(function(thumb){thumb.destroy();});this.mImageThumbnails=[];}}
var ImageThumbnail=Class.create();ImageThumbnail.prototype={initialize:function(inImage){bindEventListeners(this,['handleShowClick']);this.mImage=$(inImage);parentElm=this.mImage.parentNode;var sizeAnchorMatch=null;this.mFullSrc=this.mImage.getAttribute('longdesc')||this.mImage.getAttribute('name')||this.mImage.getAttribute('alt')||this.mImage.getAttribute('src');if(this.mFullSrc)sizeAnchorMatch=this.mFullSrc.match(/#(\d+)x(\d+)$/);if(sizeAnchorMatch)this.mEndSize=[parseInt(sizeAnchorMatch[1]),parseInt(sizeAnchorMatch[2])];if(this.mImage.getAttribute('alt')&&this.mImage.getAttribute('alt')!=''){this.mImage.setAttribute('title',this.mImage.getAttribute('alt'));}else if(this.mImage.getAttribute('title')&&this.mImage.getAttribute('title')!=''){this.mImage.setAttribute('title','');}
var cell=Builder.node('td');var fullsizeLink=Builder.node('div',{className:'fullsize_link'});this.mTable=Builder.node('table',{className:this.mImage.className,cellspacing:'0',cellpadding:'4'},[Builder.node('tbody',[Builder.node('tr',[cell]),Builder.node('tr',[Builder.node('td',[fullsizeLink,this.mImage.getAttribute('alt')||Loc.image_thumbnail_caption])])])]);parentElm.insertBefore(this.mTable,this.mImage);Element.remove(this.mImage);Element.removeClassName(this.mImage,'thumbnail');cell.appendChild(this.mImage);Event.observe(fullsizeLink,'mousedown',this.handleShowClick);Event.observe(this.mImage,'mousedown',this.handleShowClick);},destroy:function(){this.mImage.className=this.mTable.className;Element.remove(this.mImage);this.mTable.parentNode.insertBefore(this.mImage,this.mTable);Element.remove(this.mTable);Event.stopObserving(this.mImage,'mousedown',this.handleShowClick);this.mImage.name=this.mFullSrc;},handleShowClick:function(inEvent){if(!this.mEndSize)this.mEndSize=[d.viewport.getWidth(),d.viewport.getHeight()];var w=window.open(this.mFullSrc,'applewikiimg'+server().getNextUploadID(),'status=0,toolbar=0,resizable=1,scrollbars=1,width='+this.mEndSize[0]+',height='+this.mEndSize[1]);w.moveTo(0,0);}}
var FavoriteIconsManager=Class.createWithSharedInstance('favoriteIconsManager',true);FavoriteIconsManager.prototype={initialize:function()
{this.icons=$$('.favorite-icon').map(function(element)
{return new FavoriteIcon(element);});}}
var FavoriteIcon=Class.create({initialize:function(element)
{bindEventListeners(this,['onElementClick']);this.element=$(element);if(this.element.hasClassName('active')){this.element.setAttribute('title',Loc.mark_as_not_favorite);}else{this.element.setAttribute('title',Loc.mark_as_favorite);}
this.element.tabindex='0';this.element.role='button';this.element.observe('click',this.onElementClick);this.uid=this.element.getAttribute('name');},onElementClick:function(e)
{e.stop();this.toggle();},toggle:function()
{this.isSelected()?this.deselect():this.select();},select:function()
{this.element.setAttribute('title',Loc.mark_as_not_favorite);this.element.addClassName('active');server().preferences.addUsersFavorite(invalidate,this.uid);publisher().publish('DID_STAR_PAGE',this);},deselect:function()
{this.element.setAttribute('title',Loc.mark_as_favorite);this.element.removeClassName('active');server().preferences.removeUsersFavorite(invalidate,this.uid);publisher().publish('DID_UNSTAR_PAGE',this);},isSelected:function()
{return this.element.hasClassName('active');}});var HintedTextField=Class.create();HintedTextField.prototype={initialize:function(inElement,inHintStr){bindEventListeners(this,['handleFocus','handleBlur']);this.mElement=$(inElement);this.mHintStr=inHintStr;if(!this.getFocusState())this.addHint();observeEvents(this,this.mElement,{focus:'handleFocus',blur:'handleBlur'});},addHint:function(){if(this.mElement.value==''){Element.addClassName(this.mElement,'hinted');this.mElement.value=Loc[this.mHintStr]||this.mHintStr;}},getFocusState:function(){if(window.getSelection){var sel=window.getSelection();if(!sel)return false;return(sel.anchorNode&&Element.descendantOf(this.mElement,sel.anchorNode)||(sel.rangeCount>0&&sel.getRangeAt(0).intersectsNode&&sel.getRangeAt(0).intersectsNode(this.mElement)));}
else if(d.selection&&d.selection.createRange){var rng=d.selection.createRange();if(!rng)return false;return(rng.parentElement()==this.mElement);}
return false;},getValue:function(){return(Element.hasClassName(this.mElement,'hinted')?'':this.mElement.value);},setValue:function(inValue){Element.removeClassName(this.mElement,'hinted');this.mElement.value=inValue;this.addHint();},handleFocus:function(inEvent){if(Element.hasClassName(this.mElement,'hinted')){this.mElement.value='';Element.removeClassName(this.mElement,'hinted');}},handleBlur:function(inEvent){this.addHint();}}
var SearchFieldBase=Class.create();SearchFieldBase.prototype={mClickedItemCallback:null,mStartedItemSearchCallback:null,mSearchCancelledCallback:null,mResultTable:null,mPositionResults:true,mHeaderElement:null,mMinQueryChars:1,mInterval:500,mNumberOfEntries:20,mSortKey:null,mTrapTabs:true,mShowPlaceholderStrings:false,mCaptureReturnChar:true,mSelectOnClick:true,initialize:function(inSearchField){bindEventListeners(this,['handleSafariSearch','handleKeypress','handleChanged','mousedOverUser','mousedOutUser','clickedUser']);this.mSearchField=$(inSearchField);if(arguments.length>1)Object.extend(this,arguments[1]);if(!this.mResultTable){this.mResultTable=Builder.node('table',{className:'search_field_results',style:'display:none'},[Builder.node('tbody')]);d.body.appendChild(this.mResultTable);}
this.mIsReallyTable=(this.mResultTable.nodeName.toLowerCase()=='table');observeEvents(this,this.mSearchField,{keydown:'handleKeypress',change:'handleChanged'});if(SafariFixes.isWebKit&&(this.mSearchField.type=='search'))Event.observe(this.mSearchField,'search',this.handleSafariSearch);},handleSafariSearch:function(e){if(Event.element(e).value=='')this.runQuery();},handleKeypress:function(e){switch(e.keyCode){case Event.KEY_DOWN:this.suggestSibling('nextSibling');Event.stop(e);break;case Event.KEY_UP:this.suggestSibling('previousSibling');Event.stop(e);break;case Event.KEY_TAB:case Event.KEY_RETURN:case 188:if(e.keyCode==Event.KEY_TAB&&this.mSearchField.value=='')return true;if(e.keyCode==Event.KEY_RETURN&&!this.mCaptureReturnChar)return true;this.handleChanged(e);if(e.keyCode==188||this.mTrapTabs)Event.stop(e);break;case Event.KEY_ESC:this.mSearchField.value='';this.mLastQuery=null;this.mRows=null;if(this.mSearchCancelledCallback)this.mSearchCancelledCallback();break;default:if(!this.mTimer)this.mTimer=setTimeout(this.runQuery.bind(this),this.mInterval);}},handleChanged:function(e){if(this.mSearchField.value!=''){this.selectSuggestedUID();Element.hide(this.mResultTable);}},suggestSibling:function(inKey){var elm=$(this.mResultTable.id+'_'+(this.mSuggestedUID||''));if(elm&&elm.parentNode[inKey]){this.suggestUID(elm.parentNode[inKey].firstChild.dataSource.uid);}
else if((!elm)&&inKey=="nextSibling"&&this.mRows&&this.mRows.length>0){this.suggestUID(this.mRows[0].uid);}
else if(inKey=='previousSibling'&&this.mSuggestedUID==this.mRows[0].uid){this.suggestUID(null);}},suggestUID:function(inUID){Element.removeClassName(this.mResultTable.id+'_'+this.mSuggestedUID,'suggested');this.mSuggestedUID=inUID;if(inUID)Element.addClassName(this.mResultTable.id+'_'+inUID,'suggested');},selectSuggestedUID:function(){this.mChosenUID=this.mSuggestedUID;if(this.mChosenUID){var chosenElm=$(this.mResultTable.id+'_'+this.mChosenUID);this.mChosenDataSource=chosenElm.dataSource;if(this.mPositionResults){Element.hide(this.mResultTable);this.mSearchField.value=chosenElm.firstChild.nodeValue;}
if(this.mClickedItemCallback)this.mClickedItemCallback(this.mChosenUID,this.mChosenDataSource.url);}
else if(!Element.hasClassName(this.mSearchField,'hinted')){if(this.mClickedItemCallback)this.mClickedItemCallback($F(this.mSearchField),null);}
if(this.mTimer){clearTimeout(this.mTimer);this.mTimer=null;}},mousedOverUser:function(e){if(this.mSelectOnClick)this.suggestUID(Event.findElement(e,(this.mIsReallyTable?'td':'a')).dataSource.uid);},mousedOutUser:function(e){},clickedUser:function(e){this.suggestUID(Event.findElement(e,(this.mIsReallyTable?'td':'a')).dataSource.uid);if(this.mSelectOnClick)this.selectSuggestedUID();},constructQuery:function(inSearchString){},runQuery:function(){if($F(this.mSearchField)!=this.mLastQuery){this.mSuggestedUID=null;this.mRows=new Array();this.draw();if(this.mShowPlaceholderStrings){replaceElementContents(this.mResultTable,Builder.node('li',{className:'search_placeholder busy_field'},[Builder.node('a',{href:'#',onclick:invalidate},Loc.link_popup_searching_progress)]));}
if(this.mPrefetch||($F(this.mSearchField).length>=this.mMinQueryChars)){Element.addClassName(this.mSearchField,'busy_field');if(this.mStartedItemSearchCallback)this.mStartedItemSearchCallback();this.constructQuery($F(this.mSearchField));}
else{this.mTimer=null;if(this.mSearchCancelledCallback)this.mSearchCancelledCallback();}}
else{this.mTimer=null;}
this.mLastQuery=$F(this.mSearchField);},gotSearchResult:function(inRequestObj,inResponseObj){this.mRows=inResponseObj;if(this.mSortKey)Array.sortArrayUsingKey(this.mRows,this.mSortKey);if(this.mPrefetch&&(!this.mCachedRows)){this.mCachedRows=inResponseObj;Element.removeClassName(this.mSearchField,'busy_field');}
else{this.draw();}
this.mTimer=null;this.runQuery();if(this.mSearchResultCallback)this.mSearchResultCallback(inResponseObj);},handleError:function(inFaultCode,inFaultString){this.mTimer=null;},getDisplayString:function(inRow){},updatePosition:function(){if(this.mPositionResults){var cloneOptions={setHeight:false,offsetTop:Element.getHeight(this.mSearchField)};Position.clone(this.mSearchField,this.mResultTable,cloneOptions);}},draw:function(){this.updatePosition();if(this.mPositionResults)Element.hide(this.mResultTable);if(this.mHeaderElement)Element.hide(this.mHeaderElement);removeAllChildNodes(this.mIsReallyTable?this.mResultTable.firstChild:this.mResultTable);this.mSuggestedUID=null;if(this.mShowPlaceholderStrings&&(this.mRows.length==0)){this.mResultTable.appendChild(Builder.node('li',[Builder.node('a',{href:'#',onclick:invalidate,className:'search_placeholder'},$F('no_results_str'))]));}
this.mRows.each(function(row){row.displayString=this.getDisplayString(row);if(row.displayString!=''){if(this.mPositionResults)Element.show(this.mResultTable);if(this.mHeaderElement)Element.show(this.mHeaderElement);var currentCell=Builder.node((this.mIsReallyTable?'td':'a'),{id:this.mResultTable.id+'_'+row.uid});currentCell.style.cursor='pointer';currentCell.dataSource=row;this.drawCell(currentCell);if(this.mIsReallyTable){this.mResultTable.firstChild.appendChild(Builder.node('tr',[currentCell]));}
else{currentCell.href=row.url;this.mResultTable.appendChild(Builder.node('li',[currentCell]));}
observeEvents(this,currentCell,{click:'clickedUser',mouseover:'mousedOverUser',mouseout:'mousedOutUser'});}}.bind(this));Element.removeClassName(this.mSearchField,'busy_field');},drawCell:function(inCell){replaceElementContents(inCell,inCell.dataSource.displayString);}}
var QuickSearchField=Class.create();Object.extend(Object.extend(QuickSearchField.prototype,SearchFieldBase.prototype),{mCaptureReturnChar:false,getDisplayString:function(inRow){return inRow.title;},constructQuery:function(inSearchString){if(this.mQueryStartCallback)this.mQueryingCallback();return server().search.getEntriesForQuickSearch([this.gotSearchResult.bind(this),this.handleError.bind(this)],inSearchString,uid().mBasePath);}});var TextInputObserver=Class.create({initialize:function(element,options)
{var options=Object.extend({callback:Prototype.emptyFunction,duration:0.5},arguments[1]||{});this.onTimerExecute=this.onTimerExecute.bind(this);this.onValueChange=this.onValueChange.bindAsEventListener(this);this.timer=new PeriodicalExecuter(this.onTimerExecute,options.duration);this.timer.stop();this.element=$(element);this.element.observe('keyup',this.onValueChange);this.element.observe('change',this.onValueChange);if(SafariFixes.isWebKit&&(this.element.type=='search')){this.element.observe('search',this.onValueChange);}
this.callback=options.callback;},onValueChange:function()
{this.timer.stop();this.timer.start();},onTimerExecute:function()
{this.timer.stop();this.callback(this.element.getValue());}});var SizeObserver=Class.create();Object.extend(Object.extend(SizeObserver.prototype,Abstract.TimedObserver.prototype),{getValue:function(){return this.element.offsetHeight;}});var SplitView=Class.create();SplitView.prototype={mMaintainTotalHeight:false,mMinimumHeight:80,mMaximumHeight:10000,mInverseDelta:false,initialize:function(inElement){bindEventListeners(this,['handleMouseDown','handleMouseMove','handleMouseUp']);this.mElement=$(inElement);Element.cleanWhitespace(this.mElement);var nodes=this.mElement.childNodes;if(nodes.length>2)this.mViews=new Array(nodes.item(0),nodes.item(2));this.mSplitter=nodes.item(1);if(arguments.length>1)Object.extend(this,arguments[1]);Event.observe(this.mSplitter,'mousedown',this.handleMouseDown);this.mElement.onselectstart=invalidate;},handleMouseDown:function(e){this.mInitialHeight=parseInt(this.mViews[0].style.height);if(isNaN(this.mInitialHeight))this.mInitialHeight=Element.getHeight(this.mViews[0]);this.mInitialPos=e.clientY;observeEvents(this,d,{mousemove:'handleMouseMove',mouseup:'handleMouseUp'});Event.stop(e);if(this.mStartCallback)this.mStartCallback();},handleMouseMove:function(e){var height=this.mInitialHeight;if(this.mInverseDelta){height-=e.clientY-this.mInitialPos;}
else{height-=this.mInitialPos-e.clientY;}
height=Math.max(height,this.mMinimumHeight);height=Math.min(height,this.mMaximumHeight);if(this.mMaintainTotalHeight){var delta=height-parseInt(this.mViews[0].style.height||''+this.mViews[0].offsetHeight);var otherHeight=parseInt(this.mViews[1].style.height)-delta;if(otherHeight<this.mMinimumHeight){delta=this.mMinimumHeight-otherHeight;height-=delta;otherHeight+=delta;}
this.mViews[1].style.height=otherHeight+'px';}
this.mViews[0].style.height=height+'px';if(this.mDuringCallback)this.mDuringCallback(height);},handleMouseUp:function(e){Event.stopObserving(d,'mousemove',this.handleMouseMove);Event.stopObserving(d,'mouseup',this.handleMouseUp);if(this.mEndCallback)this.mEndCallback();}}
var ViewSprings=Class.create();ViewSprings.prototype={initialize:function(inElement,inOptCallback,inOptOtherElement){this.handleWindowResize=this.handleWindowResize.bindAsEventListener(this);this.mElement=$(inElement);this.mCallback=inOptCallback;if(inOptOtherElement)this.mOtherElement=$(inOptOtherElement);this.boing();Event.observe(window,'resize',this.handleWindowResize);},boing:function(){var h=this.mOtherElement?Math.max(this.mElement.offsetHeight,this.mOtherElement.offsetHeight):this.mElement.offsetHeight;h=d.viewport.getHeight()-(d.body.offsetHeight-h);if(h<300)h=300;this.mElement.style.height=h+'px';var lies=d.body.offsetHeight-d.body.parentNode.scrollHeight;if(lies!=0)this.mElement.style.height=(h+lies)+'px';if(this.mCallback)this.mCallback();},handleWindowResize:function(inEvent){this.boing();},destroy:function(){Event.stopObserving(window,'resize',this.handleWindowResize);}}
var PopupManager=Class.createWithSharedInstance('popupManager');PopupManager.prototype={mHideDelay:350,mShowDuration:0,mHideDuration:0.2,initialize:function(){bindEventListeners(this,['handleMouseOut','handleMouseOver','handleWindowClick','handleWindowKeypress','handleKeyboardFocus']);if(arguments.length>0)Object.extend(this,arguments[0]);},show:function(inParent,inElement,inOptOffset,inFade,inOptCallback){var offsetLeft=0;var offsetTop=inOptOffset||0;if(inOptOffset&&inOptOffset.constructor==Array){offsetLeft=inOptOffset[0];offsetTop=inOptOffset[1];}
var inFade=(arguments.length>3?arguments[3]:gAnimate);this.hide(false);this.clearTimer();this.mActiveParent=$(inParent);this.mActiveElement=$(inElement);this.mCallback=inOptCallback;if(this.mActiveParent){this.mActiveElement.style.position='absolute';var cloneOptions={setWidth:false,setHeight:false,offsetLeft:offsetLeft,offsetTop:offsetTop};Position.clone(this.mActiveParent,this.mActiveElement,cloneOptions);if(IEFixes.isIE){var currentLeft=parseInt(this.mActiveElement.style.left);if(currentLeft<0){this.mActiveElement.style.left=(currentLeft-offsetLeft)+'px';}}
Element.addClassName(this.mActiveParent,'active');}
var bottomOfWindow=d.viewport.getScrollOffsets()[1]+d.viewport.getHeight();var elementTop=parseInt(this.mActiveElement.style.top);this.mActiveElement.style.top='0px';var elementHeight=Element.getInvisibleSize(this.mActiveElement)[1]+40;this.mActiveElement.style.top=Math.max(Math.min(elementTop,(bottomOfWindow-elementHeight)),30)+'px';this.mActiveElement.style.opacity='';if(IEFixes.isIE)this.mActiveElement.style.filter='';Event.observe(this.mActiveParent,'mouseout',this.handleMouseOut);Event.observe(this.mActiveElement,'mouseout',this.handleMouseOut);Event.observe(this.mActiveParent,'mouseover',this.handleMouseOver);Event.observe(this.mActiveElement,'mouseover',this.handleMouseOver);if(inFade){Element.hide(this.mActiveElement);if(this.mEffect)this.mEffect.cancel();this.mEffect=new Effect.Appear(this.mActiveElement,{duration:this.mShowDuration});}
else{Element.show(this.mActiveElement);}
Event.observe(d.body.firstChild,'mousedown',this.handleWindowClick);Event.observe(d,'keypress',this.handleWindowKeypress);},createPopupElement:function(inOptClassName,inOptID){var sClassName='popup';if(inOptClassName)sClassName+=' '+inOptClassName;var elm=Builder.node('ul',{className:sClassName,style:'display:none'});if(inOptID)elm.id=inOptID;d.body.appendChild(elm);return elm;},itemWithTitle:function(inPopup,inTitle,inOptHref,inOptCallback,inOptRel){var a=Builder.node('a',{className:'popuplink',title:'',href:inOptHref||'javascript:void(0);'},[inTitle]);if(inOptRel)a.setAttribute('rel',inOptRel);if(inOptCallback)a.onclick=inOptCallback;var elm=Builder.node('li',[a]);inPopup.appendChild(elm);return a;},divider:function(inPopup){var li=Builder.node('li',{className:'popupDivider'},'\u00A0');inPopup.appendChild(li);return li;},hide:function(){if(this.mEffect)this.mEffect.cancel();if(this.mActiveElement){var inFade=(arguments.length>0?arguments[0]:gAnimate);Event.stopObserving(this.mActiveParent,'mouseout',this.handleMouseOut);Event.stopObserving(this.mActiveElement,'mouseout',this.handleMouseOut);Event.stopObserving(this.mActiveParent,'mouseover',this.handleMouseOver);Event.stopObserving(this.mActiveElement,'mouseover',this.handleMouseOver);if(inFade){this.mEffect=new Effect.Fade(this.mActiveElement,{duration:this.mHideDuration});}
else{Element.hide(this.mActiveElement);}
if(this.mChildManager)this.mChildManager.hide(inFade);Element.removeClassName(this.mActiveParent,'active');this.mActiveParent=null;this.mActiveElement=null;Event.stopObserving(d,'mousedown',this.handleWindowClick);Event.stopObserving(d,'keypress',this.handleWindowKeypress);if(this.mCallback)this.mCallback();}
$$('.popup').each(function(popupElm){popupElm.hide();});},handleMouseOut:function(inEvent){Event.stop(inEvent);this.setTimer();},handleMouseOver:function(inEvent){Event.stop(inEvent);this.clearTimer();},setTimer:function(inDelay){this.clearTimer();this.mTimer=setTimeout(this.handleTimerFired.bind(this),inDelay||this.mHideDelay);},clearTimer:function(){if(this.mTimer)clearTimeout(this.mTimer);this.mTimer=null;},handleTimerFired:function(){this.hide();},handleWindowClick:function(e){var elm=Event.element(e);if(elm&&Element.hasClassName(elm,'popuplink'))return true;this.setTimer(100);},handleWindowKeypress:function(e)
{if(e.keyCode==Event.KEY_ESC){this.setTimer(100);}},handleKeyboardFocus:function(e){}}
var Tabset=Class.create();Tabset.prototype={initialize:function(){if(arguments.length>0)Object.extend(this,arguments[0]);this.tabs=[];this.selectedPanel=null;this.selectedTrigger=null;bindEventListeners(this,['handleClick']);},addTab:function(inID,inLabel,inTabContentNode){this.tabs.push({id:inID,label:inLabel,node:inTabContentNode})},getTabset:function(){var tabsNode=Builder.node('ul');var tabContainerNode=Builder.node('div',{className:'tabpanels'});var tabsetNode=Builder.node('div',{className:'tabgroup'},[Builder.node('div',{className:'tabs'},[tabsNode]),tabContainerNode])
for(var i=0,c=this.tabs.length;i<c;i++){var tab=this.tabs[i];var trigger=Builder.node('a',{href:('#'+tab.id)},[tab.label]);var panel=tab.node;panel.setAttribute('id',tab.id);Element.addClassName(panel,'tabpanel');tabsNode.appendChild(Builder.node('li',{},[trigger]));if(c==1)trigger.style.visibility='hidden';Event.observe(trigger,'click',this.handleClick);tabContainerNode.appendChild(panel);if(!i){this.selectTab(trigger,panel);Element.addClassName(trigger,'first');}else if(i==c-1){Element.addClassName(trigger,'last');}}
return tabsetNode;},handleClick:function(inEvent){Event.stop(inEvent);var trigger=Event.element(inEvent);var panel=$(trigger.getAttribute('href').replace('#',''));this.selectTab(trigger,panel);},selectTab:function(inTrigger,inPanel){inTrigger.blur();inPanel.focus();if(this.selectedTrigger==inTrigger)return;Element.removeClassName(this.selectedTrigger,'selected');Element.removeClassName(this.selectedPanel,'tabpanelselected');Element.addClassName(inTrigger,'selected');Element.addClassName(inPanel,'tabpanelselected');this.selectedTrigger=inTrigger;this.selectedPanel=inPanel;}};var CollapsibleList=Class.create({initialize:function(element,collapsedCount)
{this.element=$(element);this.list=this.element.down('.collapsible-list');this.button=this.element.down('.collapsible-list-toggle');if(this.button){this.button.down('a').observe('click',this.onButtonClick.bindAsEventListener(this));}
this.collapsedCount=(collapsedCount!=undefined)?collapsedCount:5;this._calculateHeights();this._resizeList();},onButtonClick:function(e)
{e.stop();this.toggle();},insertListItem:function(element)
{this.list.insert(element);this._calculateHeights();this._resizeList();},removeListItem:function(element)
{element.remove();this._calculateHeights();this._resizeList();},isCollapsed:function()
{return this.list.hasClassName('collapsed');},toggle:function()
{this.isCollapsed()?this.expand():this.collapse();},expand:function()
{if(!this.isCollapsed())return;this.list.removeClassName('collapsed');this.button.down('a').addClassName('active');this.button.down('.label').update(Loc.search_saved_less);this._resizeListWithAnimation(this.collapsedHeight,this.expandedHeight);},collapse:function()
{if(this.isCollapsed())return;this.list.addClassName('collapsed');this.button.down('a').removeClassName('active');this.button.down('.label').update(Loc.search_saved_more);this._resizeListWithAnimation(this.expandedHeight,this.collapsedHeight);},_calculateHeights:function()
{var nodes=this.list.childElements();this.expandedCount=nodes.length;this.collapsedHeight=0;this.expandedHeight=0;for(var i=0,n=this.expandedCount;i<n;i++)
{var node=nodes[i];this.expandedHeight+=node.getHeight();if(i<this.collapsedCount){this.collapsedHeight=this.expandedHeight;}}
if(this.button){(this.expandedCount>this.collapsedCount)?this.button.show():this.button.hide();}},_resizeList:function(toValue)
{if(toValue==undefined){var toValue=this.isCollapsed()?this.collapsedHeight:this.expandedHeight;}
this.list.setStyle({maxHeight:'',height:(toValue).round()+'px'});},_resizeListWithAnimation:function(fromValue,toValue)
{if(this.effect)this.effect.cancel();this.effect=new Effect.Tween(this.list,fromValue,toValue,{duration:0.5},function(value){this.setStyle({height:(value).round()+'px'});});}});var ACLChooser=Class.create({initialize:function(element)
{this.element=$(element);this.onAccessLevelChange=this.onAccessLevelChange.bindAsEventListener(this);this.onUserPermissionListChange=this.onUserPermissionListChange.bind(this);this.element.select('.acl-chooser-radio').invoke('observe','click',this.onAccessLevelChange);this.element.down('.acl-chooser-checkboxes').observe('click',this.onAccessLevelChange);this.userlist=new UserPermissionList(this.element.down('.acl-chooser-private-userlist'),{mChangeCallback:this.onUserPermissionListChange});},reset:function()
{this.element.down('.acl-chooser-checkboxes-read').checked=false;this.element.down('.acl-chooser-checkboxes-write').checked=false;this.element.down('.acl-chooser-private-userlist').select('li').invoke('remove');this.setAccessLevel(ACLChooser.ACCESS_PUBLIC);},getACLs:function()
{var acls={read:'unauthenticated',write:'unauthenticated'};if(this.getAccessLevel()==ACLChooser.ACCESS_PUBLIC){if(this.element.down('.acl-chooser-checkboxes-read').checked){acls.read="non-member";}
if(this.element.down('.acl-chooser-checkboxes-write').checked){acls.write="non-member";var specific=this.element.down('.acl-chooser-public-write-radio-specific');if(specific&&specific.checked){var userlist=this.element.down('.acl-chooser-public-write-userlist');if(userlist)acls.write=userlist.select('li a').invoke('getAttribute','title');}}}else{var userlist=this.element.down('.acl-chooser-private-userlist');acls.read=userlist.select('li a.readonly').invoke('getAttribute','title');acls.write=userlist.select('li a.readwrite').invoke('getAttribute','title');}
return acls;},getAccessLevel:function()
{var radio=this.element.select('.acl-chooser-radio').find(function(r){return r.checked;});if(radio){return radio.value;}},setAccessLevel:function(name)
{this.element.select('.acl-chooser-section').each(function(section){var radio=section.down('.acl-chooser-radio');if(radio.value==name){radio.checked=true;section.addClassName('selected');}else{radio.checked=false;section.removeClassName('selected');}});var cbEmail=this.element.down('.acl-chooser-private-notification input[type="checkbox"]');var cbGroup=this.element.down('.acl-chooser-checkboxes');var cbRead=this.element.down('.acl-chooser-checkboxes-read');var cbWrite=this.element.down('.acl-chooser-checkboxes-write');if(name==ACLChooser.ACCESS_PUBLIC){cbEmail.disable();cbGroup.removeClassName('disabled');cbRead.enable();if(cbRead.checked){cbWrite.checked=true;cbWrite.disable();}else{cbWrite.enable();}}else{cbEmail.enable();cbGroup.addClassName('disabled');cbRead.disable();cbWrite.disable();}
(cbWrite.checked)?this.element.addClassName('public-authenticated-write'):this.element.removeClassName('public-authenticated-write');var rbAnyoneWrite=this.element.down('.acl-chooser-public-write-radio-anyone');var rbSpecificWrite=this.element.down('.acl-chooser-public-write-radio-specific');if(rbAnyoneWrite&&rbSpecificWrite){(rbAnyoneWrite.checked)?this.element.addClassName('public-authenticated-write-anyone'):this.element.removeClassName('public-authenticated-write-anyone');(rbSpecificWrite.checked)?this.element.addClassName('public-authenticated-write-specific'):this.element.removeClassName('public-authenticated-write-specific');}
publisher().publish('ACL_CHOOSER_CHANGE',this);},onAccessLevelChange:function(e)
{var level=this.getAccessLevel();if(level){this.setAccessLevel(level);}},onUserPermissionListChange:function()
{publisher().publish('ACL_CHOOSER_CHANGE',this);}});ACLChooser.ACCESS_PUBLIC='public';ACLChooser.ACCESS_PRIVATE='private';Position.super__clone=Position.clone;Position.ieCompatibleClone=function(source,target){var options=Object.extend({setLeft:true,setTop:true,setWidth:true,setHeight:true,offsetTop:0,offsetLeft:0},arguments[2]||{});if(!IEFixes.isIE)return Position.super__clone(source,target,options);var targetElm=$(target);if(targetElm.parentNode!=document.body)return Position.super__clone(source,target,options);var p=$(source).viewportOffset();targetElm.style.position='absolute';if(options.setLeft)targetElm.style.left=(p[0]-document.body.offsetLeft+options.offsetLeft)+'px';if(options.setTop)targetElm.style.top=(p[1]-document.body.offsetTop+options.offsetTop)+'px';if(options.setWidth)targetElm.style.width=$(source).offsetWidth+'px';if(options.setHeight)targetElm.style.height=$(source).offsetHeight+'px';}
Position.clone=function(source,target){var options=arguments[2]||{};if(!options.limitWithScrollbars)return Position.ieCompatibleClone(source,target,options);var scrolledParent=null;var elm=source;if(elm.ownerDocument&&(elm.ownerDocument!=document)&&elm.ownerDocument.defaultView){scrolledParent=elm.ownerDocument.defaultView.frameElement;}
while(!scrolledParent&&elm&&elm.parentNode&&(elm.nodeName.toLowerCase()!='body')){if(elm.scrollTop&&elm.scrollTop>0){scrolledParent=elm;}
else{elm=elm.parentNode;}};if(!scrolledParent)return Position.ieCompatibleClone(source,target,options);var parentTop=Element.getTop(scrolledParent);Position.ieCompatibleClone(source,target,options);if(parseFloat(target.style.top)<parentTop)target.style.top=parentTop+'px';}
Object.extend(Element,{getLeft:function(inElement,inOptParent){var parent=inOptParent?$(inOptParent):null;var currentNode=$(inElement);var currentLeft=0;while(currentNode){currentLeft+=currentNode.offsetLeft;currentNode=currentNode.offsetParent;if(parent&&currentNode==parent){currentNode=null;}
if(currentNode&&!IEFixes.isIE&&currentNode.nodeName.toLowerCase()=='body'){currentNode=null;}}
return currentLeft;},getTop:function(inElement,inOptParent){var parent=inOptParent?$(inOptParent):null;var currentNode=$(inElement);var currentTop=0;while(currentNode){currentTop+=currentNode.offsetTop;currentNode=currentNode.offsetParent;if(parent&&currentNode==parent){currentNode=null;}
if(currentNode&&!IEFixes.isIE&&currentNode.nodeName.toLowerCase()=='body'){currentNode=null;}}
return currentTop;},setOffsetHeight:function(element,height){element=$(element);if(height){element.style.height=height+'px';}
else{height=parseInt(element.style.height);}
var actual=Element.getHeight(element);element.style.height=(height-(actual-height))+'px';},setOffsetWidth:function(element,width){element=$(element);if(width){element.style.width=width+'px';}
else{width=parseInt(element.style.width);}
var actual=element.offsetWidth;element.style.width=(width-(actual-width))+'px';},getInvisibleSize:function(inElement){var elm=$(inElement);if(Element.visible(inElement))return[Element.getWidth(inElement),Element.getHeight(inElement)];elm.style.visibility='hidden';Element.show(elm);var width=elm.offsetWidth;var height=Element.getHeight(elm);Element.hide(elm);elm.style.visibility='';return[width,height];},getInvisibleHeight:function(inElement){return Element.getInvisibleSize(inElement)[1];},isChild:function(inChildElement,inParentElement){return Element.descendantOf(inChildElement,inParentElement);},unwrap:function(inChildElm,inSelector,inTagBuilderCallback,inOptParentElm){inChildElm=$(inChildElm);var parentElm=inOptParentElm||inChildElm.up(inSelector);if(parentElm){var ancestor=$A(parentElm.childNodes).detect(function(elm){return(elm==inChildElm||inChildElm.descendantOf(elm));});if(ancestor&&ancestor.previousSibling){var subelm=inTagBuilderCallback();while(ancestor.previousSibling){var sibling=ancestor.previousSibling;Element.remove(sibling);insertAtBeginning(sibling,subelm);}
insertAtBeginning(subelm,parentElm);}
if(ancestor&&ancestor.nextSibling){var subelm=inTagBuilderCallback();while(ancestor.nextSibling){var sibling=ancestor.nextSibling;Element.remove(sibling);subelm.appendChild(sibling);}
parentElm.appendChild(subelm);}
if(ancestor!=inChildElm){Element.unwrap(inChildElm,inSelector,inTagBuilderCallback,ancestor);}
if(!inOptParentElm){promoteElementChildren(parentElm);promoteElementChildren(inChildElm);}}},reload:function(inElement,inCallback,optUrl){var elm=$(inElement);var inCallback=inCallback||Prototype.emptyFunction;if(!elm||!elm.id){inCallback(false);return false;}
var url=optUrl||(window.location.pathname+window.location.search);var reloadFrame=Builder.node('iframe',{name:'element_reload_'+server().getNextUploadID(),style:'position:absolute;top:0;left:0;width:1px;height:1px;visibility:hidden',src:'about:blank'});d.body.appendChild(reloadFrame);var frameWindow=reloadFrame.contentWindow;var maybeLoadedCallback=function(){if(frameWindow.document&&frameWindow.document.body){var req=new Ajax.Request(url,{method:'get',onSuccess:function(inTransport){var bodyTextMatch=inTransport.responseText.replace(/[\r\n]/gm,'').match(/<body[^>]*>(.+)<\/body>/);if(bodyTextMatch){frameWindow.document.body.innerHTML=bodyTextMatch[1];var replacementElement=frameWindow.document.getElementById(elm.id);if(replacementElement){elm.update(replacementElement.innerHTML);inCallback(true);}
else{inCallback(false);}}
else{inCallback(false);}
Element.remove(reloadFrame);}});}
else{setTimeout(maybeLoadedCallback,250);}}
setTimeout(maybeLoadedCallback,750);},enableLinkIfAvailable:function(inElement,inOptCallback){var elm=$(inElement);if(!elm)return;var availability_url=elm.getAttribute('name')||elm.getAttribute('href');if(availability_url)
{var href=elm.getAttribute('href');elm.addClassName('disabled');elm.setAttribute('href','#');new Ajax.Request(availability_url,{onComplete:function(transport)
{if(transport.status>=200&&transport.status<300)
{elm.removeClassName('disabled');elm.setAttribute('href',href);}
if(Object.isFunction(inOptCallback))inOptCallback(elm);}});}},forceReflow:function(inElement){var elm=$(inElement);if(elm&&elm.style){Element.hide(elm);setTimeout(function(){Element.show(elm)},1);}},formatElementDateContents:function(inElement,inOptIsGMT){var elm=$(inElement);var d=createDateObjFromISO8601(Element.firstNodeValue(elm),inOptIsGMT);if(d)replaceElementContents(elm,Loc.getLongDateString(d));}});Object.extend(Array,{syncKeyedArrayWithRows:function(inKeyedArray,inRows,inOptCopyKeys,inOptDeletePrefix){var copyKeys=inOptCopyKeys||$A([]);var syncStatus={deletedRows:Object.extend({},inKeyedArray),updatedRows:[],addedRows:[]};for(var rowIdx=0;rowIdx<inRows.length;rowIdx++){var row=inRows[rowIdx];if(!row.uid)continue;if(inKeyedArray[row.uid]){delete syncStatus.deletedRows[row.uid];syncStatus.updatedRows.push(row);for(var i=0;i<copyKeys.length;i++){row[copyKeys[i]]=inKeyedArray[row.uid][copyKeys[i]];}}
else{syncStatus.addedRows.push(row);}
inKeyedArray[row.uid]=row;}
var deletedKeys=$H(syncStatus.deletedRows).keys();syncStatus.deletedRows=$A([]);for(var i=0;i<deletedKeys.length;i++){if(!inOptDeletePrefix||deletedKeys[i].indexOf(inOptDeletePrefix)>=0){syncStatus.deletedRows.push(inKeyedArray[deletedKeys[i]]);delete inKeyedArray[deletedKeys[i]];}}
return syncStatus;}});Object.extend(Form,{getIntValue:function(inFieldElement){var val=parseInt($(inFieldElement).value);return(isNaN(val)?0:val);},setSelectValue:function(inSelectElement,inValue,inOptDefaultIdx){var defaultIdx=inOptDefaultIdx||0;var elm=$(inSelectElement);elm.options[defaultIdx].selected=true;if(!inValue)return;for(var optionIdx=0;optionIdx<elm.options.length;optionIdx++){if(elm.options[optionIdx].value==inValue){elm.options[optionIdx].selected=true;return;}}}});Object.extend(Form.Element.Serializers,{textarea:function(element){return Element.hasClassName('hinted')?'':element.value;}});Object.extend(PeriodicalExecuter.prototype,{start:function()
{if(this.timer)this.stop();this.registerCallback();}});function boundsForDiv(theDiv){return offsetBoundsForDiv(theDiv);}
function offsetBoundsForDiv(theDiv){return new Array(Element.getLeft(theDiv),Element.getTop(theDiv),theDiv.offsetWidth,theDiv.offsetHeight);}
function styleBoundsForDiv(theDiv){var s=theDiv.style;if(s.left&&s.top&&s.width&&s.height){return new Array(parseFloat(s.left),parseFloat(s.top),parseFloat(s.width),parseFloat(s.height));}
return null;}
function blur(){try{var anchors=$A(d.getElementsByTagName('a'));if(anchors.length){var firstLink=anchors.detect(function(elm){return elm.href});firstLink.focus();firstLink.blur();}}
catch(e){}}
function afterFinishShow(effect){effect.element.style.height='';Element.show(effect.element);}
function afterFinishHide(effect){effect.element.style.height='';Element.hide(effect.element);}
function afterFinishDelete(effect){effect.element.style.height='';Element.remove(effect.element);}
Object.extend(String.prototype,{trim:function(){return this.toString().replace(/^[\s\t\n\r]*|[\s\t\n\r]*$/g,'');}});if(window.loaded)loaded('widgets.js');

/* wiki_core.js */

var ServerUI=Class.createWithSharedInstance('serverui',true);ServerUI.prototype={initialize:function(){bindEventListeners(this,['handleLogoutButtonClick','handlePasswordResetButtonClick']);publisher().subscribe(this.handleBadSessionID.bind(this),'BAD_SESSION_ID');publisher().subscribe(this.handleAuthenticationFailed.bind(this),'AUTHENTICATION_FAILED');publisher().subscribe(this.handleAuthenticated.bind(this),'AUTHENTICATED');publisher().subscribe(this.handleAuthorizationFailed.bind(this),'AUTHORIZATION_FAILED');publisher().subscribe(this.handleAuthorized.bind(this),'AUTHORIZED');publisher().subscribe(this.handleLoggedOut.bind(this),'LOGGED_OUT');publisher().subscribe(this.handleServerError.bind(this),'MISC_SERVER_ERROR');if(!this.userIsAuthenticated()&&server().sessionID!='unauthenticated'){server().rememberSessionID('unauthenticated');this.setCachedLevel(0);}
$$('#logout_button a').invoke('observe','click',this.handleLogoutButtonClick);if($('login_link'))$('login_link').observe('click',this.handleLogoutButtonClick);var serverUIRevision=getMetaTagValue('apple_required_ui_revision');if(serverUIRevision&&requiredUIRevision!=serverUIRevision){alert(Loc.incorrectRevision+'\nClient: '+requiredUIRevision+'\nServer: '+serverUIRevision);}
if(gDebug){dialogManager().drawDialog('debug_dialog',[{label:'Request',contents:'<pre id="debug_dialog_request" style="width:600px;height:180px;overflow:scroll;border:1px solid gray">'},{label:'Response',contents:'<pre id="debug_dialog_response" style="width:600px;height:180px;overflow:scroll;border:1px solid gray">'}],'Continue');}},userIsAuthenticated:function()
{return!$('wikid').hasClassName('unauthenticated');},passwordResetEnabled:function()
{return(getMetaTagValue('apple_passwordResetEnabled')=="True");},handlePasswordResetButtonClick:function(inEvent){inEvent.stop();if(!this.passwordResetEnabled())return invalidate;window.location='/passwordreset';},ensureLogin:function(inCallback,inOptLevel,inOptSilent,inOptAlwaysLogin){this.mCheckingLevel=inOptLevel||'write';this.mSilent=inOptSilent;this.mSuccessCallback=inCallback;this.mFailureCallback=null;if(inCallback&&inCallback.constructor==Array){this.mSuccessCallback=inCallback[0];this.mFailureCallback=inCallback[1];}
if(this.getCachedLevel()>=this.getLevelInt(this.mCheckingLevel)&&(!inOptAlwaysLogin)){this.mCheckingLevel=null;if(this.mSuccessCallback)this.mSuccessCallback();return true;}
else{blur();if(server().sessionID&&(server().sessionID!='')&&(!inOptAlwaysLogin)){if(!this.mSilent)dialogManager().showProgressMessage('login_progress');var callback=inCallback;if(this.mSilent&&callback&&callback.constructor!=Array){callback=[callback,invalidate];}
server().checkSessionAuthorization(callback,this.mCheckingLevel,uid().mBasePath);}
else if(this.mSilent){if(this.mFailureCallback)this.mFailureCallback();}
else{this.showLoginDialog();}}
return false;},testForCookies:function(){d.cookie='cookies=1; path=/';if(d.cookie&&d.cookie.match(/cookies=1/))return true;alert(Loc.no_cookies);return false;},showLoginDialog:function(inOptFocusField){if(!this.testForCookies())return false;var thirdPartyAuth=getMetaTagValue('apple_third_party_auth');if(!thirdPartyAuth)server().cacheDigestChallenge();if(!this.mAuthDialog){this.mAuthDialog=dialogManager().drawDialog('login_dialog',[{label:'',contents:'<span class="icon"><img width="44" height="44" id="login_dialog_icon" alt=""><span class="mask"></span></span>'},{label:'',contents:'<div id="login_dialog_wiki_name"></div>'},{label:'login_dialog_username',contents:'<input type="text" id="login_dialog_username">'},{label:'login_dialog_password',contents:'<input type="password" id="login_dialog_password">'},{label:'',contents:'<input type="checkbox" id="login_dialog_persistent"><label for="login_dialog_persistent">'+(Loc['login_dialog_persistent']||'')+'</label>'}],'login_dialog_ok');var iconElm=$('login_dialog_icon');iconElm.up('tr').down('th').remove();iconElm.up('td').colSpan='2';iconElm.up('td').id='login_dialog_icon_cell';var src=getMetaTagValue('apple_iconURI');iconElm.src=src||'/collaboration/images/user.png';if(!src||src.indexOf('/collaboration/images/')!=-1)Element.addClassName(iconElm.up('span'),'default');var titleElm=$('login_dialog_wiki_name');titleElm.up('tr').down('th').remove();titleElm.up('td').colSpan='2';titleElm.up('td').id='login_dialog_title_cell';replaceElementContents(titleElm,getMetaTagValue('apple_siteDisplayName')||Loc.mac_os_x);var submitElm=$('login_dialog').down('div.submit');var iforgot=Builder.node('input',{type:'button',name:'login_dialog_iforgot',value:Loc.iforgot,style:'display:none;',id:'login_dialog_iforgot'});Element.observe(iforgot,'click',this.handlePasswordResetButtonClick);submitElm.appendChild(iforgot);if(thirdPartyAuth){var authFrameInfo=thirdPartyAuth.match(/^(.+)#(\d+)x(\d+)$/);var authFrameSrc=authFrameInfo?authFrameInfo[1]:thirdPartyAuth;var authFrameStyle=authFrameInfo?'width:'+authFrameInfo[2]+'px;height:'+authFrameInfo[3]+'px':'';var authFrame='<iframe id="third_party_auth" src='+authFrameSrc+' style="'+authFrameStyle+'"></iframe>';replaceElementContents(this.mAuthDialog,authFrame,true);}}
var loginSuccessCallback=function(){if(this.getCachedLevel()<this.getLevelInt(this.mCheckingLevel)){server().checkSessionAuthorization(this.mSuccessCallback,this.mCheckingLevel,uid().mBasePath);}
else{if(this.mSuccessCallback)this.mSuccessCallback();}}
var cancelCallback=function(){dialogManager().hide();if(this.mFailureCallback)this.mFailureCallback();}
var okCallback=function(){if(thirdPartyAuth){loginSuccessCallback();}
else{this.mLoginDialogUsername=$F('login_dialog_username');server().login(loginSuccessCallback.bind(this),$F('login_dialog_username'),$F('login_dialog_password'),uid().mBasePath,$('login_dialog_persistent').checked);$('login_dialog_password').value='';}}
dialogManager().show(this.mAuthDialog,cancelCallback,okCallback.bind(this),null,true,inOptFocusField);},showUnauthenticatedDialog:function(){if(!$('unauthenticated_dialog')){dialogManager().drawDialog('unauthenticated_dialog',[{contents:'-',id:'unauthenticated_dialog_description'}],'unauthenticated_dialog_ok');$('unauthenticated_dialog_cancel').hide();}
var pageTypeStr=Loc.unauthenticated_page_type_unknown;if(['users','groups'].indexOf(uid().mOwnerType)>=0)pageTypeStr=Loc['unauthenticated_page_type_'+uid().mOwnerType];var dialogDescription=String.format(Loc['unauthenticated_dialog_'+(this.mCheckingLevel?this.mCheckingLevel:'unknown')],{pageType:pageTypeStr});replaceElementContents('unauthenticated_dialog_description',dialogDescription);dialogManager().show('unauthenticated_dialog',null,invalidate);},logout:function(){dialogManager().showProgressMessage('logout_progress');server().logout();return false;},getLevelInt:function(inStr){return['-','read','write','admin'].indexOf(inStr);},getCachedLevel:function(){var results=d.cookie.match(/acl_cache=(\d+)/);return(results?parseInt(results[1]):0);},setCachedLevel:function(inLevel){d.cookie='acl_cache='+inLevel+'; path='+uid().mBaseLocation.replace(/^\/none\//,'/');},handleBadSessionID:function(inMessage,inObject,inUserInfo){dialogManager().hideProgressMessage();this.setCachedLevel(0);this.showLoginDialog();},handleAuthenticationFailed:function(inMessage,inObject,inUserInfo){this.setCachedLevel(0);this.showLoginDialog('login_dialog_password');dialogManager().shakeDialog();if(this.passwordResetEnabled()){new Effect.Appear('login_dialog_iforgot');}},handleAuthenticated:function(inMessage,inObject,inUserInfo){this.setCachedLevel(0);$$('#logout_button a .label').invoke('update',Loc.logout);$$('#logout_button a .username').invoke('update',this.mLoginDialogUsername||'');$('wikid').removeClassName('unauthenticated');$('wikid').addClassName('authenticated');},handleAuthorizationFailed:function(inMessage,inObject,inUserInfo){dialogManager().hideProgressMessage();this.setCachedLevel(0);if(inObject.methodNameStr!='checkSessionAuthorization'){this.mPendingRequest=inObject;}
if(this.mSilent){if(this.mFailureCallback)this.mFailureCallback();}
else if(server().sessionID=='unauthenticated'){this.showLoginDialog();}
else{this.showUnauthenticatedDialog();}},handleAuthorized:function(inMessage,inObject,inUserInfo){var level=this.getLevelInt(inUserInfo.action||'write');this.setCachedLevel(Math.max(level,this.getCachedLevel()));if(this.mAuthDialog)dialogManager().hide(this.mAuthDialog);dialogManager().hideProgressMessage();if(this.mPendingRequest){var req=this.mPendingRequest;this.mPendingRequest=null;req.requestMessageObj.params[0]=server().sessionID;req.sendRequest();}},handleLoggedOut:function(inMessage,inObject,inUserInfo){this.setCachedLevel(0);dialogManager().hide();if(inUserInfo.reload){notifier().printAtPage('loggedOut');}
else{notifier().print('session_expired');$$('#logout_button a .label').invoke('update',Loc.login);$$('#logout_button a .username').invoke('update','');$('wikid').removeClassName('authenticated');$('wikid').addClassName('unauthenticated');}},handleServerError:function(inMessage,inObject,inUserInfo){if(dialogManager())dialogManager().hide();if(inUserInfo.faultCode==0||inUserInfo.faultCode==503){alert(String.format(Loc.noserver_error_format,{hostname:window.location.hostname}));return true;}
else if(inUserInfo.faultCode==410){alert(Loc.noparse_error);return true;}
else if(inUserInfo.faultCode==99){var faultData=inUserInfo.faultString.evalJSON();var maxPageSize=parseInt(faultData['maxPageSize']);var pageSize=parseInt(faultData['pageSize']);faultData['pctOverMax']=Math.round(100-(100*(maxPageSize/pageSize)));alert(String.format(Loc.pagetoobig_error,faultData));return true;}
var errorStr=Loc.error_from_server+' '+inUserInfo.faultString.split('\n')[0]+" ("+inUserInfo.faultCode+")";if(window.unitTestHandler)unitTestHandler.errorFromJS_(errorStr);if(gDebug&&(!this.mDebugInfo)){replaceElementContents('debug_dialog_request',inObject.requestMessageObj.xml());replaceElementContents('debug_dialog_response',(inObject.responseObj?inUserInfo.faultString:'No response.'));var callback=function(){alert(errorStr);}
dialogManager().show('debug_dialog',null,callback);}
else{alert(errorStr);}},handleLogoutButtonClick:function(e){e.stop();if(serverui().userIsAuthenticated()){this.logout();}else{var loginCallback=function(){notifier().print('loggedIn');}
this.ensureLogin(loginCallback,['read','read','write','admin','admin'][this.getCachedLevel()],false,true);}}}
var Tagger=Class.createWithSharedInstance('tagger',true);Tagger.prototype={mConfirmDelete:true,mShouldShowPoof:true,initialize:function(){if($('login_link'))return invalidate;bindEventListeners(this,['handleExpanderClick','handleInputFocus','handleInputBlur','handleMouseDownInTag','handleMouseMove','handleMouseUp']);this.mParent=$('apple_collab_tags');if(!this.mParent)return false;this.mElement=this.mParent.down('ul');if(!this.mElement)return false;if(!IEFixes.isIE){Element.cleanWhitespace(this.mParent);Element.cleanWhitespace(this.mElement);}
$A(this.mParent.getElementsByTagName('a')).each(function(node){if(node.firstChild&&node.firstChild.nodeValue!=''){this.addTag(node.firstChild.nodeValue);}}.bind(this));this.draw();this.mTagSearchField=new TagSearchField(this.mInput,{mClickedItemCallback:this.selectedSearchItem.bind(this)});publisher().subscribe(this.switchToEditor.bind(this),'DID_START_EDITING');publisher().subscribe(this.switchToDisplay.bind(this),'DID_FINISH_EDITING');},draw:function(){if(!this.mElement){this.mParent.appendChild(Builder.node('h3',{},[Loc.tags_label]));this.mElement=Builder.node('ul',{className:'taglist'});this.mParent.appendChild(this.mElement);}
if(!this.mInputExpander){this.mInputExpander=$(Builder.node('a',{href:'#',className:'next_tag_expander','role':'button'},[Loc.tags_addtag_hint]));this.mParent.appendChild(this.mInputExpander);this.mInputExpander.onclick=this.handleExpanderClick;}
if(!this.mInput){this.mInput=Builder.node('input',{id:'next_tag',title:Loc.tags_addtag_hint,type:'text',className:'text next_tag',style:'display:none',maxLength:'70'});if(SafariFixes.isWebKit)$(this.mInput).setStyle({position:'relative',top:'0',left:'0'});this.mParent.appendChild(this.mInput);observeEvents(this,this.mInput,{focus:'handleInputFocus',blur:'handleInputBlur'});this.mInputHinter=new HintedTextField(this.mInput,Loc.tags_addtag_hint);}
if(!this.mDragHandle){this.mDragHandle=Builder.node('div',{className:'bvr-tagdraghandle',style:'position:absolute;top:0;left:0;z-index:100;display:none;fontSize:0.8em;background:#dedede'},['-']);d.body.appendChild(this.mDragHandle);}},filterTagInput:function(inTagName){return inTagName.replace(/[\t\r\n]/g,' ').replace(/^\s+/,'').replace(/\s+$/,'').replace(/\s{2,}/g,' ').toLowerCase();},addTag:function(inTagName,sendToServer){inTagName=this.filterTagInput(inTagName);var elm=this.getTags().elements[inTagName];if(elm||(!inTagName.match(/\S/))){sendToServer=false;}
else{elm=Builder.node('li',[Builder.node('a',{href:uid().mBaseLocation+'search/?tag='+encodeURIComponent(inTagName)},[inTagName])]);this.mElement.appendChild(elm);this.mParent.removeClassName('empty');if(this.mEditMode)this.mDeleteButtons.push(new InlineDeleteButton(elm,this.handleDeleteButtonClick.bind(this),this.mConfirmDelete,this.mShouldShowPoof));}
if(sendToServer){this.mRequest=server()[uid().mService].addTagToEntry(function(){publisher().publish('DID_ADD_TAG',this,{tag:inTagName});notifier().print('tag_added');}.bind(this),uid().mValue,inTagName);}
elm.firstChild.onmousedown=this.handleMouseDownInTag;elm.firstChild.title=Loc.tag_tooltip;var recentTags=[];var tagCookieMatch=d.cookie.match('recentTags=([^;]+)');if(tagCookieMatch)recentTags=tagCookieMatch[1].split(',').slice(0,9);recentTags=recentTags.reject(function(t){return t==inTagName});recentTags.unshift(inTagName);var expireDate=new Date();expireDate.setMonth(expireDate.getMonth()+6);d.cookie='recentTags='+recentTags.join(',')+'; path='+uid().mBaseLocation+'; expires='+expireDate.toGMTString();return elm;},handleDeleteButtonClick:function(inElement){this.removeTag(inElement.firstChild.firstChild.nodeValue,inElement);},removeTag:function(inTagName,inOptTagElement){var elm=inOptTagElement||this.getTags().elements[inTagName];if(elm){var removeTagFromServer=function(){server()[uid().mService].removeTagFromEntry(function(){publisher().publish('DID_REMOVE_TAG',this,{tag:inTagName});}.bind(this),uid().mValue,inTagName);};serverui().ensureLogin(removeTagFromServer.bind(this));Element.remove(elm);if(this.getTags().length==0){this.mParent.addClassName('empty');}}},hasTag:function(inTag){return(this.getTags().elements[inTag]?true:false);},getTags:function(){var tags=[];tags.elements={};if(this.mElement)$A(this.mElement.childNodes).each(function(node){var tagName='-';if(!node.firstChild.firstChild){node.firstChild.appendChild(d.createTextNode(tagName));}
else{tagName=node.firstChild.firstChild.nodeValue;}
tags.push(tagName);tags.elements[tagName]=node;});return tags;},switchToDisplay:function(){if(!this.mElement)return false;var tagName=this.mInputHinter.getValue();if(tagName!='')this.addTag(tagName,true);this.mInputHinter.setValue('');this.mDeleteButtons.each(function(button){button.mParent.getElementsByTagName('a').item(0).onclick='';button.destroy();}.bind(this));delete this.mDeleteButtons;this.hideInputElement();this.mEditMode=false;},switchToEditor:function(){if(!this.mElement)return false;if(!this.mDeleteButtons)this.mDeleteButtons=[];var tags=this.getTags();tags.each(function(tag){this.mDeleteButtons.push(new InlineDeleteButton(tags.elements[tag],this.handleDeleteButtonClick.bind(this),this.mConfirmDelete,this.mShouldShowPoof));tags.elements[tag].getElementsByTagName('a').item(0).onclick=invalidate;}.bind(this));this.showInputElement();this.mEditMode=true;},handleExpanderClick:function(inEvent){this.showInputElement(true);return false;},handleInputFocus:function(inEvent){this.mInput.style.visibility='visible';var afterFinish=function(){this.mInput.focus();this.mTagSearchField.runQuery();}
serverui().ensureLogin(afterFinish.bind(this));},handleInputBlur:function(inEvent){this.mInput.style.visibility='';var tagName=this.mInputHinter.getValue();if(!this.mEditMode){this.hideInputElement();}},showInputElement:function(focus)
{var focus=focus||false;this.mInputExpander.hide();this.mInput.appear({duration:0.15,afterFinish:function(effect){afterFinishShow(effect);if(focus)effect.element.focus();}});this.mParent.addClassName('editing');},hideInputElement:function()
{this.mInput.fade({duration:0.15,afterFinish:function(effect){afterFinishHide(effect);this.mInputExpander.show();}.bind(this)});this.mParent.removeClassName('editing');},selectedSearchItem:function(){var tagName=(this.mInput.value||"").strip();if(tagName!=""){this.addTag(tagName,true);Element.addClassName(this.mElement,'focused_page_tags');Element.removeClassName(this.mElement,'page_tags');}
this.mInput.value='';},handleMouseDownInTag:function(inEvent){Event.stop(inEvent);this.mDraggingTag=Event.findElement(inEvent,'a');var table=this.mDraggingTag.parentNode;this.mDragStartOffset=new Array(Event.pointerX(inEvent)-Element.getLeft(this.mDraggingTag),Event.pointerY(inEvent)-Element.getTop(this.mDraggingTag));Position.clone(table,this.mDragHandle);Element.setStyle(this.mDragHandle,{display:(Element.getStyle(this.mDraggingTag,'display')||'block'),textAlign:(Element.getStyle(this.mDraggingTag,'text-align')||'center'),margin:(Element.getStyle(this.mDraggingTag,'margin')||''),padding:(Element.getStyle(this.mDraggingTag,'padding')||''),color:(Element.getStyle(this.mDraggingTag,'color')||''),backgroundColor:(Element.getStyle(this.mDraggingTag,'background-color')||''),fontFamily:(Element.getStyle(this.mDraggingTag,'font-family')||''),fontSize:(Element.getStyle(this.mDraggingTag,'font-size')||'1em')});this.mDragHandle.firstChild.nodeValue=this.mDraggingTag.firstChild.nodeValue;Element.show(this.mDragHandle);table.style.opacity='0.01';observeEvents(this,d,{mousemove:'handleMouseMove',mouseup:'handleMouseUp'});return false;},handleMouseMove:function(inEvent){Element.setStyle(this.mDragHandle,{left:Event.pointerX(inEvent)-this.mDragStartOffset[0]+'px',top:Event.pointerY(inEvent)-this.mDragStartOffset[1]+'px'});},handleMouseUp:function(inEvent){Event.stopObserving(d,'mousemove',this.handleMouseMove);Event.stopObserving(d,'mouseup',this.handleMouseUp);var table=this.mDraggingTag.parentNode;var tagName=this.mDraggingTag.firstChild.nodeValue;table.style.opacity='';if(Position.within(this.mParent,Event.pointerX(inEvent),Event.pointerY(inEvent))){Element.hide(this.mDragHandle);if(!this.mEditMode)location.href=this.mDraggingTag.href;}
else{this.removeTag(tagName,table);var afterFinish=function(){Element.hide(this.mDragHandle);}
poof().showOverElement(this.mDragHandle,afterFinish.bind(this));}}}
var UserList=Class.create();Object.extend(Object.extend(UserList.prototype,Tagger.prototype),{mConfirmDelete:false,mShouldShowPoof:true,initialize:function(inParent){Loc.tags_addtag_hint=Loc.settings_acl_username_hint;Loc.tag_tooltip='';bindEventListeners(this,['handleExpanderClick','handleInputFocus','handleInputBlur','handleMouseDownInTag','handleMouseMove','handleMouseUp','onInputKeypress']);this.mParent=$(inParent);if(!this.mParent)return false;this.mElement=this.mParent.down('ul');if(!this.mElement)return false;if(!IEFixes.isIE){Element.cleanWhitespace(this.mParent);Element.cleanWhitespace(this.mElement);}
$A(this.mParent.getElementsByTagName('a')).each(function(node){if(node.firstChild&&node.firstChild.nodeValue)
this.addTag(node.firstChild.nodeValue,false,node.getAttribute('title'));}.bind(this));this.draw();this.mTagSearchField=new UserSearchField(this.mInput,{mClickedItemCallback:this.selectedSearchItem.bind(this)});this.mInput.observe('keypress',this.onInputKeypress);this.switchToEditor();},selectedSearchItem:function(userUID)
{var userDisplayName=(this.mInput.value||"").strip();if(userUID&&userDisplayName)
{this.addTag(userDisplayName,false,userUID);Element.addClassName(this.mElement,'focused_page_tags');Element.removeClassName(this.mElement,'page_tags');}
this.mInput.value='';},onInputKeypress:function(e)
{e.stopPropagation();},handleInputFocus:function(inEvent){this.mInput.style.visibility='visible';},addTag:function(inTagName,sendToServer,uid){var label=inTagName.gsub(/\s*<([^>]+)>\s*$/,'');var elm=this.getTags().elements[inTagName];if(!elm){elm=Builder.node('li',[Builder.node('a',{href:'#',title:uid},[label])]);this.mElement.appendChild(elm);if(this.mEditMode)this.mDeleteButtons.push(new InlineDeleteButton(elm,this.handleDeleteButtonClick.bind(this),this.mConfirmDelete,this.mShouldShowPoof));}
var extendedElm=Element.extend(elm);extendedElm.down('a').onclick=invalidate;if(this.mChangeCallback)this.mChangeCallback();return extendedElm;},removeTag:function(inTagName,inOptTagElement){var elm=inOptTagElement||this.getTags().elements[inTagName];poof().showOverElement(elm);if(elm)Element.remove(elm);if(this.mChangeCallback)this.mChangeCallback();},registerChangeCallback:function(inChangeCallback)
{this.mChangeCallback=inChangeCallback;}});var OwnerAdminList=Class.create(UserList,{mShouldShowPoof:false,mDidRemoveActiveAdmin:false,initialize:function($super,inParent){$super(inParent);this.warningDialog=targetedDialogManager().drawDialog('settings_acl_admin_remove_warning',['settings_acl_admin_remove_warning_message'],'settings_acl_admin_remove_warning_delete');},removeTag:function(inTagName,inOptTagElement){var elm=inOptTagElement||this.getTags().elements[inTagName];if(!elm)return;var classNames=elm.down('a').classNames();var callback=function(inElement){this.mDidRemoveActiveAdmin=true;this.removeNode(inElement);}.bind(this);if(!classNames.include('admin')&&classNames.include('active')){targetedDialogManager().show(this.warningDialog,null,function(){callback(elm);},elm);}
else{this.removeNode(elm);}},removeNode:function(inNode){poof().showOverElement(inNode);Element.remove(inNode);if(this.mChangeCallback)this.mChangeCallback();}});var UserPermissionList=Class.create(UserList,{mChangeCallback:null,initialize:function($super,inParent){this.initializing=true;$super(inParent);if(arguments.length>1)Object.extend(this,arguments[2]);bindEventListeners(this,['handlePermissionChanged']);$A(this.mParent.getElementsByTagName('li')).each(function(li){var elem=Element.remove(li);var a=elem.down('a');var tagName=a.firstChild.nodeValue;var uid=a.getAttribute('title');a.hasClassName("readwrite")?this.addTag(tagName,false,uid,"readwrite"):this.addTag(tagName,false,uid,"readonly");}.bind(this));this.initializing=false;},addTag:function(inTagName,sendToServer,uid,permission,ignoreChanges){var label=inTagName.gsub(/\s*<([^>]+)>\s*$/,'');var elm=this.getTags().elements[uid];if(!elm){if(!permission)permission="readwrite";elm=Builder.node('li',[Builder.node('a',{href:'#',title:uid,className:permission},[label]),Builder.node('span',{className:'permissions'},[Builder.node('select',[Builder.node('option',{className:'readwrite',value:'readwrite'},Loc.settings_private_acls_readwrite),Builder.node('option',{className:'readonly',value:'readonly'},Loc.settings_private_acls_readonly)]),Builder.node('span',{className:'fakeselect'},(permission=='readwrite')?Loc.settings_private_acls_readwrite:Loc.settings_private_acls_readonly)])]);(permission=='readwrite')?elm.down('option.readwrite').setAttribute('selected','selected'):elm.down('option.readonly').setAttribute('selected','selected');this.mElement.appendChild(elm);elm.down('select').observe('change',this.handlePermissionChanged);if(this.mEditMode)this.mDeleteButtons.push(new InlineDeleteButton(elm,this.handleDeleteButtonClick.bind(this),this.mConfirmDelete,this.mShouldShowPoof));elm.down('a').onclick=invalidate;if(this.mChangeCallback&&!this.initializing)this.mChangeCallback();}
return elm;},getTags:function(){var tags=[];tags.elements={};if(this.mElement)$A(this.mElement.getElementsBySelector('li')).each(function(tag){var tagName=tag.down('a').getAttribute('title');tags.push(tagName);tags.elements[tagName]=tag;});return tags;},handlePermissionChanged:function(inEvent)
{var permissions=inEvent.findElement('span.permissions');var select=permissions.down('select');var fakeselect=permissions.down('span.fakeselect');permissions.adjacent('a').first().className=select.value;(select.value=="readonly")?fakeselect.innerHTML=Loc.settings_private_acls_readonly:fakeselect.innerHTML=Loc.settings_private_acls_readwrite;if(this.mChangeCallback)this.mChangeCallback();}});var UserSearchField=Class.create();Object.extend(Object.extend(UserSearchField.prototype,SearchFieldBase.prototype),{mSortKey:'displayName',mValueKey:'displayName',mMinQueryChars:3,mSearchCancelledCallback:function(){this.mResultTable.hide();},filterTagInput:function(inTagName){return inTagName.replace(/[\t\r\n]/g,' ').replace(/^\s+/,'').replace(/\s+$/,'');},getDisplayString:function(inRow){return inRow['displayName']+' <'+inRow['uid']+'>';},constructQuery:function(inSearchString)
{if(!inSearchString)return;return server().whitepages.getRecordsStartingWith([this.gotSearchResult.bind(this),this.handleError.bind(this)],inSearchString,false);}});var ButtonBarWidget=Class.create();ButtonBarWidget.prototype={mSelectedIndex:0,initialize:function(inParentElm,inParentClassName,inChildClassNames){bindEventListeners(this,['handleClickedButton']);this.mChildClassNames=inChildClassNames;if(arguments.length>3)Object.extend(this,arguments[3]);this.mButtons=inChildClassNames.collect(function(className,i){var a=Builder.node('a',{href:'#',title:(Loc[className]||''),'role':'button'},["\u00A0"]);a.onclick=this.handleClickedButton;return Builder.node('li',{className:className,'role':'presentation'},[a]);}.bind(this));this.mElement=Builder.node('ul',{className:inParentClassName,'role':'toolbar'},this.mButtons);$(inParentElm).appendChild(this.mElement);this.setSelectedIndex(this.mSelectedIndex);},handleClickedButton:function(inEvent){var elm=Event.findElement(inEvent,'li');this.setSelectedIndex(this.mButtons.indexOf(elm));return false;},getSelectedIndex:function(){return this.mSelectedIndex;},setSelectedIndex:function(inIndex){this.mSelectedIndex=inIndex;this.mButtons.each(function(elm,i){if(i==inIndex)Element.addClassName($(elm).down(),'selected');else Element.removeClassName($(elm).down(),'selected');}.bind(this));}}
var Paginator=Class.create();Paginator.prototype={initialize:function(inParentElm){bindEventListeners(this,['handleClickPopupHandle']);this.mEntriesPerPage=getMetaTagValue('apple_collab_how_many');if(this.mEntriesPerPage)this.mEntriesPerPage=parseInt(this.mEntriesPerPage);this.mTotalEntries=getMetaTagValue('apple_collab_entry_count');if(this.mTotalEntries)this.mTotalEntries=parseInt(this.mTotalEntries);var startIndexMatch=location.search.match(/startIndex=(\d+)/);this.mCurrentStartIndex=startIndexMatch?startIndexMatch[1]:0;if(this.mCurrentStartIndex)this.mCurrentStartIndex=parseInt(this.mCurrentStartIndex);var url=location.href.replace(/startIndex=\d*&*/,'').replace(/\?*&*$/,'');if(url.match(/\?/)){url+='&startIndex=';}
else{url+='?startIndex=';}
var lastEntry=Math.min(this.mCurrentStartIndex+this.mEntriesPerPage,this.mTotalEntries);this.mPreviousURL=url+Math.max(this.mCurrentStartIndex-this.mEntriesPerPage,0);this.mNextURL=url+Math.min(this.mCurrentStartIndex+this.mEntriesPerPage,this.mTotalEntries-1);if(lastEntry==this.mTotalEntries)this.mNextURL='#';this.mPopup=popupManager().createPopupElement('paginatorpopup');for(var i=0;i<this.mTotalEntries;i+=this.mEntriesPerPage){var pLastEntry=Math.min(i+this.mEntriesPerPage,this.mTotalEntries);var displayString=String.format(Loc.paginator_popup_item_format,{firstEntry:i+1,lastEntry:pLastEntry});popupManager().itemWithTitle(this.mPopup,displayString,url+i);}
var displayString=String.format(Loc.paginator_picker_format,{firstEntry:this.mCurrentStartIndex+1,lastEntry:lastEntry,totalEntries:this.mTotalEntries});var prevPageButton=Builder.node('a',{className:'paginator_prev'},'←');if(this.mCurrentStartIndex!=0&&this.mPreviousURL!='#'){prevPageButton.setAttribute('href',this.mPreviousURL);prevPageButton.setAttribute('title',Loc['paginator_previous']);}else{Element.addClassName(prevPageButton,'disabled');}
this.mPopupHandle=Builder.node('a',{className:'paginator_choose'},displayString);this.mPopupHandle.onclick=this.handleClickPopupHandle;var nextPageButton=Builder.node('a',{className:'paginator_next'},'→');if(this.mNextURL!='#'){nextPageButton.setAttribute('href',this.mNextURL);nextPageButton.setAttribute('title',Loc['paginator_next']);}else{Element.addClassName(nextPageButton,'disabled');}
this.mElement=Builder.node('div',{className:'paginator'},[Builder.node('ul',[Builder.node('li',{'class':'first'},[prevPageButton]),Builder.node('li',{'class':'middle'},[this.mPopupHandle]),Builder.node('li',{'class':'last'},[nextPageButton])])]);if(this.mTotalEntries<1)Element.hide(this.mElement);$(inParentElm).appendChild(this.mElement);},handleClickPopupHandle:function(inEvent){Event.stop(inEvent);popupManager().show(this.mPopupHandle,this.mPopup,(Element.getInvisibleHeight(this.mPopup)+Element.getInvisibleHeight(this.mPopupHandle))*(-1)-12);return false;}}
var LowScriptPaginator=Class.createWithSharedInstance('paginator');Object.extend(Object.extend(LowScriptPaginator.prototype,Paginator.prototype),{initialize:function(){this.mPopupHandle=$('paginator_choose');bindEventListeners(this,['handleClickPopupHandle']);$$('#paginator li.disabled a').each(function(a){a.onclick=invalidate;});this.mEntriesPerPage=getMetaTagValue('apple_collab_how_many');if(this.mEntriesPerPage)this.mEntriesPerPage=parseInt(this.mEntriesPerPage);this.mTotalEntries=getMetaTagValue('apple_collab_entry_count');if(this.mTotalEntries)this.mTotalEntries=parseInt(this.mTotalEntries);var url=location.href.replace(/startIndex=\d*&*/,'').replace(/\?*&*$/,'');if(url.match(/\?/)){url+='&startIndex=';}
else{url+='?startIndex=';}
this.mPopup=popupManager().createPopupElement();for(var i=0;i<this.mTotalEntries;i+=this.mEntriesPerPage){var pLastEntry=Math.min(i+this.mEntriesPerPage,this.mTotalEntries);var displayString=String.format(Loc.paginator_popup_item_format,{firstEntry:i+1,lastEntry:pLastEntry});popupManager().itemWithTitle(this.mPopup,displayString,url+i);}
Event.observe(this.mPopupHandle,'click',this.handleClickPopupHandle);}});var DatePicker=Class.create();DatePicker.prototype={mSelectWeek:false,mAllowMonthMode:false,mPositionPicker:true,mPositionAbove:false,mAlwaysShowPicker:false,mTodayString:null,mShowChanges:true,initialize:function(inChooseWidget){bindEventListeners(this,['clickedChooseWidget','clickedPrevWidget','clickedNextWidget','clickedDate','clickedPopup','clickedUpButton','clickedTodayButton','clickedDownButton','clickedWindow','clickedMonthLink']);this.drawDatePicker();this.mChooseWidget=$(inChooseWidget);this.mSelectedDate=new Date();this.mTodaySelected=true;this.mStartIndex=parseInt(getMetaTagValue('apple_collab_start_index')||'0');this.mEntryCount=parseInt(getMetaTagValue('apple_collab_entry_count')||'0');if(arguments.length>1)Object.extend(this,arguments[1]);if(this.mAllowMonthMode){var monthLink=this.mTableBody.getElementsByTagName('a').item(0);monthLink.href='#';monthLink.onclick=this.clickedMonthLink;}
$A(this.mTableBody.childNodes.item(1).getElementsByTagName('td')).each(function(elm,i){replaceElementContents(elm,Loc.shortWeekdays[i]);});this.mShownDateElement=this.mTableBody.getElementsByTagName('a').item(0).firstChild;Event.observe(this.mChooseWidget,'click',this.clickedChooseWidget);Event.observe(this.mUpButton,'click',this.clickedUpButton);Event.observe(this.mTodayButton,'click',this.clickedTodayButton);Event.observe(this.mDownButton,'click',this.clickedDownButton);if(this.mPrevWidget){this.mPrevWidget=$(this.mPrevWidget);this.clickedPrevWidget=this.clickedPrevWidget.bindAsEventListener(this);Event.observe(this.mPrevWidget,'mousedown',this.clickedPrevWidget);this.mPrevWidget.onselectstart=invalidate;}
if(this.mNextWidget){this.mNextWidget=$(this.mNextWidget);this.clickedNextWidget=this.clickedNextWidget.bindAsEventListener(this);Event.observe(this.mNextWidget,'mousedown',this.clickedNextWidget);this.mNextWidget.onselectstart=invalidate;}
this.updateFromSelection();this.mElement.onselectstart=invalidate;this.mChooseWidget.onselectstart=invalidate;if(this.mAlwaysShowPicker)this.show();},drawDatePicker:function(){this.mTableBody=Builder.node('tbody',[Builder.node('tr',[Builder.node('td',{colSpan:'7'},[Builder.node('a',"\u00A0")])])]);for(var row=0;row<7;row++){var tr=Builder.node('tr');for(var col=0;col<7;col++){tr.appendChild(Builder.node('td',"\u00A0"));}
this.mTableBody.appendChild(tr);}
this.mUpButton=Builder.node('td',{id:'date_up_button',title:Loc.tooltips.prev_button_month},"\u00A0");this.mTodayButton=Builder.node('td',{id:'date_today_button',title:Loc.tooltips.current_button},"\u00A0");this.mDownButton=Builder.node('td',{id:'date_down_button',title:Loc.tooltips.next_button_month},"\u00A0");this.mElement=Builder.node('div',{id:'date_picker',className:'datepicker',style:'display:none'},[Builder.node('table',{id:'date_picker_buttons',className:'datepickerbuttons'},[Builder.node('tbody',[Builder.node('tr',[this.mUpButton,this.mTodayButton,this.mDownButton])])]),Builder.node('table',{id:'date_picker_calendar_table',className:'datepickerbody'},[this.mTableBody])]);if(IEFixes.isIE)this.mElement.style.backgroundPosition='4px 0';d.body.appendChild(this.mElement);},getSelectedRange:function(){var startDate=new Date(this.mSelectedDate.getTime());if(this.mMonthMode)startDate.setDate(1);else if(this.mSelectWeek)startDate.setDate(startDate.getDate()-startDate.getDay());var endDate=new Date(startDate.getTime());if(this.mMonthMode){endDate.setMonth(endDate.getMonth()+1);endDate.setDate(0);}
else if(this.mSelectWeek)endDate.setDate(endDate.getDate()+6);startDate.setHours(0);startDate.setMinutes(0);startDate.setSeconds(0);endDate.setHours(23);endDate.setMinutes(59);endDate.setSeconds(59);return new Array(startDate,endDate);},isTodaySelected:function(){if(this.mTodaySelected&&parseInt(dateObjToISO8601(this.mSelectedDate))!=parseInt(dateObjToISO8601(new Date()))){this.mTodaySelected=false;}
return this.mTodaySelected;},updateShownDate:function(){this.mShownDateElement.nodeValue=this.mShownDate.formatDate(Loc.dateFormats.monthAndYear);var now=new Date();var date=new Date(this.mShownDate.getTime());date.setDate(1);date.setDate(date.getDate()-date.getDay());for(var week=0;week<6;week++){var row=this.mTableBody.childNodes.item(week+2);for(var day=0;day<7;day++){var cell=row.childNodes.item(day);if(compareDateWeeks(this.mSelectedDate,date)&&(this.mSelectWeek||(this.mSelectedDate.getDate()==date.getDate()))&&(this.mSelectedDate.getMonth()==this.mShownDate.getMonth())){Element.addClassName(cell,'date_picker_current_week');}
else{Element.removeClassName(cell,'date_picker_current_week');}
if(date.getMonth()==this.mShownDate.getMonth()){Event.observe(cell,'mousedown',this.clickedDate);cell.firstChild.nodeValue=padNumberStr(date.getDate(),2,' ');cell.style.cursor='pointer';if((this.mSelectWeek||(!Element.hasClassName(cell,'date_picker_current_week')))&&(compareDateWeeks(date,now)&&(date.getDate()==now.getDate()))){Element.removeClassName(cell,'date_picker_current_week');cell.id='date_picker_today';}
else{cell.id=null;}}
else{Event.stopObserving(cell,'mousedown',this.clickedDate);cell.firstChild.nodeValue=' ';cell.style.cursor=null;}
date.setDate(date.getDate()+1);}}},updateFromSelection:function(inAlwaysShow){var range=this.getSelectedRange();var s='';if(this.mTodayString&&this.isTodaySelected()){s=Loc[this.mTodayString]||this.mTodayString;if(this.mStartIndex){s+=' ('+this.mStartIndex+' - '+(this.mStartIndex+this.mEntryCount)+')';}}
else if(this.mMonthMode){s=this.mSelectedDate.formatDate(Loc.dateFormats.monthAndYear);if(this.mPrevWidget)this.mPrevWidget.title=Loc.tooltips.prev_button_month;if(this.mNextWidget)this.mNextWidget.title=Loc.tooltips.next_button_month;}
else{s=range[0].formatDate(Loc.dateFormats.mediumDate);if((range[0].getMonth()!=range[1].getMonth())||(range[0].getDate()!=range[1].getDate())){s+=' - '+range[1].formatDate(Loc.dateFormats.mediumDate);}
if(this.mPrevWidget)this.mPrevWidget.title=Loc.tooltips.prev_button_week;if(this.mNextWidget)this.mNextWidget.title=Loc.tooltips.next_button_week;}
if(inAlwaysShow||this.mShowChanges){replaceElementContents(this.mChooseWidget,s);}
this.mShownDate=new Date(this.mSelectedDate.getTime());this.updateShownDate();this.hide();this.publish();},publish:function(){if(this.mSubscribers){for(var i=0;i<this.mSubscribers.length;i++){var currentFunction=this.mSubscribers[i];currentFunction();}}},subscribe:function(inFunction){if(!this.mSubscribers)this.mSubscribers=new Array();this.mSubscribers.push(inFunction);},show:function(){if(!this.mShown){this.mShownDate=new Date(this.mSelectedDate.getTime());this.mShownDate.setDate(1);this.updateShownDate();if(this.mEffect){this.mEffect.cancel();this.mEffect=null;}
if(this.mMonthMode){if(!this.mMonthPopup){this.mMonthPopup=Object.extend(popupManager().createPopupElement(),{id:'date_month_popup'});}
$$('#date_month_popup li').invoke('remove');var currentDate=new Date(this.mShownDate.getTime());currentDate.setDate(1);currentDate.setMonth(currentDate.getMonth()-6);for(var i=0;i<12;i++){popupManager().itemWithTitle(this.mMonthPopup,currentDate.formatDate(Loc.dateFormats.monthAndYear),'#'+dateObjToISO8601(currentDate),this.clickedMonthLink);currentDate.setMonth(currentDate.getMonth()+1);}
popupManager().show(this.mChooseWidget,this.mMonthPopup,Element.getInvisibleHeight(this.mMonthPopup)*(-1),true);}
else{this.mShown=true;this.mElement.style.visibility='hidden';Element.show(this.mElement);if(this.mPositionPicker){var offsetTop=Element.getHeight(this.mChooseWidget)-4;if(this.mPositionAbove){offsetTop=(Element.getHeight(this.mElement)-12)*(-1);}
var cloneOptions={setWidth:false,setHeight:false,offsetLeft:(this.mChooseWidget.offsetWidth-this.mElement.offsetWidth)/2,offsetTop:offsetTop};Position.clone(this.mChooseWidget,this.mElement,cloneOptions);}
Element.hide(this.mElement);this.mElement.style.visibility='';Event.observe(this.mElement,'mousedown',this.clickedPopup);Event.observe(d,'mousedown',this.clickedWindow);this.mEffect=Effect.Appear(this.mElement,{duration:0.3});}}},hide:function(){if(this.mShown&&(!this.mAlwaysShowPicker)){if(this.mEffect){this.mEffect.cancel();this.mEffect=null;}
Event.stopObserving(this.mElement,'mousedown',this.clickedPopup);Event.stopObserving(d,'mousedown',this.clickedWindow);this.mShown=false;Element.hide(this.mElement);}},clickedMonthLink:function(e){var elm=Event.element(e);if(elm.hasClassName('popuplink')){this.mSelectedDate=createDateObjFromISO8601(elm.href.match(/#(\d{8})/)[1]);}
else{this.mSelectedDate=new Date(this.mShownDate.getTime());}
this.mMonthMode=true;this.updateFromSelection();return false;},clickedChooseWidget:function(e){Event.stop(e);if(this.mShown)this.hide();else this.show();},clickedPrevWidget:function(e){Event.stop(e);if(this.mMonthMode){this.mSelectedDate.setDate(1);this.mSelectedDate.setMonth(this.mSelectedDate.getMonth()-1);}
else{var amt=this.mSelectWeek?7:1;this.mSelectedDate.setDate(this.mSelectedDate.getDate()-amt);}
this.updateFromSelection();return false;},clickedNextWidget:function(e){Event.stop(e);if(this.mMonthMode){this.mSelectedDate.setDate(1);this.mSelectedDate.setMonth(this.mSelectedDate.getMonth()+1);}
else{var amt=this.mSelectWeek?7:1;this.mSelectedDate.setDate(this.mSelectedDate.getDate()+amt);}
this.updateFromSelection();return false;},clickedUpButton:function(e){if(this.mShownDate.getMonth()==0){this.mShownDate.setMonth(11);this.mShownDate.setFullYear(this.mShownDate.getFullYear()-1);}
else this.mShownDate.setMonth(this.mShownDate.getMonth()-1);this.updateShownDate();},clickedTodayButton:function(e){this.mTodaySelected=true;this.mSelectedDate=new Date();this.mMonthMode=false;this.updateFromSelection();return false;},clickedDownButton:function(e){this.mShownDate.setMonth(this.mShownDate.getMonth()+1);this.updateShownDate();},clickedDate:function(e){this.hide();this.mShownDate.setDate(parseInt(Event.element(e).firstChild.nodeValue));this.mSelectedDate=new Date(this.mShownDate.getTime());this.mMonthMode=false;this.updateFromSelection();},clickedPopup:function(e){Event.stop(e);},clickedWindow:function(e){if((!IEFixes.isIE)||(Event.element(e)!=this.mChooseWidget))this.hide();}}
var TagSearchField=Class.create();Object.extend(Object.extend(TagSearchField.prototype,SearchFieldBase.prototype),{mInterval:10,mPrefetch:true,mSortKey:'uid',mSearchCancelledCallback:function(){this.mResultTable.hide();},getDisplayString:function(inRow){return inRow.uid;},constructQuery:function(inSearchString){if(this.mCachedRows){if(inSearchString.length>0){var searchExp=new RegExp('^'+inSearchString,'i');this.mRows=this.mCachedRows.findAll(function(row){return searchExp.test(row.uid);});}
else{this.mRows=[];}
this.draw();this.mTimer=null;}
else{return server().tags.getEntries([this.gotSearchResult.bind(this),this.handleError.bind(this)],uid().mBasePath);}}});var SearchPopup=Class.createWithSharedInstance('searchPopup',true);SearchPopup.prototype={mMaxTags:10,initialize:function(){if(!$('linkSearch'))return invalidate;bindEventListeners(this,['handleItemSelect','handleMouseDown','handleSearchInputBlur','handleSearchInputFocus']);this.mParentElement=$('linkSearch').down('input');if(!this.mParentElement)return invalidate;this.mElement=$('linkSearchPopup');if(!this.mElement)return invalidate;if(SafariFixes.isTigerSafari)return true;Event.observe(this.mParentElement,'focus',this.handleSearchInputFocus);Event.observe(this.mParentElement,'blur',this.handleSearchInputBlur);Event.observe($('linkSearch').down('form'),'submit',this.handleItemSelect);if(MozillaFixes.isGecko)$('search_field').setAttribute('autocomplete','off');this.draw();setTimeout(this.getRelevantTags.bind(this),500);publisher().subscribe(this.getRelevantTags.bind(this),'AUTHENTICATED');},draw:function(inOptTags){tags=inOptTags||[];var tagCookieMatch=d.cookie.match('recentTags=([^;]+)');if(tagCookieMatch&&(tags.length<this.mMaxTags)){var recentTags=tagCookieMatch[1].split(',');tags=tags.concat(recentTags).uniq().slice(0,this.mMaxTags);}
tags.sort();if(!this.mHeaderElement){this.mHeaderElement=Builder.node('h2',Loc.search_recent_tags);this.mElement.appendChild(this.mHeaderElement);}
if(!this.mResultsContainer){this.mResultsContainer=Builder.node('div',{className:'search_popup_results'});this.mElement.appendChild(this.mResultsContainer);}
if(!this.mQuickSearchField){this.mResultTable=Builder.node('ul',{id:'quick_search_field_results',style:'display:none'},[Builder.node('li',[Builder.node('a',{href:'#',onclick:invalidate,className:'search_placeholder busy_field'},Loc.link_popup_searching_progress)])]);this.mResultsContainer.appendChild(this.mResultTable);this.mQuickSearchField=new QuickSearchField('search_field',{mResultTable:this.mResultTable,mClickedItemCallback:this.handleQuickSearchClick.bind(this),mStartedItemSearchCallback:this.handleQuickSearchStarted.bind(this),mSearchCancelledCallback:this.handleQuickSearchCancelled.bind(this),mSearchResultCallback:this.handleQuickSearchResults.bind(this),mPositionResults:false,mShowPlaceholderStrings:true});}
if(this.mLinkListElement){$A(this.mLinkListElement.getElementsByTagName('a')).each(function(a){Event.stopObserving(a,'click',this.handleItemSelect);}.bind(this));$(this.mLinkListElement).remove();}
this.mLinkListElement=Builder.node('ul');if(tags.length>0){var searchURI=uid().mBaseLocation+'search/';tags.each(function(tag){var href=searchURI+encodeURIComponent(tag).replace(/\%20/g,'+')+'?sort=modifiedDate&howMany=10&sortDirection=reverse&tag='+encodeURIComponent(tag).replace(/\%20/g,'+');this.mLinkListElement.appendChild(Builder.node('li',[Builder.node('a',{href:href},tag)]));}.bind(this));this.mLinkListElement.appendChild(Builder.node('li',{className:'linkPopupSplitter'}));}
this.mLinkListElement.appendChild(Builder.node('li',{className:'search_all_tags_item'},[Builder.node('a',{href:uid().mBaseLocation+'tags/'},Loc.tags_all_item)]));this.mLinkListElement.appendChild(Builder.node('li',{className:'search_all_recents_item'},[Builder.node('a',{href:uid().mBaseLocation+'search/',className:'tagsRecentsItem'},Loc.tags_recents_item)]));this.mResultsContainer.appendChild(this.mLinkListElement);$A(this.mLinkListElement.getElementsByTagName('a')).each(function(a){Event.observe(a,'click',this.handleItemSelect);}.bind(this));},handleSearchInputBlur:function(inEvent){setTimeout(this.hide.bind(this),200);},handleSearchInputFocus:function(inEvent){Event.stop(inEvent);Element.show(this.mElement);if(this.mElement.visible()){if(MozillaFixes.isGecko)this.mElement.setStyle({width:(this.mElement.offsetWidth+4)+'px',overflowX:'hidden',overflowY:'auto'});Event.observe(d.body,'mousedown',this.handleMouseDown);}
else{Event.stopObserving(d.body,'mousedown',this.handleMouseDown);if(MozillaFixes.isGecko)this.mElement.setStyle({width:'',overflowX:'',overflowY:''});}
this.mElement.up('.header').addClassName('quicksearch');},handleQuickSearchCancelled:function(){replaceElementContents(this.mHeaderElement,Loc.search_recent_tags);Element.hide(this.mResultTable);Element.show(this.mLinkListElement);},handleQuickSearchResults:function(){Element.show(this.mResultTable);if(SafariFixes.isWebKit)Element.forceReflow(this.mResultsContainer);},handleQuickSearchStarted:function(){replaceElementContents(this.mHeaderElement,Loc.search_quicksearch);Element.hide(this.mLinkListElement);Element.show(this.mResultTable);},handleQuickSearchClick:function(inUID,inURL){if(inURL)location.href=inURL;else if(inUID&&inUID.match(/^[^\/]+\/[^\/]+\/[^\/]+\/[^\/]+$/))location.href='/'+inUID+'/';},handleItemSelect:function(inEvent){this.hide();if(this.mQuickSearchField&&this.mQuickSearchField.mSuggestedUID){Event.stop(inEvent);return false;}},handleMouseDown:function(inEvent){var pos=[Event.pointerX(inEvent),Event.pointerY(inEvent)];if((!Position.within(this.mElement,pos[0],pos[1]))&&(!Position.within(this.mParentElement,pos[0],pos[1]))){this.hide();}},hide:function(){this.mElement.up('.header').removeClassName('quicksearch');this.mElement.hide();Event.stopObserving(d.body,'mousedown',this.handleMouseDown);},getRelevantTags:function(){server().preferences.getUsersRelevantTags([this.gotRelevantTags.bind(this),invalidate],uid().mBasePath);},gotRelevantTags:function(inRequestObj,inResponseObj){this.draw(inResponseObj);}}
Effect.ResizeBy=Class.create();Object.extend(Object.extend(Effect.ResizeBy.prototype,Effect.Base.prototype),{initialize:function(element,toWidth,toHeight){this.element=$(element);var bounds=styleBoundsForDiv(this.element)||offsetBoundsForDiv(this.element);this.originalWidth=bounds[2];this.originalHeight=bounds[3];this.toWidth=toWidth;this.toHeight=toHeight;this.start(arguments[3]);},update:function(position){var widthd=this.toWidth*position+this.originalWidth;this.element.style.width=widthd+'px';if(this.toHeight){var heightd=this.toHeight*position+this.originalHeight;this.element.style.height=heightd+'px';}}});var CommentUID=Class.createWithSharedInstance();Object.extend(Object.extend(CommentUID.prototype,CollabUID.prototype),{mMetaTagName:'apple_collab_comment_uid'});var CommentUID=Class.createWithSharedInstance();Object.extend(Object.extend(CommentUID.prototype,CollabUID.prototype),{mMetaTagName:'apple_collab_comment_uid'});if(window.loaded)loaded('wiki_core.js');