
var Rico={Version:'1.1.0',prototypeVersion:parseFloat(Prototype.Version.split(".")[0]+"."+Prototype.Version.split(".")[1])}
Rico.Color=Class.create();Rico.Color.prototype={initialize:function(red,green,blue){this.rgb={r:red,g:green,b:blue};},blend:function(other){this.rgb.r=Math.floor((this.rgb.r+other.rgb.r)/2);this.rgb.g=Math.floor((this.rgb.g+other.rgb.g)/2);this.rgb.b=Math.floor((this.rgb.b+other.rgb.b)/2);},asRGB:function(){return"rgb("+this.rgb.r+","+this.rgb.g+","+this.rgb.b+")";},asHex:function(){return"#"+this.rgb.r.toColorPart()+this.rgb.g.toColorPart()+this.rgb.b.toColorPart();},asHSB:function(){return Rico.Color.RGBtoHSB(this.rgb.r,this.rgb.g,this.rgb.b);},toString:function(){return this.asHex();}};Rico.Color.createFromHex=function(hexCode){if(hexCode.length==4){var shortHexCode=hexCode;var hexCode='#';for(var i=1;i<4;i++)hexCode+=(shortHexCode.charAt(i)+shortHexCode.charAt(i));}
if(hexCode.indexOf('#')==0)
hexCode=hexCode.substring(1);var red=hexCode.substring(0,2);var green=hexCode.substring(2,4);var blue=hexCode.substring(4,6);return new Rico.Color(parseInt(red,16),parseInt(green,16),parseInt(blue,16));}
Rico.Color.createColorFromBackground=function(elem){var actualColor=$(elem).getStyle('backgroundColor');if(actualColor=="transparent"&&elem.parentNode)
return Rico.Color.createColorFromBackground(elem.parentNode);if(actualColor==null)
return new Rico.Color(255,255,255);if(actualColor.indexOf("rgb(")==0){var colors=actualColor.substring(4,actualColor.length-1);var colorArray=colors.split(",");return new Rico.Color(parseInt(colorArray[0]),parseInt(colorArray[1]),parseInt(colorArray[2]));}
else if(actualColor.indexOf("#")==0){return Rico.Color.createFromHex(actualColor);}
else
return new Rico.Color(255,255,255);}
Rico.Color.HSBtoRGB=function(hue,saturation,brightness){var br=Math.round(brightness/100*255);if(this[1]==0){return[br,br,br];}else{var hue=this[0]%360;var f=hue%60;var p=Math.round((brightness*(100-saturation))/10000*255);var q=Math.round((brightness*(6000-saturation*f))/600000*255);var t=Math.round((brightness*(6000-saturation*(60-f)))/600000*255);switch(Math.floor(hue/60)){case 0:return{r:br,g:t,b:p};case 1:return{r:q,g:br,b:p};case 2:return{r:p,g:br,b:t};case 3:return{r:p,g:q,b:br};case 4:return{r:t,g:p,b:br};case 5:return{r:br,g:p,b:q};}}
return false;}
Rico.Color.RGBtoHSB=function(red,green,blue){var hue,saturation,brightness;var max=Math.max(red,green,blue),min=Math.min(red,green,blue);var delta=max-min;brightness=max/255;saturation=(max!=0)?delta/max:0;if(saturation==0){hue=0;}else{var rr=(max-red)/delta;var gr=(max-green)/delta;var br=(max-blue)/delta;if(red==max)hue=br-gr;else if(green==max)hue=2+rr-br;else hue=4+gr-rr;hue/=6;if(hue<0)hue++;}
return{h:Math.round(hue*360),s:Math.round(saturation*100),b:Math.round(brightness*100)};}
Rico.Corner={round:function(e,options){var e=$(e);this._setOptions(options);var color=this.options.color;if(this.options.color=="fromElement")
color=this._background(e);var bgColor=this.options.bgColor;if(this.options.bgColor=="fromParent")
bgColor=this._background(e.offsetParent);this._roundCornersImpl(e,color,bgColor);},_roundCornersImpl:function(e,color,bgColor){if(this.options.border)
this._renderBorder(e,bgColor);if(this._isTopRounded())
this._roundTopCorners(e,color,bgColor);if(this._isBottomRounded())
this._roundBottomCorners(e,color,bgColor);},_renderBorder:function(el,bgColor){var borderValue="1px solid "+this._borderColor(bgColor);var borderL="border-left: "+borderValue;var borderR="border-right: "+borderValue;var style="style='"+borderL+";"+borderR+"'";el.innerHTML="<div "+style+">"+el.innerHTML+"</div>"},_roundTopCorners:function(el,color,bgColor){var corner=this._createCorner(bgColor);for(var i=0;i<this.options.numSlices;i++)
corner.appendChild(this._createCornerSlice(color,bgColor,i,"top"));el.style.paddingTop=0;el.insertBefore(corner,el.firstChild);},_roundBottomCorners:function(el,color,bgColor){var corner=this._createCorner(bgColor);for(var i=(this.options.numSlices-1);i>=0;i--)
corner.appendChild(this._createCornerSlice(color,bgColor,i,"bottom"));el.style.paddingBottom=0;el.appendChild(corner);},_createCorner:function(bgColor){var corner=document.createElement("div");corner.style.backgroundColor=(this._isTransparent()?"transparent":bgColor);return corner;},_createCornerSlice:function(color,bgColor,n,position){var slice=document.createElement("span");var inStyle=slice.style;inStyle.backgroundColor=color;inStyle.display="block";inStyle.height="1px";inStyle.overflow="hidden";inStyle.fontSize="1px";var borderColor=this._borderColor(color,bgColor);if(this.options.border&&n==0){inStyle.borderTopStyle="solid";inStyle.borderTopWidth="1px";inStyle.borderLeftWidth="0px";inStyle.borderRightWidth="0px";inStyle.borderBottomWidth="0px";inStyle.height="0px";inStyle.borderColor=borderColor;}
else if(borderColor){inStyle.borderColor=borderColor;inStyle.borderStyle="solid";inStyle.borderWidth="0px 1px";}
if(!this.options.compact&&(n==(this.options.numSlices-1)))
inStyle.height="2px";this._setMargin(slice,n,position);this._setBorder(slice,n,position);return slice;},_setOptions:function(options){this.options={corners:"all",color:"fromElement",bgColor:"fromParent",blend:true,border:false,compact:false}
Object.extend(this.options,options||{});this.options.numSlices=this.options.compact?2:4;if(this._isTransparent())
this.options.blend=false;},_whichSideTop:function(){if(this._hasString(this.options.corners,"all","top"))
return"";if(this.options.corners.indexOf("tl")>=0&&this.options.corners.indexOf("tr")>=0)
return"";if(this.options.corners.indexOf("tl")>=0)
return"left";else if(this.options.corners.indexOf("tr")>=0)
return"right";return"";},_whichSideBottom:function(){if(this._hasString(this.options.corners,"all","bottom"))
return"";if(this.options.corners.indexOf("bl")>=0&&this.options.corners.indexOf("br")>=0)
return"";if(this.options.corners.indexOf("bl")>=0)
return"left";else if(this.options.corners.indexOf("br")>=0)
return"right";return"";},_borderColor:function(color,bgColor){if(color=="transparent")
return bgColor;else if(this.options.border)
return this.options.border;else if(this.options.blend)
return this._blend(bgColor,color);else
return"";},_setMargin:function(el,n,corners){var marginSize=this._marginSize(n);var whichSide=corners=="top"?this._whichSideTop():this._whichSideBottom();if(whichSide=="left"){el.style.marginLeft=marginSize+"px";el.style.marginRight="0px";}
else if(whichSide=="right"){el.style.marginRight=marginSize+"px";el.style.marginLeft="0px";}
else{el.style.marginLeft=marginSize+"px";el.style.marginRight=marginSize+"px";}},_setBorder:function(el,n,corners){var borderSize=this._borderSize(n);var whichSide=corners=="top"?this._whichSideTop():this._whichSideBottom();if(whichSide=="left"){el.style.borderLeftWidth=borderSize+"px";el.style.borderRightWidth="0px";}
else if(whichSide=="right"){el.style.borderRightWidth=borderSize+"px";el.style.borderLeftWidth="0px";}
else{el.style.borderLeftWidth=borderSize+"px";el.style.borderRightWidth=borderSize+"px";}
if(this.options.border!=false)
el.style.borderLeftWidth=borderSize+"px";el.style.borderRightWidth=borderSize+"px";},_marginSize:function(n){if(this._isTransparent())
return 0;var marginSizes=[5,3,2,1];var blendedMarginSizes=[3,2,1,0];var compactMarginSizes=[2,1];var smBlendedMarginSizes=[1,0];if(this.options.compact&&this.options.blend)
return smBlendedMarginSizes[n];else if(this.options.compact)
return compactMarginSizes[n];else if(this.options.blend)
return blendedMarginSizes[n];else
return marginSizes[n];},_borderSize:function(n){var transparentBorderSizes=[5,3,2,1];var blendedBorderSizes=[2,1,1,1];var compactBorderSizes=[1,0];var actualBorderSizes=[0,2,0,0];if(this.options.compact&&(this.options.blend||this._isTransparent()))
return 1;else if(this.options.compact)
return compactBorderSizes[n];else if(this.options.blend)
return blendedBorderSizes[n];else if(this.options.border)
return actualBorderSizes[n];else if(this._isTransparent())
return transparentBorderSizes[n];return 0;},_hasString:function(str){for(var i=1;i<arguments.length;i++)if(str.indexOf(arguments[i])>=0)return true;return false;},_blend:function(c1,c2){var cc1=Rico.Color.createFromHex(c1);cc1.blend(Rico.Color.createFromHex(c2));return cc1;},_background:function(el){try{return Rico.Color.createColorFromBackground(el).asHex();}catch(err){return"#ffffff";}},_isTransparent:function(){return this.options.color=="transparent";},_isTopRounded:function(){return this._hasString(this.options.corners,"all","top","tl","tr");},_isBottomRounded:function(){return this._hasString(this.options.corners,"all","bottom","bl","br");},_hasSingleTextChild:function(el){return el.childNodes.length==1&&el.childNodes[0].nodeType==3;}}
window.dhtmlHistory={isIE:false,isOpera:false,isSafari:false,isKonquerer:false,isGecko:false,isSupported:false,create:function(options){var that=this;window.historyStorage.setup(options);if(options&&options.baseTitle){if(options.baseTitle.indexOf("@@@")<0&&historyStorage.debugMode){throw new Error("Programmer error: options.baseTitle must contain the replacement parameter"
+" '@@@' to be useful.");}
this.baseTitle=options.baseTitle;}
var UA=navigator.userAgent.toLowerCase();var platform=navigator.platform.toLowerCase();var vendor=navigator.vendor||"";if(vendor==="KDE"){this.isKonqueror=true;this.isSupported=false;}else if(typeof window.opera!=="undefined"){this.isOpera=true;this.isSupported=true;}else if(typeof document.all!=="undefined"){this.isIE=true;this.isSupported=true;}else if(vendor.indexOf("Apple Computer, Inc.")>-1){this.isSafari=true;this.isSupported=(platform.indexOf("mac")>-1);}else if(UA.indexOf("gecko")!=-1){this.isGecko=true;this.isSupported=true;}
if(this.isSafari){this.createSafari();}else if(this.isOpera){this.createOpera();}
var initialHash=this.getCurrentLocation();this.currentLocation=initialHash;if(this.isIE){if(options&&options.blankURL){var u=options.blankURL;this.blankURL=(u.indexOf("?")!=u.length-1?u+"?":u);}
this.createIE(initialHash);}
var unloadHandler=function(){that.firstLoad=null;};this.addEventListener(window,'unload',unloadHandler);if(this.isIE){this.ignoreLocationChange=true;}else{if(!historyStorage.hasKey(this.PAGELOADEDSTRING)){this.ignoreLocationChange=true;this.firstLoad=true;historyStorage.put(this.PAGELOADEDSTRING,true);}else{this.ignoreLocationChange=false;this.firstLoad=false;this.fireOnNewListener=true;}}
var locationHandler=function(){that.checkLocation();};setInterval(locationHandler,100);},initialize:function(listener){this.originalTitle=document.title;if(this.isIE){if(!historyStorage.hasKey(this.PAGELOADEDSTRING)){this.fireOnNewListener=false;this.firstLoad=true;historyStorage.put(this.PAGELOADEDSTRING,true);}
else{this.fireOnNewListener=true;this.firstLoad=false;}}
if(listener){this.addListener(listener);}},addListener:function(listener){this.listener=listener;if(this.fireOnNewListener){this.fireHistoryEvent(this.currentLocation);this.fireOnNewListener=false;}},changeTitle:function(historyData){var winTitle=(historyData&&historyData.newTitle?this.baseTitle.replace('@@@',historyData.newTitle):this.originalTitle);if(document.title==winTitle){return;}
document.title=winTitle;if(this.isIE){this.iframe.contentWindow.document.title=winTitle;}
if(!this.isIE&&!this.isOpera){var hash=decodeURI(document.location.hash);if(hash!=""){var encodedHash=encodeURI(this.removeHash(hash));document.location.hash=encodedHash;}else{}}},add:function(newLocation,historyData){var that=this;var encodedLocation=encodeURI(this.removeHash(newLocation));if(this.isSafari){historyStorage.put(newLocation,historyData);this.currentLocation=encodedLocation;window.location.hash=encodedLocation;this.putSafariState(encodedLocation);this.changeTitle(historyData);}else{var addImpl=function(){if(that.currentWaitTime>0){that.currentWaitTime=that.currentWaitTime-that.waitTime;}
if(document.getElementById(encodedLocation)&&that.debugMode){var e="Exception: History locations can not have the same value as _any_ IDs that might be in the document,"
+" due to a bug in IE; please ask the developer to choose a history location that does not match any HTML"
+" IDs in this document. The following ID is already taken and cannot be a location: "+newLocation;throw new Error(e);}
historyStorage.put(newLocation,historyData);that.ignoreLocationChange=true;that.ieAtomicLocationChange=true;that.currentLocation=encodedLocation;window.location.hash=encodedLocation;if(that.isIE){that.iframe.src=that.blankURL+encodedLocation;}
that.ieAtomicLocationChange=false;that.changeTitle(historyData);};window.setTimeout(addImpl,this.currentWaitTime);this.currentWaitTime=this.currentWaitTime+this.waitTime;}},isFirstLoad:function(){return this.firstLoad;},getVersion:function(){return this.VERSIONNUMBER;},PAGELOADEDSTRING:"DhtmlHistory_pageLoaded",VERSIONNUMBER:"0.8",baseTitle:"@@@",originalTitle:null,blankURL:"/blank.html?",listener:null,waitTime:200,currentWaitTime:0,currentLocation:null,iframe:null,safariHistoryStartPoint:null,safariStack:null,safariLength:null,ignoreLocationChange:null,fireOnNewListener:null,firstLoad:null,ieAtomicLocationChange:null,addEventListener:function(o,e,l){if(o.addEventListener){o.addEventListener(e,l,false);}else if(o.attachEvent){o.attachEvent('on'+e,function(){l(window.event);});}},createIE:function(initialHash){this.waitTime=400;var styles=(historyStorage.debugMode?'width: 800px;height:80px;border:1px solid black;':historyStorage.hideStyles);var iframeID="rshHistoryFrame";var iframeHTML='<iframe frameborder="0" id="'+iframeID+'" style="'+styles+'" src="'+this.blankURL+initialHash+'"></iframe>';document.write(iframeHTML);this.iframe=document.getElementById(iframeID);},createOpera:function(){this.waitTime=400;var imgHTML='<img src="javascript:location.href=\'javascript:dhtmlHistory.checkLocation();\';" style="'+historyStorage.hideStyles+'" />';document.write(imgHTML);},createSafari:function(){var formID="rshSafariForm";var stackID="rshSafariStack";var lengthID="rshSafariLength";var formStyles=historyStorage.debugMode?historyStorage.showStyles:historyStorage.hideStyles;var stackStyles=(historyStorage.debugMode?'width: 800px;height:80px;border:1px solid black;':historyStorage.hideStyles);var lengthStyles=(historyStorage.debugMode?'width:800px;height:20px;border:1px solid black;margin:0;padding:0;':historyStorage.hideStyles);var safariHTML='<form id="'+formID+'" style="'+formStyles+'">'
+'<textarea style="'+stackStyles+'" id="'+stackID+'">[]</textarea>'
+'<input type="text" style="'+lengthStyles+'" id="'+lengthID+'" value=""/>'
+'</form>';document.write(safariHTML);this.safariStack=document.getElementById(stackID);this.safariLength=document.getElementById(lengthID);if(!historyStorage.hasKey(this.PAGELOADEDSTRING)){this.safariHistoryStartPoint=history.length;this.safariLength.value=this.safariHistoryStartPoint;}else{this.safariHistoryStartPoint=this.safariLength.value;}},getCurrentLocation:function(){var r=(this.isSafari?this.getSafariState():this.getCurrentHash());return r;},getCurrentHash:function(){var r=window.location.href;var i=r.indexOf("#");return(i>=0?r.substr(i+1):"");},getSafariStack:function(){var r=this.safariStack.value;return historyStorage.fromJSON(r);},getSafariState:function(){var stack=this.getSafariStack();var state=stack[history.length-this.safariHistoryStartPoint-1];return state;},putSafariState:function(newLocation){var stack=this.getSafariStack();stack[history.length-this.safariHistoryStartPoint]=newLocation;this.safariStack.value=historyStorage.toJSON(stack);},fireHistoryEvent:function(newHash){var decodedHash=decodeURI(newHash)
var historyData=historyStorage.get(decodedHash);this.changeTitle(historyData);this.listener.call(null,decodedHash,historyData);},checkLocation:function(){if(!this.isIE&&this.ignoreLocationChange){this.ignoreLocationChange=false;return;}
if(!this.isIE&&this.ieAtomicLocationChange){return;}
var hash=this.getCurrentLocation();if(hash==this.currentLocation){return;}
this.ieAtomicLocationChange=true;if(this.isIE&&this.getIframeHash()!=hash){this.iframe.src=this.blankURL+hash;}
else if(this.isIE){return;}
this.currentLocation=hash;this.ieAtomicLocationChange=false;this.fireHistoryEvent(hash);},getIframeHash:function(){var doc=this.iframe.contentWindow.document;var hash=String(doc.location.search);if(hash.length==1&&hash.charAt(0)=="?"){hash="";}
else if(hash.length>=2&&hash.charAt(0)=="?"){hash=hash.substring(1);}
return hash;},removeHash:function(hashValue){var r;if(hashValue===null||hashValue===undefined){r=null;}
else if(hashValue===""){r="";}
else if(hashValue.length==1&&hashValue.charAt(0)=="#"){r="";}
else if(hashValue.length>1&&hashValue.charAt(0)=="#"){r=hashValue.substring(1);}
else{r=hashValue;}
return r;},iframeLoaded:function(newLocation){if(this.ignoreLocationChange){this.ignoreLocationChange=false;return;}
var hash=String(newLocation.search);if(hash.length==1&&hash.charAt(0)=="?"){hash="";}
else if(hash.length>=2&&hash.charAt(0)=="?"){hash=hash.substring(1);}
window.location.hash=hash;this.fireHistoryEvent(hash);}};window.historyStorage={setup:function(options){if(typeof options!=="undefined"){if(options.debugMode){this.debugMode=options.debugMode;}
if(options.toJSON){this.toJSON=options.toJSON;}
if(options.fromJSON){this.fromJSON=options.fromJSON;}}
var formID="rshStorageForm";var textareaID="rshStorageField";var formStyles=this.debugMode?historyStorage.showStyles:historyStorage.hideStyles;var textareaStyles=(historyStorage.debugMode?'width: 800px;height:80px;border:1px solid black;':historyStorage.hideStyles);var textareaHTML='<form id="'+formID+'" style="'+formStyles+'">'
+'<textarea id="'+textareaID+'" style="'+textareaStyles+'"></textarea>'
+'</form>';document.write(textareaHTML);this.storageField=document.getElementById(textareaID);if(typeof window.opera!=="undefined"){this.storageField.focus();}},put:function(key,value){var encodedKey=encodeURI(key);this.assertValidKey(encodedKey);if(this.hasKey(key)){this.remove(key);}
this.storageHash[encodedKey]=value;this.saveHashTable();},get:function(key){var encodedKey=encodeURI(key);this.assertValidKey(encodedKey);this.loadHashTable();var value=this.storageHash[encodedKey];if(value===undefined){value=null;}
return value;},remove:function(key){var encodedKey=encodeURI(key);this.assertValidKey(encodedKey);this.loadHashTable();delete this.storageHash[encodedKey];this.saveHashTable();},reset:function(){this.storageField.value="";this.storageHash={};},hasKey:function(key){var encodedKey=encodeURI(key);this.assertValidKey(encodedKey);this.loadHashTable();return(typeof this.storageHash[encodedKey]!=="undefined");},isValidKey:function(key){return(typeof key==="string");},showStyles:'border:0;margin:0;padding:0;',hideStyles:'left:-1000px;top:-1000px;width:1px;height:1px;border:0;position:absolute;',debugMode:false,storageHash:{},hashLoaded:false,storageField:null,assertValidKey:function(key){var isValid=this.isValidKey(key);if(!isValid&&this.debugMode){throw new Error("Please provide a valid key for window.historyStorage. Invalid key = "+key+".");}},loadHashTable:function(){if(!this.hashLoaded){var serializedHashTable=this.storageField.value;if(serializedHashTable!==""&&serializedHashTable!==null){this.storageHash=this.fromJSON(serializedHashTable);this.hashLoaded=true;}}},saveHashTable:function(){this.loadHashTable();var serializedHashTable=this.toJSON(this.storageHash);this.storageField.value=serializedHashTable;},toJSON:function(o){return o.toJSONString();},fromJSON:function(s){return s.parseJSON();}};function Querystring(qs){this.params={};if(qs==null)qs=location.search.substring(1,location.search.length);if(qs.length==0)return;qs=qs.replace(/\+/g,' ');var args=qs.split('&');for(var i=0;i<args.length;i++){var pair=args[i].split('=');var name=decodeURI(pair[0]);var value=(pair.length==2)?decodeURI(pair[1]):name;this.params[name]=value;}}
Querystring.prototype.get=function(key,default_){var value=this.params[key];return(value!=null)?value:default_;}
Querystring.prototype.contains=function(key){var value=this.params[key];return(value!=null);}
window.dhtmlHistory.create({toJSON:function(o){return Object.toJSON(o);},fromJSON:function(s){return s.evalJSON();},blankURL:'/blank.html?'});var handleHistoryChange=function(pageId,pageData){if(!pageData)return;var info=pageId.split(':');var id=info[0];pageData+='&_method=get';new Ajax.Request(pageData,{asynchronous:true,evalScripts:true,method:'get',onLoading:function(request){Element.show(id+'-pagination-loading-indicator');}});}
window.onload=function(){dhtmlHistory.initialize(handleHistoryChange);};if(typeof Prototype=='undefined')
{warning="ActiveScaffold Error: Prototype could not be found. Please make sure that your application's layout includes prototype.js (e.g. <%= javascript_include_tag :defaults %>) *before* it includes active_scaffold.js (e.g. <%= active_scaffold_includes %>).";alert(warning);}
if(Prototype.Version.substring(0,3)!='1.6')
{warning="ActiveScaffold Error: Prototype version 1.6.x is required. Please update prototype.js (rake rails:update:javascripts).";alert(warning);}
if(!Element.Methods.highlight)Element.addMethods({highlight:Prototype.emptyFunction});var ActiveScaffold={records_for:function(tbody_id){var rows=[];var child=$(tbody_id).down('.record');while(child){rows.push(child);child=child.next('.record');}
return rows;},stripe:function(tbody_id){var even=false;var rows=this.records_for(tbody_id);for(var i=0;i<rows.length;i++){var child=rows[i];if(child.tagName!='SCRIPT'&&!child.hasClassName("create")&&!child.hasClassName("update")&&!child.hasClassName("inline-adapter")&&!child.hasClassName("active-scaffold-calculations")){if(even)child.addClassName("even-record");else child.removeClassName("even-record");even=!even;}}},hide_empty_message:function(tbody,empty_message_id){if(this.records_for(tbody).length!=0){$(empty_message_id).hide();}},reload_if_empty:function(tbody,url){if(this.records_for(tbody).length==0){new Ajax.Request(url,{method:'get',asynchronous:true,evalScripts:true});}},removeSortClasses:function(scaffold_id){$$('#'+scaffold_id+' td.sorted').each(function(element){element.removeClassName("sorted");});$$('#'+scaffold_id+' th.sorted').each(function(element){element.removeClassName("sorted");element.removeClassName("asc");element.removeClassName("desc");});},decrement_record_count:function(scaffold_id){count=$$('#'+scaffold_id+' span.active-scaffold-records').last();if(count)count.update(parseInt(count.innerHTML,10)-1);},increment_record_count:function(scaffold_id){count=$$('#'+scaffold_id+' span.active-scaffold-records').last();if(count)count.update(parseInt(count.innerHTML,10)+1);},update_row:function(row,html){row=$(row);Element.replace(row,html);var new_row=$(row.id);if(row.hasClassName('even-record'))new_row.addClassName('even-record');new_row.highlight();},server_error_response:'',report_500_response:function(active_scaffold_id){messages_container=$(active_scaffold_id).down('td.messages-container');new Insertion.Top(messages_container,this.server_error_response);}}
function addActiveScaffoldPageToHistory(url,active_scaffold_id){if(typeof dhtmlHistory=='undefined')return;var array=url.split('?');var qs=new Querystring(array[1]);var sort=qs.get('sort')
var dir=qs.get('sort_direction')
var page=qs.get('page')
if(sort||dir||page)dhtmlHistory.add(active_scaffold_id+":"+page+":"+sort+":"+dir,url);}
Element.replace=function(element,html){element=$(element);if(element.outerHTML){try{element.outerHTML=html.stripScripts();}catch(e){var tn=element.tagName;if(tn=='TBODY'||tn=='TR'||tn=='TD')
{var tempDiv=document.createElement("div");tempDiv.innerHTML='<table id="tempTable" style="display: none">'+html.stripScripts()+'</table>';element.parentNode.replaceChild(tempDiv.getElementsByTagName(tn).item(0),element);}
else throw e;}}else{var range=element.ownerDocument.createRange();range.selectNodeContents(element.parentNode);element.parentNode.replaceChild(range.createContextualFragment(html.stripScripts()),element);}
setTimeout(function(){html.evalScripts()},10);return element;};Object.extend(String.prototype,{append_params:function(params){url=this;if(url.indexOf('?')==-1)url+='?';else if(url.lastIndexOf('&')!=url.length)url+='&';url+=$H(params).collect(function(item){return item.key+'='+item.value;}).join('&');return url;}});Element.Methods.Simulated={hasAttribute:function(element,attribute){var t=Element._attributeTranslations;attribute=(t.names&&t.names[attribute])||attribute;try{return $(element).getAttributeNode(attribute).specified;}catch(e){return false;}}};ActiveScaffold.Actions=new Object();ActiveScaffold.Actions.Abstract=Class.create({initialize:function(links,target,loading_indicator,options){this.target=$(target);this.loading_indicator=$(loading_indicator);this.options=options;this.links=links.collect(function(link){return this.instantiate_link(link);}.bind(this));},instantiate_link:function(link){throw'unimplemented'}});ActiveScaffold.ActionLink=new Object();ActiveScaffold.ActionLink.Abstract=Class.create({initialize:function(a,target,loading_indicator){this.tag=$(a);this.url=this.tag.href;this.method='get';if(this.url.match('_method=delete')){this.method='delete';}else if(this.url.match('_method=post')){this.method='post';}else if(this.url.match('_method=put')){this.method='put';}
this.target=target;this.loading_indicator=loading_indicator;this.hide_target=false;this.position=this.tag.getAttribute('position');this.page_link=this.tag.getAttribute('page_link');this.onclick=this.tag.onclick;this.tag.onclick=null;this.tag.observe('click',function(event){this.open();Event.stop(event);}.bind(this));this.tag.action_link=this;},open:function(){if(this.is_disabled())return;if(this.tag.hasAttribute("dhtml_confirm")){if(this.onclick)this.onclick();return;}else{if(this.onclick&&!this.onclick())return;this.open_action();}},open_action:function(){if(this.position)this.disable();if(this.page_link){window.location=this.url;}else{if(this.loading_indicator)this.loading_indicator.style.visibility='visible';new Ajax.Request(this.url,{asynchronous:true,evalScripts:true,method:this.method,onSuccess:function(request){if(this.position){this.insert(request.responseText);if(this.hide_target)this.target.hide();}else{request.evalResponse();}}.bind(this),onFailure:function(request){ActiveScaffold.report_500_response(this.scaffold_id());if(this.position)this.enable()}.bind(this),onComplete:function(request){if(this.loading_indicator)this.loading_indicator.style.visibility='hidden';}.bind(this)});}},insert:function(content){throw'unimplemented'},close:function(){this.enable();this.adapter.remove();if(this.hide_target)this.target.show();},close_handler:function(event){this.close();if(event)Event.stop(event);},register_cancel_hooks:function(){var self=this;this.adapter.select('.cancel').each(function(elem){elem.observe('click',this.close_handler.bind(this));elem.link=self;}.bind(this))},reload:function(){this.close();this.open();},get_new_adapter_id:function(){var id='adapter_';var i=0;while($(id+i))i++;return id+i;},enable:function(){return this.tag.removeClassName('disabled');},disable:function(){return this.tag.addClassName('disabled');},is_disabled:function(){return this.tag.hasClassName('disabled');},scaffold_id:function(){return this.tag.up('div.active-scaffold').id;}});ActiveScaffold.Actions.Record=Class.create(ActiveScaffold.Actions.Abstract,{instantiate_link:function(link){var l=new ActiveScaffold.ActionLink.Record(link,this.target,this.loading_indicator);l.refresh_url=this.options.refresh_url;if(link.hasClassName('delete')){l.url=l.url.replace(/\/delete(\?.*)?$/,'$1');l.url=l.url.replace(/\/delete\/(.*)/,'/destroy/$1');}
if(l.position)l.url=l.url.append_params({adapter:'_list_inline_adapter'});l.set=this;return l;}});ActiveScaffold.ActionLink.Record=Class.create(ActiveScaffold.ActionLink.Abstract,{close_previous_adapter:function(){this.set.links.each(function(item){if(item.url!=this.url&&item.is_disabled()&&item.adapter){item.enable();item.adapter.remove();}}.bind(this));},insert:function(content){this.close_previous_adapter();if(this.position=='replace'){this.position='after';this.hide_target=true;}
if(this.position=='after'){new Insertion.After(this.target,content);this.adapter=this.target.next();}
else if(this.position=='before'){new Insertion.Before(this.target,content);this.adapter=this.target.previous();}
else{return false;}
this.adapter.down('a.inline-adapter-close').observe('click',this.close_handler.bind(this));this.register_cancel_hooks();this.adapter.down('td').down().highlight();},close:function($super,updatedRow){if(updatedRow){ActiveScaffold.update_row(this.target,updatedRow);$super();}else{new Ajax.Request(this.refresh_url,{asynchronous:true,evalScripts:true,method:this.method,onSuccess:function(request){ActiveScaffold.update_row(this.target,request.responseText);$super();}.bind(this),onFailure:function(request){ActiveScaffold.report_500_response(this.scaffold_id());}});}},enable:function(){this.set.links.each(function(item){if(item.url!=this.url)return;item.tag.removeClassName('disabled');}.bind(this));},disable:function(){this.set.links.each(function(item){if(item.url!=this.url)return;item.tag.addClassName('disabled');}.bind(this));}});ActiveScaffold.Actions.Table=Class.create(ActiveScaffold.Actions.Abstract,{instantiate_link:function(link){var l=new ActiveScaffold.ActionLink.Table(link,this.target,this.loading_indicator);if(l.position)l.url=l.url.append_params({adapter:'_list_inline_adapter'});return l;}});ActiveScaffold.ActionLink.Table=Class.create(ActiveScaffold.ActionLink.Abstract,{insert:function(content){if(this.position=='top'){new Insertion.Top(this.target,content);this.adapter=this.target.immediateDescendants().first();}
else{throw'Unknown position "'+this.position+'"'}
this.adapter.down('a.inline-adapter-close').observe('click',this.close_handler.bind(this));this.register_cancel_hooks();this.adapter.down('td').down().highlight();}});if(Ajax.InPlaceEditor){ActiveScaffold.InPlaceEditor=Class.create(Ajax.InPlaceEditor,{setFieldFromAjax:function(url,options){var ipe=this;$(ipe._controls.editor).remove();new Ajax.Request(url,{method:'get',onComplete:function(response){ipe._form.insert({top:response.responseText});if(options.plural){ipe._form.getElements().each(function(el){if(el.type!="submit"&&el.type!="image"){el.name=ipe.options.paramName+'[]';el.className='editor_field';}});}else{var fld=ipe._form.findFirstElement();fld.name=ipe.options.paramName;fld.className='editor_field';if(ipe.options.submitOnBlur)
fld.onblur=ipe._boundSubmitHandler;ipe._controls.editor=fld;}}});},clonePatternField:function(){var patternNodes=this.getPatternNodes(this.options.inplacePatternSelector);if(patternNodes.editNode==null){alert('did not find any matching node for '+this.options.editFieldSelector);return;}
var fld=patternNodes.editNode.cloneNode(true);if(fld.id.length>0)fld.id+=this.options.nodeIdSuffix;fld.name=this.options.paramName;fld.className='editor_field';this.setValue(fld,this._controls.editor.value);if(this.options.submitOnBlur)
fld.onblur=this._boundSubmitHandler;$(this._controls.editor).remove();this._controls.editor=fld;this._form.appendChild(this._controls.editor);$A(patternNodes.additionalNodes).each(function(node){var patternNode=node.cloneNode(true);if(patternNode.id.length>0){patternNode.id=patternNode.id+this.options.nodeIdSuffix;}
this._form.appendChild(patternNode);}.bind(this));},getPatternNodes:function(inplacePatternSelector){var nodes={editNode:null,additionalNodes:[]};var selectedNodes=$$(inplacePatternSelector);var firstNode=selectedNodes.first();if(typeof(firstNode)!=='undefined'){if(firstNode.className.indexOf('as_inplace_pattern')!==-1){selectedNodes=firstNode.childElements();}
nodes.editNode=selectedNodes.first();selectedNodes.shift();nodes.additionalNodes=selectedNodes;}
return nodes;},setValue:function(editField,textValue){var function_name='setValueFor'+editField.nodeName.toLowerCase();if(typeof(this[function_name])=='function'){this[function_name](editField,textValue);}else{editField.value=textValue;}},setValueForselect:function(editField,textValue){var len=editField.options.length;var i=0;while(i<len&&editField.options[i].text!=textValue){i++;}
if(i<len){editField.value=editField.options[i].value}}});}
TextFieldWithExample=Class.create();TextFieldWithExample.prototype={initialize:function(inputElementId,defaultText,options){this.setOptions(options);this.input=$(inputElementId);this.name=this.input.name;this.defaultText=defaultText;this.createHiddenInput();if(options.focus)this.input.focus();this.checkAndShowExample();if(options.focus){this.input.selectionStart=0;this.input.selectionEnd=0;}
Event.observe(this.input,"blur",this.onBlur.bindAsEventListener(this));Event.observe(this.input,"focus",this.onFocus.bindAsEventListener(this));Event.observe(this.input,"select",this.onFocus.bindAsEventListener(this));Event.observe(this.input,"keydown",this.onKeyPress.bindAsEventListener(this));Event.observe(this.input,"click",this.onClick.bindAsEventListener(this));},createHiddenInput:function(){this.hiddenInput=document.createElement("input");this.hiddenInput.type="hidden";this.hiddenInput.value="";this.input.parentNode.appendChild(this.hiddenInput);},setOptions:function(options){this.options={exampleClassName:'example'};Object.extend(this.options,options||{});},onKeyPress:function(event){if(!event)var event=window.event;var code=(event.which)?event.which:event.keyCode
if(this.isAlphanumeric(code)){this.removeExample();}},onBlur:function(event){this.checkAndShowExample();},onFocus:function(event){this.removeExample();},onClick:function(event){this.removeExample();},isAlphanumeric:function(keyCode){return keyCode>=40&&keyCode<=90;},checkAndShowExample:function(){if(this.input.value==''){this.input.value=this.defaultText;this.input.name=null;this.hiddenInput.name=this.name;Element.addClassName(this.input,this.options.exampleClassName);}},removeExample:function(){if(this.exampleShown()){this.input.value='';this.input.name=this.name;this.hiddenInput.name=null;Element.removeClassName(this.input,this.options.exampleClassName);}},exampleShown:function(){return Element.hasClassName(this.input,this.options.exampleClassName);}}
Form.disable=function(form){var elements=this.getElements(form);for(var i=0;i<elements.length;i++){var element=elements[i];try{element.blur();}catch(e){}
element.disabled='disabled';Element.addClassName(element,'disabled');}}
Form.enable=function(form){var elements=this.getElements(form);for(var i=0;i<elements.length;i++){var element=elements[i];element.disabled='';Element.removeClassName(element,'disabled');}}
DraggableLists=Class.create({initialize:function(list){list=$(list).addClassName('draggable-list');var list_selected=list.cloneNode(false).addClassName('selected');list_selected.id+='_seleted';list.select('input[type=checkbox]').each(function(item){var li=item.up('li');li.down('label').htmlFor=null;new Draggable(li,{revert:'failure',ghosting:true});if(item.checked)list_selected.insert(li.remove());});list.insert({after:list_selected});Droppables.add(list,{hoverclass:'hover',containment:list_selected.id,onDrop:this.drop_to_list});Droppables.add(list_selected,{hoverclass:'hover',containment:list.id,onDrop:this.drop_to_list});list.undoPositioned();list_selected.undoPositioned();},drop_to_list:function(draggable,droppable,event){droppable.insert(draggable.remove());draggable.setStyle({left:'0px',top:'0px'});draggable.down('input').checked=droppable.hasClassName('selected');}});if(typeof Prototype=='undefined')alert("CalendarDateSelect Error: Prototype could not be found. Please make sure that your application's layout includes prototype.js (.g. <%= javascript_include_tag :defaults %>) *before* it includes calendar_date_select.js (.g. <%= calendar_date_select_includes %>).");if(Prototype.Version<"1.6")alert("Prototype 1.6.0 is required.  If using earlier version of prototype, please use calendar_date_select version 1.8.3");Element.addMethods({purgeChildren:function(element){$A(element.childNodes).each(function(e){$(e).remove();});},build:function(element,type,options,style){var newElement=Element.buildAndAppend(type,options,style);element.appendChild(newElement);return newElement;}});Element.buildAndAppend=function(type,options,style)
{var e=$(document.createElement(type));$H(options).each(function(pair){e[pair.key]=pair.value});if(style)e.setStyle(style);return e;};nil=null;Date.one_day=24*60*60*1000;Date.weekdays=$w("S M T W T F S");Date.first_day_of_week=0;Date.months=$w("January February March April May June July August September October November December");Date.padded2=function(hour){var padded2=parseInt(hour,10);if(hour<10)padded2="0"+padded2;return padded2;}
Date.prototype.getPaddedMinutes=function(){return Date.padded2(this.getMinutes());}
Date.prototype.getAMPMHour=function(){var hour=this.getHours();return(hour==0)?12:(hour>12?hour-12:hour)}
Date.prototype.getAMPM=function(){return(this.getHours()<12)?"AM":"PM";}
Date.prototype.stripTime=function(){return new Date(this.getFullYear(),this.getMonth(),this.getDate());};Date.prototype.daysDistance=function(compare_date){return Math.round((compare_date-this)/Date.one_day);};Date.prototype.toFormattedString=function(include_time){var hour,str;str=Date.months[this.getMonth()]+" "+this.getDate()+", "+this.getFullYear();if(include_time){hour=this.getHours();str+=" "+this.getAMPMHour()+":"+this.getPaddedMinutes()+" "+this.getAMPM()}
return str;}
Date.parseFormattedString=function(string){return new Date(string);}
Math.floor_to_interval=function(n,i){return Math.floor(n/i)*i;}
window.f_height=function(){return([window.innerHeight?window.innerHeight:null,document.documentElement?document.documentElement.clientHeight:null,document.body?document.body.clientHeight:null].select(function(x){return x>0}).first()||0);}
window.f_scrollTop=function(){return([window.pageYOffset?window.pageYOffset:null,document.documentElement?document.documentElement.scrollTop:null,document.body?document.body.scrollTop:null].select(function(x){return x>0}).first()||0);}
_translations={"OK":"OK","Now":"Now","Today":"Today","Clear":"Clear"}
SelectBox=Class.create();SelectBox.prototype={initialize:function(parent_element,values,html_options,style_options){this.element=$(parent_element).build("select",html_options,style_options);this.populate(values);},populate:function(values){this.element.purgeChildren();var that=this;$A(values).each(function(pair){if(typeof(pair)!="object"){pair=[pair,pair]};that.element.build("option",{value:pair[1],innerHTML:pair[0]})});},setValue:function(value){var e=this.element;var matched=false;$R(0,e.options.length-1).each(function(i){if(e.options[i].value==value.toString()){e.selectedIndex=i;matched=true;};});return matched;},getValue:function(){return $F(this.element)}}
CalendarDateSelect=Class.create();CalendarDateSelect.prototype={initialize:function(target_element,options){this.target_element=$(target_element);if(!this.target_element){alert("Target element "+target_element+" not found!");return false;}
if(this.target_element.tagName!="INPUT")this.target_element=this.target_element.down("INPUT")
this.target_element.calendar_date_select=this;this.last_click_at=0;this.options=$H({embedded:false,popup:nil,time:false,buttons:true,clear_button:true,year_range:10,close_on_click:nil,minute_interval:5,popup_by:this.target_element,month_year:"dropdowns",onchange:this.target_element.onchange,valid_date_check:nil}).merge(options||{});this.use_time=this.options.get("time");this.parseDate();this.callback("before_show")
this.initCalendarDiv();if(!this.options.get("embedded")){this.positionCalendarDiv()
Event.observe(document,"mousedown",this.closeIfClickedOut_handler=this.closeIfClickedOut.bindAsEventListener(this));Event.observe(document,"keypress",this.keyPress_handler=this.keyPress.bindAsEventListener(this));}
this.callback("after_show")},positionCalendarDiv:function(){var above=false;var c_pos=this.calendar_div.cumulativeOffset(),c_left=c_pos[0],c_top=c_pos[1],c_dim=this.calendar_div.getDimensions(),c_height=c_dim.height,c_width=c_dim.width;var w_top=window.f_scrollTop(),w_height=window.f_height();var e_dim=$(this.options.get("popup_by")).cumulativeOffset(),e_top=e_dim[1],e_left=e_dim[0],e_height=$(this.options.get("popup_by")).getDimensions().height,e_bottom=e_top+e_height;if(((e_bottom+c_height)>(w_top+w_height))&&(e_bottom-c_height>w_top))above=true;var left_px=e_left.toString()+"px",top_px=(above?(e_top-c_height):(e_top+e_height)).toString()+"px";this.calendar_div.style.left=left_px;this.calendar_div.style.top=top_px;this.calendar_div.setStyle({visibility:""});if(navigator.appName=="Microsoft Internet Explorer")this.iframe=$(document.body).build("iframe",{src:"javascript:false",className:"ie6_blocker"},{left:left_px,top:top_px,height:c_height.toString()+"px",width:c_width.toString()+"px",border:"0px"})},initCalendarDiv:function(){if(this.options.get("embedded")){var parent=this.target_element.parentNode;var style={}}else{var parent=document.body
var style={position:"absolute",visibility:"hidden",left:0,top:0}}
this.calendar_div=$(parent).build('div',{className:"calendar_date_select"},style);var that=this;$w("top header body buttons footer bottom").each(function(name){eval("var "+name+"_div = that."+name+"_div = that.calendar_div.build('div', { className: 'cds_"+name+"' }, { clear: 'left'} ); ");});this.initHeaderDiv();this.initButtonsDiv();this.initCalendarGrid();this.updateFooter("&#160;");this.refresh();this.setUseTime(this.use_time);},initHeaderDiv:function(){var header_div=this.header_div;this.close_button=header_div.build("a",{innerHTML:"x",href:"#",onclick:function(){this.close();return false;}.bindAsEventListener(this),className:"close"});this.next_month_button=header_div.build("a",{innerHTML:"&gt;",href:"#",onclick:function(){this.navMonth(this.date.getMonth()+1);return false;}.bindAsEventListener(this),className:"next"});this.prev_month_button=header_div.build("a",{innerHTML:"&lt;",href:"#",onclick:function(){this.navMonth(this.date.getMonth()-1);return false;}.bindAsEventListener(this),className:"prev"});if(this.options.get("month_year")=="dropdowns"){this.month_select=new SelectBox(header_div,$R(0,11).map(function(m){return[Date.months[m],m]}),{className:"month",onchange:function(){this.navMonth(this.month_select.getValue())}.bindAsEventListener(this)});this.year_select=new SelectBox(header_div,[],{className:"year",onchange:function(){this.navYear(this.year_select.getValue())}.bindAsEventListener(this)});this.populateYearRange();}else{this.month_year_label=header_div.build("span")}},initCalendarGrid:function(){var body_div=this.body_div;this.calendar_day_grid=[];var days_table=body_div.build("table",{cellPadding:"0px",cellSpacing:"0px",width:"100%"})
var weekdays_row=days_table.build("thead").build("tr");Date.weekdays.each(function(weekday){weekdays_row.build("th",{innerHTML:weekday});});var days_tbody=days_table.build("tbody")
var row_number=0,weekday;for(var cell_index=0;cell_index<42;cell_index++)
{weekday=(cell_index+Date.first_day_of_week)%7;if(cell_index%7==0)days_row=days_tbody.build("tr",{className:'row_'+row_number++});(this.calendar_day_grid[cell_index]=days_row.build("td",{calendar_date_select:this,onmouseover:function(){this.calendar_date_select.dayHover(this);},onmouseout:function(){this.calendar_date_select.dayHoverOut(this)},onclick:function(){this.calendar_date_select.updateSelectedDate(this,true);},className:(weekday==0)||(weekday==6)?" weekend":""},{cursor:"pointer"})).build("div");this.calendar_day_grid[cell_index];}},initButtonsDiv:function()
{var buttons_div=this.buttons_div;if(this.options.get("time"))
{var blank_time=$A(this.options.get("time")=="mixed"?[[" - ",""]]:[]);buttons_div.build("span",{innerHTML:"@",className:"at_sign"});var t=new Date();this.hour_select=new SelectBox(buttons_div,blank_time.concat($R(0,23).map(function(x){t.setHours(x);return $A([t.getAMPMHour()+" "+t.getAMPM(),x])})),{calendar_date_select:this,onchange:function(){this.calendar_date_select.updateSelectedDate({hour:this.value});},className:"hour"});buttons_div.build("span",{innerHTML:":",className:"seperator"});var that=this;this.minute_select=new SelectBox(buttons_div,blank_time.concat($R(0,59).select(function(x){return(x%that.options.get('minute_interval')==0)}).map(function(x){return $A([Date.padded2(x),x]);})),{calendar_date_select:this,onchange:function(){this.calendar_date_select.updateSelectedDate({minute:this.value})},className:"minute"});}else if(!this.options.get("buttons"))buttons_div.remove();if(this.options.get("buttons")){buttons_div.build("span",{innerHTML:"&#160;"});if(this.options.get("time")=="mixed"||!this.options.get("time"))b=buttons_div.build("a",{innerHTML:_translations["Today"],href:"#",onclick:function(){this.today(false);return false;}.bindAsEventListener(this)});if(this.options.get("time")=="mixed")buttons_div.build("span",{innerHTML:"&#160;|&#160;",className:"button_seperator"})
if(this.options.get("time"))b=buttons_div.build("a",{innerHTML:_translations["Now"],href:"#",onclick:function(){this.today(true);return false}.bindAsEventListener(this)});if(!this.options.get("embedded")&&!this.closeOnClick())
{buttons_div.build("span",{innerHTML:"&#160;|&#160;",className:"button_seperator"})
buttons_div.build("a",{innerHTML:_translations["OK"],href:"#",onclick:function(){this.close();return false;}.bindAsEventListener(this)});}
if(this.options.get('clear_button')){buttons_div.build("span",{innerHTML:"&#160;|&#160;",className:"button_seperator"})
buttons_div.build("a",{innerHTML:_translations["Clear"],href:"#",onclick:function(){this.clearDate();if(!this.options.get("embedded"))this.close();return false;}.bindAsEventListener(this)});}}},refresh:function()
{this.refreshMonthYear();this.refreshCalendarGrid();this.setSelectedClass();this.updateFooter();},refreshCalendarGrid:function(){this.beginning_date=new Date(this.date).stripTime();this.beginning_date.setDate(1);this.beginning_date.setHours(12);var pre_days=this.beginning_date.getDay()
if(pre_days<3)pre_days+=7;this.beginning_date.setDate(1-pre_days+Date.first_day_of_week);var iterator=new Date(this.beginning_date);var today=new Date().stripTime();var this_month=this.date.getMonth();vdc=this.options.get("valid_date_check");for(var cell_index=0;cell_index<42;cell_index++)
{day=iterator.getDate();month=iterator.getMonth();cell=this.calendar_day_grid[cell_index];Element.remove(cell.childNodes[0]);div=cell.build("div",{innerHTML:day});if(month!=this_month)div.className="other";cell.day=day;cell.month=month;cell.year=iterator.getFullYear();if(vdc){if(vdc(iterator.stripTime()))cell.removeClassName("disabled");else cell.addClassName("disabled")};iterator.setDate(day+1);}
if(this.today_cell)this.today_cell.removeClassName("today");if($R(0,41).include(days_until=this.beginning_date.stripTime().daysDistance(today))){this.today_cell=this.calendar_day_grid[days_until];this.today_cell.addClassName("today");}},refreshMonthYear:function(){var m=this.date.getMonth();var y=this.date.getFullYear();if(this.options.get("month_year")=="dropdowns")
{this.month_select.setValue(m,false);var e=this.year_select.element;if(this.flexibleYearRange()&&(!(this.year_select.setValue(y,false))||e.selectedIndex<=1||e.selectedIndex>=e.options.length-2))this.populateYearRange();this.year_select.setValue(y);}else{this.month_year_label.update(Date.months[m]+" "+y.toString());}},populateYearRange:function(){this.year_select.populate(this.yearRange().toArray());},yearRange:function(){if(!this.flexibleYearRange())
return $R(this.options.get("year_range")[0],this.options.get("year_range")[1]);var y=this.date.getFullYear();return $R(y-this.options.get("year_range"),y+this.options.get("year_range"));},flexibleYearRange:function(){return(typeof(this.options.get("year_range"))=="number");},validYear:function(year){if(this.flexibleYearRange()){return true;}else{return this.yearRange().include(year);}},dayHover:function(element){var hover_date=new Date(this.selected_date);hover_date.setYear(element.year);hover_date.setMonth(element.month);hover_date.setDate(element.day);this.updateFooter(hover_date.toFormattedString(this.use_time));},dayHoverOut:function(element){this.updateFooter();},clearSelectedClass:function(){if(this.selected_cell)this.selected_cell.removeClassName("selected");},setSelectedClass:function(){if(!this.selection_made)return;this.clearSelectedClass()
if($R(0,42).include(days_until=this.beginning_date.stripTime().daysDistance(this.selected_date.stripTime()))){this.selected_cell=this.calendar_day_grid[days_until];this.selected_cell.addClassName("selected");}},reparse:function(){this.parseDate();this.refresh();},dateString:function(){return(this.selection_made)?this.selected_date.toFormattedString(this.use_time):"&#160;";},parseDate:function()
{var value=$F(this.target_element).strip()
this.selection_made=(value!="");this.date=value==""?NaN:Date.parseFormattedString(this.options.get("date")||value);if(isNaN(this.date))this.date=new Date();if(!this.validYear(this.date.getFullYear()))this.date.setYear((this.date.getFullYear()<this.yearRange().start)?this.yearRange().start:this.yearRange().end);this.selected_date=new Date(this.date);this.use_time=/[0-9]:[0-9]{2}/.exec(value)?true:false;this.date.setDate(1);},updateFooter:function(text){if(!text)text=this.dateString();this.footer_div.purgeChildren();this.footer_div.build("span",{innerHTML:text});},clearDate:function(){if((this.target_element.disabled||this.target_element.readOnly)&&this.options.get("popup")!="force")return false;var last_value=this.target_element.value;this.target_element.value="";this.clearSelectedClass();this.updateFooter('&#160;');if(last_value!=this.target_element.value)this.callback("onchange");},updateSelectedDate:function(partsOrElement,via_click){var parts=$H(partsOrElement);if((this.target_element.disabled||this.target_element.readOnly)&&this.options.get("popup")!="force")return false;if(parts.get("day")){var t_selected_date=this.selected_date,vdc=this.options.get("valid_date_check");for(var x=0;x<=3;x++)t_selected_date.setDate(parts.get("day"));t_selected_date.setYear(parts.get("year"));t_selected_date.setMonth(parts.get("month"));if(vdc&&!vdc(t_selected_date.stripTime())){return false;}
this.selected_date=t_selected_date;this.selection_made=true;}
if(!isNaN(parts.get("hour")))this.selected_date.setHours(parts.get("hour"));if(!isNaN(parts.get("minute")))this.selected_date.setMinutes(Math.floor_to_interval(parts.get("minute"),this.options.get("minute_interval")));if(parts.get("hour")===""||parts.get("minute")==="")
this.setUseTime(false);else if(!isNaN(parts.get("hour"))||!isNaN(parts.get("minute")))
this.setUseTime(true);this.updateFooter();this.setSelectedClass();if(this.selection_made)this.updateValue();if(this.closeOnClick()){this.close();}
if(via_click&&!this.options.get("embedded")){if((new Date()-this.last_click_at)<333)this.close();this.last_click_at=new Date();}},closeOnClick:function(){if(this.options.get("embedded"))return false;if(this.options.get("close_on_click")===nil)
return(this.options.get("time"))?false:true
else
return(this.options.get("close_on_click"))},navMonth:function(month){(target_date=new Date(this.date)).setMonth(month);return(this.navTo(target_date));},navYear:function(year){(target_date=new Date(this.date)).setYear(year);return(this.navTo(target_date));},navTo:function(date){if(!this.validYear(date.getFullYear()))return false;this.date=date;this.date.setDate(1);this.refresh();this.callback("after_navigate",this.date);return true;},setUseTime:function(turn_on){this.use_time=this.options.get("time")&&(this.options.get("time")=="mixed"?turn_on:true)
if(this.use_time&&this.selected_date){var minute=Math.floor_to_interval(this.selected_date.getMinutes(),this.options.get("minute_interval"));var hour=this.selected_date.getHours();this.hour_select.setValue(hour);this.minute_select.setValue(minute)}else if(this.options.get("time")=="mixed"){this.hour_select.setValue("");this.minute_select.setValue("");}},updateValue:function(){var last_value=this.target_element.value;this.target_element.value=this.dateString();if(last_value!=this.target_element.value)this.callback("onchange");},today:function(now){var d=new Date();this.date=new Date();var o=$H({day:d.getDate(),month:d.getMonth(),year:d.getFullYear(),hour:d.getHours(),minute:d.getMinutes()});if(!now)o=o.merge({hour:"",minute:""});this.updateSelectedDate(o,true);this.refresh();},close:function(){if(this.closed)return false;this.callback("before_close");this.target_element.calendar_date_select=nil;Event.stopObserving(document,"mousedown",this.closeIfClickedOut_handler);Event.stopObserving(document,"keypress",this.keyPress_handler);this.calendar_div.remove();this.closed=true;if(this.iframe)this.iframe.remove();if(this.target_element.type!="hidden"&&!this.target_element.disabled)this.target_element.focus();this.callback("after_close");},closeIfClickedOut:function(e){if(!$(Event.element(e)).descendantOf(this.calendar_div))this.close();},keyPress:function(e){if(e.keyCode==Event.KEY_ESC)this.close();},callback:function(name,param){if(this.options.get(name)){this.options.get(name).bind(this.target_element)(param);}}}
