/*
 MIT
 @url http://livepipe.net/core
 @require prototype.js
 MIT
 @url http://livepipe.net/control/tabs
 @require prototype.js, livepipe.js
 MIT
 @url http://livepipe.net/control/rating
 @require prototype.js, livepipe.js
 MIT
 @url http://livepipe.net/control/progressbar
 @require prototype.js, livepipe.js
*/
if(typeof BrainstormJs=="undefined"){BrainstormJs={};BrainstormJs.Controls={};BrainstormJs.Controls.Comments={};BrainstormJs.Controls.Follow={};BrainstormJs.Controls.Grid={};BrainstormJs.Controls.Input={};BrainstormJs.Controls.Parts={};BrainstormJs.Controls.ModalBox={};BrainstormJs.Controls.CustomFields={};BrainstormJs.Controls.CustomFields.Forms={};BrainstormJs.Controls.DataFilters={};BrainstormJs.Controls.DataFilters.Input={};BrainstormJs.Controls.Evaluation={};BrainstormJs.Controls.Messaging={};
BrainstormJs.Forms={};BrainstormJs.Forms.Fields={};BrainstormJs.Forms.Fields.MultiSelect={};BrainstormJs.Forms.Grid={};BrainstormJs.Forms.Parts={};BrainstormJs.Forms.TenantProfile={};BrainstormJs.Parts={};BrainstormJs.Modules={};BrainstormJs.Modules.Idea={};BrainstormJs.Modules.Person={};BrainstormJs.Modules.Feedback={};BrainstormJs.Modules.Tag={};BrainstormJs.Modules.PipelineProfile={};BrainstormJs.Modules.ChallengeProfile={};BrainstormJs.Modules.TenantProfile={};BrainstormJs.Profiles={};BrainstormJs.Pages=
{};BrainstormJs.Admin={};BrainstormJs.Admin.Forms={};BrainstormJs.Admin.Forms.Instance={};BrainstormJs.Admin.Forms.Tenant={};BrainstormJs.Admin.Forms.Fields={};BrainstormJs.Admin.Pages={}}if(!window.console){window.console={};window.console.log=console.log||function(){};window.console.warn=console.warn||function(){};window.console.error=console.error||function(){};window.console.info=console.info||function(){}}
BrainstormJs.Analytics={scTrackOpenForm:function(formName){this.scTrackEvent(["scOpen"],formName+" form open",{prop5:formName,eVar5:formName})},scTrackSubmitForm:function(formName){this.scTrackEvent(["scCheckout"],formName+" form submit",{prop5:formName})},scTrackAction:function(actionType,actionId){var actionString=actionType+":"+actionId;this.scTrackEvent([],"click help link",{prop6:actionString})},scTrackEvent:function(events,actionId,vars){try{if(!this.scIsEnabled())return;var s=s_gi(s_account);
var eventString=events.join(",");var sendVars=this.getTrackVars(vars);sendVars.unshift("events","prop1","eVar1","prop2","eVar2","prop3","campaign");s.campaign=s.prop3;s.linkTrackVars=sendVars.join(",");s.linkTrackEvents=eventString;s.events=eventString;Object.extend(s,vars);s.tl(null,"o",actionId)}catch(exception){console.exception(exception)}},scIsEnabled:function(){return typeof s_account!="undefined"},getTrackVars:function(vars){return Object.keys(vars)}};
BrainstormJs.Utils={disableTinyMceSpellChecking:function(){if(Prototype.Browser.IE)if(typeof window.tinyMCE!=="undefined")for(var id in tinyMCE.editors){var ed=tinyMCE.editors[id];if(ed.plugins&&ed.plugins.spellchecker&&ed.plugins.spellchecker.active)ed.plugins.spellchecker._done()}},hasPlaceholderSupport:function(){var i=document.createElement("input");return"placeholder"in i}};
var Prototype={Version:"1.7",Browser:function(){var ua=navigator.userAgent;var isOpera=Object.prototype.toString.call(window.opera)=="[object Opera]";return{IE:!!window.attachEvent&&!isOpera,Opera:isOpera,WebKit:ua.indexOf("AppleWebKit/")>-1,Gecko:ua.indexOf("Gecko")>-1&&ua.indexOf("KHTML")===-1,MobileSafari:/Apple.*Mobile/.test(ua)}}(),BrowserFeatures:{XPath:!!document.evaluate,SelectorsAPI:!!document.querySelector,ElementExtensions:function(){var constructor=window.Element||window.HTMLElement;return!!(constructor&&
constructor.prototype)}(),SpecificElementExtensions:function(){if(typeof window.HTMLDivElement!=="undefined")return true;var div=document.createElement("div"),form=document.createElement("form"),isSupported=false;if(div["__proto__"]&&div["__proto__"]!==form["__proto__"])isSupported=true;div=form=null;return isSupported}()},ScriptFragment:"<script[^>]*>([\\S\\s]*?)<\/script>",JSONFilter:/^\/\*-secure-([\s\S]*)\*\/\s*$/,emptyFunction:function(){},K:function(x){return x}};
if(Prototype.Browser.MobileSafari)Prototype.BrowserFeatures.SpecificElementExtensions=false;
var Class=function(){var IS_DONTENUM_BUGGY=function(){for(var p in{toString:1})if(p==="toString")return false;return true}();function subclass(){}function create(){var parent=null,properties=$A(arguments);if(Object.isFunction(properties[0]))parent=properties.shift();function klass(){this.initialize.apply(this,arguments)}Object.extend(klass,Class.Methods);klass.superclass=parent;klass.subclasses=[];if(parent){subclass.prototype=parent.prototype;klass.prototype=new subclass;parent.subclasses.push(klass)}for(var i=
0,length=properties.length;i<length;i++)klass.addMethods(properties[i]);if(!klass.prototype.initialize)klass.prototype.initialize=Prototype.emptyFunction;klass.prototype.constructor=klass;return klass}function addMethods(source){var ancestor=this.superclass&&this.superclass.prototype,properties=Object.keys(source);if(IS_DONTENUM_BUGGY){if(source.toString!=Object.prototype.toString)properties.push("toString");if(source.valueOf!=Object.prototype.valueOf)properties.push("valueOf")}for(var i=0,length=
properties.length;i<length;i++){var property=properties[i],value=source[property];if(ancestor&&Object.isFunction(value)&&value.argumentNames()[0]=="$super"){var method=value;value=function(m){return function(){return ancestor[m].apply(this,arguments)}}(property).wrap(method);value.valueOf=method.valueOf.bind(method);value.toString=method.toString.bind(method)}this.prototype[property]=value}return this}return{create:create,Methods:{addMethods:addMethods}}}();
(function(){var _toString=Object.prototype.toString,NULL_TYPE="Null",UNDEFINED_TYPE="Undefined",BOOLEAN_TYPE="Boolean",NUMBER_TYPE="Number",STRING_TYPE="String",OBJECT_TYPE="Object",FUNCTION_CLASS="[object Function]",BOOLEAN_CLASS="[object Boolean]",NUMBER_CLASS="[object Number]",STRING_CLASS="[object String]",ARRAY_CLASS="[object Array]",DATE_CLASS="[object Date]",NATIVE_JSON_STRINGIFY_SUPPORT=window.JSON&&typeof JSON.stringify==="function"&&JSON.stringify(0)==="0"&&typeof JSON.stringify(Prototype.K)===
"undefined";function Type(o){switch(o){case null:return NULL_TYPE;case void 0:return UNDEFINED_TYPE}var type=typeof o;switch(type){case "boolean":return BOOLEAN_TYPE;case "number":return NUMBER_TYPE;case "string":return STRING_TYPE}return OBJECT_TYPE}function extend(destination,source){for(var property in source)destination[property]=source[property];return destination}function inspect(object){try{if(isUndefined(object))return"undefined";if(object===null)return"null";return object.inspect?object.inspect():
String(object)}catch(e){if(e instanceof RangeError)return"...";throw e;}}function toJSON(value){return Str("",{"":value},[])}function Str(key,holder,stack){var value=holder[key],type=typeof value;if(Type(value)===OBJECT_TYPE&&typeof value.toJSON==="function")value=value.toJSON(key);var _class=_toString.call(value);switch(_class){case NUMBER_CLASS:case BOOLEAN_CLASS:case STRING_CLASS:value=value.valueOf()}switch(value){case null:return"null";case true:return"true";case false:return"false"}type=typeof value;
switch(type){case "string":return value.inspect(true);case "number":return isFinite(value)?String(value):"null";case "object":for(var i=0,length=stack.length;i<length;i++)if(stack[i]===value)throw new TypeError;stack.push(value);var partial=[];if(_class===ARRAY_CLASS){for(var i=0,length=value.length;i<length;i++){var str=Str(i,value,stack);partial.push(typeof str==="undefined"?"null":str)}partial="["+partial.join(",")+"]"}else{var keys=Object.keys(value);for(var i=0,length=keys.length;i<length;i++){var key=
keys[i],str=Str(key,value,stack);if(typeof str!=="undefined")partial.push(key.inspect(true)+":"+str)}partial="{"+partial.join(",")+"}"}stack.pop();return partial}}function stringify(object){return JSON.stringify(object)}function toQueryString(object){return $H(object).toQueryString()}function toHTML(object){return object&&object.toHTML?object.toHTML():String.interpret(object)}function keys(object){if(Type(object)!==OBJECT_TYPE)throw new TypeError;var results=[];for(var property in object)if(object.hasOwnProperty(property))results.push(property);
return results}function values(object){var results=[];for(var property in object)results.push(object[property]);return results}function clone(object){return extend({},object)}function isElement(object){return!!(object&&object.nodeType==1)}function isArray(object){return _toString.call(object)===ARRAY_CLASS}var hasNativeIsArray=typeof Array.isArray=="function"&&Array.isArray([])&&!Array.isArray({});if(hasNativeIsArray)isArray=Array.isArray;function isHash(object){return object instanceof Hash}function isFunction(object){return _toString.call(object)===
FUNCTION_CLASS}function isString(object){return _toString.call(object)===STRING_CLASS}function isNumber(object){return _toString.call(object)===NUMBER_CLASS}function isDate(object){return _toString.call(object)===DATE_CLASS}function isUndefined(object){return typeof object==="undefined"}extend(Object,{extend:extend,inspect:inspect,toJSON:NATIVE_JSON_STRINGIFY_SUPPORT?stringify:toJSON,toQueryString:toQueryString,toHTML:toHTML,keys:Object.keys||keys,values:values,clone:clone,isElement:isElement,isArray:isArray,
isHash:isHash,isFunction:isFunction,isString:isString,isNumber:isNumber,isDate:isDate,isUndefined:isUndefined})})();
Object.extend(Function.prototype,function(){var slice=Array.prototype.slice;function update(array,args){var arrayLength=array.length,length=args.length;while(length--)array[arrayLength+length]=args[length];return array}function merge(array,args){array=slice.call(array,0);return update(array,args)}function argumentNames(){var names=this.toString().match(/^[\s\(]*function[^(]*\(([^)]*)\)/)[1].replace(/\/\/.*?[\r\n]|\/\*(?:.|[\r\n])*?\*\//g,"").replace(/\s+/g,"").split(",");return names.length==1&&!names[0]?
[]:names}function bind(context){if(arguments.length<2&&Object.isUndefined(arguments[0]))return this;var __method=this,args=slice.call(arguments,1);return function(){var a=merge(args,arguments);return __method.apply(context,a)}}function bindAsEventListener(context){var __method=this,args=slice.call(arguments,1);return function(event){var a=update([event||window.event],args);return __method.apply(context,a)}}function curry(){if(!arguments.length)return this;var __method=this,args=slice.call(arguments,
0);return function(){var a=merge(args,arguments);return __method.apply(this,a)}}function delay(timeout){var __method=this,args=slice.call(arguments,1);timeout=timeout*1E3;return window.setTimeout(function(){return __method.apply(__method,args)},timeout)}function defer(){var args=update([0.01],arguments);return this.delay.apply(this,args)}function wrap(wrapper){var __method=this;return function(){var a=update([__method.bind(this)],arguments);return wrapper.apply(this,a)}}function methodize(){if(this._methodized)return this._methodized;
var __method=this;return this._methodized=function(){var a=update([this],arguments);return __method.apply(null,a)}}return{argumentNames:argumentNames,bind:bind,bindAsEventListener:bindAsEventListener,curry:curry,delay:delay,defer:defer,wrap:wrap,methodize:methodize}}());
(function(proto){function toISOString(){return this.getUTCFullYear()+"-"+(this.getUTCMonth()+1).toPaddedString(2)+"-"+this.getUTCDate().toPaddedString(2)+"T"+this.getUTCHours().toPaddedString(2)+":"+this.getUTCMinutes().toPaddedString(2)+":"+this.getUTCSeconds().toPaddedString(2)+"Z"}function toJSON(){return this.toISOString()}if(!proto.toISOString)proto.toISOString=toISOString;if(!proto.toJSON)proto.toJSON=toJSON})(Date.prototype);RegExp.prototype.match=RegExp.prototype.test;
RegExp.escape=function(str){return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g,"\\$1")};
var PeriodicalExecuter=Class.create({initialize:function(callback,frequency){this.callback=callback;this.frequency=frequency;this.currentlyExecuting=false;this.registerCallback()},registerCallback:function(){this.timer=setInterval(this.onTimerEvent.bind(this),this.frequency*1E3)},execute:function(){this.callback(this)},stop:function(){if(!this.timer)return;clearInterval(this.timer);this.timer=null},onTimerEvent:function(){if(!this.currentlyExecuting)try{this.currentlyExecuting=true;this.execute();
this.currentlyExecuting=false}catch(e){this.currentlyExecuting=false;throw e;}}});Object.extend(String,{interpret:function(value){return value==null?"":String(value)},specialChar:{"\u0008":"\\b","\t":"\\t","\n":"\\n","\u000c":"\\f","\r":"\\r","\\":"\\\\"}});
Object.extend(String.prototype,function(){var NATIVE_JSON_PARSE_SUPPORT=window.JSON&&typeof JSON.parse==="function"&&JSON.parse('{"test": true}').test;function prepareReplacement(replacement){if(Object.isFunction(replacement))return replacement;var template=new Template(replacement);return function(match){return template.evaluate(match)}}function gsub(pattern,replacement){var result="",source=this,match;replacement=prepareReplacement(replacement);if(Object.isString(pattern))pattern=RegExp.escape(pattern);
if(!(pattern.length||pattern.source)){replacement=replacement("");return replacement+source.split("").join(replacement)+replacement}while(source.length>0)if(match=source.match(pattern)){result+=source.slice(0,match.index);result+=String.interpret(replacement(match));source=source.slice(match.index+match[0].length)}else result+=source,source="";return result}function sub(pattern,replacement,count){replacement=prepareReplacement(replacement);count=Object.isUndefined(count)?1:count;return this.gsub(pattern,
function(match){if(--count<0)return match[0];return replacement(match)})}function scan(pattern,iterator){this.gsub(pattern,iterator);return String(this)}function truncate(length,truncation){length=length||30;truncation=Object.isUndefined(truncation)?"...":truncation;return this.length>length?this.slice(0,length-truncation.length)+truncation:String(this)}function strip(){return this.replace(/^\s+/,"").replace(/\s+$/,"")}function stripTags(){return this.replace(/<\w+(\s+("[^"]*"|'[^']*'|[^>])+)?>|<\/\w+>/gi,
"")}function stripScripts(){return this.replace(new RegExp(Prototype.ScriptFragment,"img"),"")}function extractScripts(){var matchAll=new RegExp(Prototype.ScriptFragment,"img"),matchOne=new RegExp(Prototype.ScriptFragment,"im");return(this.match(matchAll)||[]).map(function(scriptTag){return(scriptTag.match(matchOne)||["",""])[1]})}function evalScripts(){return this.extractScripts().map(function(script){return eval(script)})}function escapeHTML(){return this.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,
"&gt;")}function unescapeHTML(){return this.stripTags().replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&")}function toQueryParams(separator){var match=this.strip().match(/([^?#]*)(#.*)?$/);if(!match)return{};return match[1].split(separator||"&").inject({},function(hash,pair){if((pair=pair.split("="))[0]){var key=decodeURIComponent(pair.shift()),value=pair.length>1?pair.join("="):pair[0];if(value!=undefined)value=decodeURIComponent(value);if(key in hash){if(!Object.isArray(hash[key]))hash[key]=
[hash[key]];hash[key].push(value)}else hash[key]=value}return hash})}function toArray(){return this.split("")}function succ(){return this.slice(0,this.length-1)+String.fromCharCode(this.charCodeAt(this.length-1)+1)}function times(count){return count<1?"":(new Array(count+1)).join(this)}function camelize(){return this.replace(/-+(.)?/g,function(match,chr){return chr?chr.toUpperCase():""})}function capitalize(){return this.charAt(0).toUpperCase()+this.substring(1).toLowerCase()}function underscore(){return this.replace(/::/g,
"/").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").replace(/([a-z\d])([A-Z])/g,"$1_$2").replace(/-/g,"_").toLowerCase()}function dasherize(){return this.replace(/_/g,"-")}function inspect(useDoubleQuotes){var escapedString=this.replace(/[\x00-\x1f\\]/g,function(character){if(character in String.specialChar)return String.specialChar[character];return"\\u00"+character.charCodeAt().toPaddedString(2,16)});if(useDoubleQuotes)return'"'+escapedString.replace(/"/g,'\\"')+'"';return"'"+escapedString.replace(/'/g,
"\\'")+"'"}function unfilterJSON(filter){return this.replace(filter||Prototype.JSONFilter,"$1")}function isJSON(){var str=this;if(str.blank())return false;str=str.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,"@");str=str.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,"]");str=str.replace(/(?:^|:|,)(?:\s*\[)+/g,"");return/^[\],:{}\s]*$/.test(str)}function evalJSON(sanitize){var json=this.unfilterJSON(),cx=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
if(cx.test(json))json=json.replace(cx,function(a){return"\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4)});try{if(!sanitize||json.isJSON())return eval("("+json+")")}catch(e){}throw new SyntaxError("Badly formed JSON string: "+this.inspect());}function parseJSON(){var json=this.unfilterJSON();return JSON.parse(json)}function include(pattern){return this.indexOf(pattern)>-1}function startsWith(pattern){return this.lastIndexOf(pattern,0)===0}function endsWith(pattern){var d=this.length-pattern.length;
return d>=0&&this.indexOf(pattern,d)===d}function empty(){return this==""}function blank(){return/^\s*$/.test(this)}function interpolate(object,pattern){return(new Template(this,pattern)).evaluate(object)}return{gsub:gsub,sub:sub,scan:scan,truncate:truncate,strip:String.prototype.trim||strip,stripTags:stripTags,stripScripts:stripScripts,extractScripts:extractScripts,evalScripts:evalScripts,escapeHTML:escapeHTML,unescapeHTML:unescapeHTML,toQueryParams:toQueryParams,parseQuery:toQueryParams,toArray:toArray,
succ:succ,times:times,camelize:camelize,capitalize:capitalize,underscore:underscore,dasherize:dasherize,inspect:inspect,unfilterJSON:unfilterJSON,isJSON:isJSON,evalJSON:NATIVE_JSON_PARSE_SUPPORT?parseJSON:evalJSON,include:include,startsWith:startsWith,endsWith:endsWith,empty:empty,blank:blank,interpolate:interpolate}}());
var Template=Class.create({initialize:function(template,pattern){this.template=template.toString();this.pattern=pattern||Template.Pattern},evaluate:function(object){if(object&&Object.isFunction(object.toTemplateReplacements))object=object.toTemplateReplacements();return this.template.gsub(this.pattern,function(match){if(object==null)return match[1]+"";var before=match[1]||"";if(before=="\\")return match[2];var ctx=object,expr=match[3],pattern=/^([^.[]+|\[((?:.*?[^\\])?)\])(\.|\[|$)/;match=pattern.exec(expr);
if(match==null)return before;while(match!=null){var comp=match[1].startsWith("[")?match[2].replace(/\\\\]/g,"]"):match[1];ctx=ctx[comp];if(null==ctx||""==match[3])break;expr=expr.substring("["==match[3]?match[1].length:match[0].length);match=pattern.exec(expr)}return before+String.interpret(ctx)})}});Template.Pattern=/(^|.|\r|\n)(#\{(.*?)\})/;var $break={};
var Enumerable=function(){function each(iterator,context){var index=0;try{this._each(function(value){iterator.call(context,value,index++)})}catch(e){if(e!=$break)throw e;}return this}function eachSlice(number,iterator,context){var index=-number,slices=[],array=this.toArray();if(number<1)return array;while((index+=number)<array.length)slices.push(array.slice(index,index+number));return slices.collect(iterator,context)}function all(iterator,context){iterator=iterator||Prototype.K;var result=true;this.each(function(value,
index){result=result&&!!iterator.call(context,value,index);if(!result)throw $break;});return result}function any(iterator,context){iterator=iterator||Prototype.K;var result=false;this.each(function(value,index){if(result=!!iterator.call(context,value,index))throw $break;});return result}function collect(iterator,context){iterator=iterator||Prototype.K;var results=[];this.each(function(value,index){results.push(iterator.call(context,value,index))});return results}function detect(iterator,context){var result;
this.each(function(value,index){if(iterator.call(context,value,index)){result=value;throw $break;}});return result}function findAll(iterator,context){var results=[];this.each(function(value,index){if(iterator.call(context,value,index))results.push(value)});return results}function grep(filter,iterator,context){iterator=iterator||Prototype.K;var results=[];if(Object.isString(filter))filter=new RegExp(RegExp.escape(filter));this.each(function(value,index){if(filter.match(value))results.push(iterator.call(context,
value,index))});return results}function include(object){if(Object.isFunction(this.indexOf))if(this.indexOf(object)!=-1)return true;var found=false;this.each(function(value){if(value==object){found=true;throw $break;}});return found}function inGroupsOf(number,fillWith){fillWith=Object.isUndefined(fillWith)?null:fillWith;return this.eachSlice(number,function(slice){while(slice.length<number)slice.push(fillWith);return slice})}function inject(memo,iterator,context){this.each(function(value,index){memo=
iterator.call(context,memo,value,index)});return memo}function invoke(method){var args=$A(arguments).slice(1);return this.map(function(value){return value[method].apply(value,args)})}function max(iterator,context){iterator=iterator||Prototype.K;var result;this.each(function(value,index){value=iterator.call(context,value,index);if(result==null||value>=result)result=value});return result}function min(iterator,context){iterator=iterator||Prototype.K;var result;this.each(function(value,index){value=iterator.call(context,
value,index);if(result==null||value<result)result=value});return result}function partition(iterator,context){iterator=iterator||Prototype.K;var trues=[],falses=[];this.each(function(value,index){(iterator.call(context,value,index)?trues:falses).push(value)});return[trues,falses]}function pluck(property){var results=[];this.each(function(value){results.push(value[property])});return results}function reject(iterator,context){var results=[];this.each(function(value,index){if(!iterator.call(context,value,
index))results.push(value)});return results}function sortBy(iterator,context){return this.map(function(value,index){return{value:value,criteria:iterator.call(context,value,index)}}).sort(function(left,right){var a=left.criteria,b=right.criteria;return a<b?-1:a>b?1:0}).pluck("value")}function toArray(){return this.map()}function zip(){var iterator=Prototype.K,args=$A(arguments);if(Object.isFunction(args.last()))iterator=args.pop();var collections=[this].concat(args).map($A);return this.map(function(value,
index){return iterator(collections.pluck(index))})}function size(){return this.toArray().length}function inspect(){return"#<Enumerable:"+this.toArray().inspect()+">"}return{each:each,eachSlice:eachSlice,all:all,every:all,any:any,some:any,collect:collect,map:collect,detect:detect,findAll:findAll,select:findAll,filter:findAll,grep:grep,include:include,member:include,inGroupsOf:inGroupsOf,inject:inject,invoke:invoke,max:max,min:min,partition:partition,pluck:pluck,reject:reject,sortBy:sortBy,toArray:toArray,
entries:toArray,zip:zip,size:size,inspect:inspect,find:detect}}();function $A(iterable){if(!iterable)return[];if("toArray"in Object(iterable))return iterable.toArray();var length=iterable.length||0,results=new Array(length);while(length--)results[length]=iterable[length];return results}function $w(string){if(!Object.isString(string))return[];string=string.strip();return string?string.split(/\s+/):[]}Array.from=$A;
(function(){var arrayProto=Array.prototype,slice=arrayProto.slice,_each=arrayProto.forEach;function each(iterator,context){for(var i=0,length=this.length>>>0;i<length;i++)if(i in this)iterator.call(context,this[i],i,this)}if(!_each)_each=each;function clear(){this.length=0;return this}function first(){return this[0]}function last(){return this[this.length-1]}function compact(){return this.select(function(value){return value!=null})}function flatten(){return this.inject([],function(array,value){if(Object.isArray(value))return array.concat(value.flatten());
array.push(value);return array})}function without(){var values=slice.call(arguments,0);return this.select(function(value){return!values.include(value)})}function reverse(inline){return(inline===false?this.toArray():this)._reverse()}function uniq(sorted){return this.inject([],function(array,value,index){if(0==index||(sorted?array.last()!=value:!array.include(value)))array.push(value);return array})}function intersect(array){return this.uniq().findAll(function(item){return array.detect(function(value){return item===
value})})}function clone(){return slice.call(this,0)}function size(){return this.length}function inspect(){return"["+this.map(Object.inspect).join(", ")+"]"}function indexOf(item,i){i||(i=0);var length=this.length;if(i<0)i=length+i;for(;i<length;i++)if(this[i]===item)return i;return-1}function lastIndexOf(item,i){i=isNaN(i)?this.length:(i<0?this.length+i:i)+1;var n=this.slice(0,i).reverse().indexOf(item);return n<0?n:i-n-1}function concat(){var array=slice.call(this,0),item;for(var i=0,length=arguments.length;i<
length;i++){item=arguments[i];if(Object.isArray(item)&&!("callee"in item))for(var j=0,arrayLength=item.length;j<arrayLength;j++)array.push(item[j]);else array.push(item)}return array}Object.extend(arrayProto,Enumerable);if(!arrayProto._reverse)arrayProto._reverse=arrayProto.reverse;Object.extend(arrayProto,{_each:_each,clear:clear,first:first,last:last,compact:compact,flatten:flatten,without:without,reverse:reverse,uniq:uniq,intersect:intersect,clone:clone,toArray:clone,size:size,inspect:inspect});
var CONCAT_ARGUMENTS_BUGGY=function(){return[].concat(arguments)[0][0]!==1}(1,2);if(CONCAT_ARGUMENTS_BUGGY)arrayProto.concat=concat;if(!arrayProto.indexOf)arrayProto.indexOf=indexOf;if(!arrayProto.lastIndexOf)arrayProto.lastIndexOf=lastIndexOf})();function $H(object){return new Hash(object)}
var Hash=Class.create(Enumerable,function(){function initialize(object){this._object=Object.isHash(object)?object.toObject():Object.clone(object)}function _each(iterator){for(var key in this._object){var value=this._object[key],pair=[key,value];pair.key=key;pair.value=value;iterator(pair)}}function set(key,value){return this._object[key]=value}function get(key){if(this._object[key]!==Object.prototype[key])return this._object[key]}function unset(key){var value=this._object[key];delete this._object[key];
return value}function toObject(){return Object.clone(this._object)}function keys(){return this.pluck("key")}function values(){return this.pluck("value")}function index(value){var match=this.detect(function(pair){return pair.value===value});return match&&match.key}function merge(object){return this.clone().update(object)}function update(object){return(new Hash(object)).inject(this,function(result,pair){result.set(pair.key,pair.value);return result})}function toQueryPair(key,value){if(Object.isUndefined(value))return key;
return key+"="+encodeURIComponent(String.interpret(value))}function toQueryString(){return this.inject([],function(results,pair){var key=encodeURIComponent(pair.key),values=pair.value;if(values&&typeof values=="object"){if(Object.isArray(values)){var queryValues=[];for(var i=0,len=values.length,value;i<len;i++){value=values[i];queryValues.push(toQueryPair(key,value))}return results.concat(queryValues)}}else results.push(toQueryPair(key,values));return results}).join("&")}function inspect(){return"#<Hash:{"+
this.map(function(pair){return pair.map(Object.inspect).join(": ")}).join(", ")+"}>"}function clone(){return new Hash(this)}return{initialize:initialize,_each:_each,set:set,get:get,unset:unset,toObject:toObject,toTemplateReplacements:toObject,keys:keys,values:values,index:index,merge:merge,update:update,toQueryString:toQueryString,inspect:inspect,toJSON:toObject,clone:clone}}());Hash.from=$H;
Object.extend(Number.prototype,function(){function toColorPart(){return this.toPaddedString(2,16)}function succ(){return this+1}function times(iterator,context){$R(0,this,true).each(iterator,context);return this}function toPaddedString(length,radix){var string=this.toString(radix||10);return"0".times(length-string.length)+string}function abs(){return Math.abs(this)}function round(){return Math.round(this)}function ceil(){return Math.ceil(this)}function floor(){return Math.floor(this)}return{toColorPart:toColorPart,
succ:succ,times:times,toPaddedString:toPaddedString,abs:abs,round:round,ceil:ceil,floor:floor}}());function $R(start,end,exclusive){return new ObjectRange(start,end,exclusive)}
var ObjectRange=Class.create(Enumerable,function(){function initialize(start,end,exclusive){this.start=start;this.end=end;this.exclusive=exclusive}function _each(iterator){var value=this.start;while(this.include(value)){iterator(value);value=value.succ()}}function include(value){if(value<this.start)return false;if(this.exclusive)return value<this.end;return value<=this.end}return{initialize:initialize,_each:_each,include:include}}());var Abstract={};
var Try={these:function(){var returnValue;for(var i=0,length=arguments.length;i<length;i++){var lambda=arguments[i];try{returnValue=lambda();break}catch(e){}}return returnValue}};var Ajax={getTransport:function(){return Try.these(function(){return new XMLHttpRequest},function(){return new ActiveXObject("Msxml2.XMLHTTP")},function(){return new ActiveXObject("Microsoft.XMLHTTP")})||false},activeRequestCount:0};
Ajax.Responders={responders:[],_each:function(iterator){this.responders._each(iterator)},register:function(responder){if(!this.include(responder))this.responders.push(responder)},unregister:function(responder){this.responders=this.responders.without(responder)},dispatch:function(callback,request,transport,json){this.each(function(responder){if(Object.isFunction(responder[callback]))try{responder[callback].apply(responder,[request,transport,json])}catch(e){}})}};Object.extend(Ajax.Responders,Enumerable);
Ajax.Responders.register({onCreate:function(){Ajax.activeRequestCount++},onComplete:function(){Ajax.activeRequestCount--}});Ajax.Base=Class.create({initialize:function(options){this.options={method:"post",asynchronous:true,contentType:"application/x-www-form-urlencoded",encoding:"UTF-8",parameters:"",evalJSON:true,evalJS:true};Object.extend(this.options,options||{});this.options.method=this.options.method.toLowerCase();if(Object.isHash(this.options.parameters))this.options.parameters=this.options.parameters.toObject()}});
Ajax.Request=Class.create(Ajax.Base,{_complete:false,initialize:function($super,url,options){$super(options);this.transport=Ajax.getTransport();this.request(url)},request:function(url){this.url=url;this.method=this.options.method;var params=Object.isString(this.options.parameters)?this.options.parameters:Object.toQueryString(this.options.parameters);if(!["get","post"].include(this.method)){params+=(params?"&":"")+"_method="+this.method;this.method="post"}if(params&&this.method==="get")this.url+=(this.url.include("?")?
"&":"?")+params;this.parameters=params.toQueryParams();try{var response=new Ajax.Response(this);if(this.options.onCreate)this.options.onCreate(response);Ajax.Responders.dispatch("onCreate",this,response);this.transport.open(this.method.toUpperCase(),this.url,this.options.asynchronous);if(this.options.asynchronous)this.respondToReadyState.bind(this).defer(1);this.transport.onreadystatechange=this.onStateChange.bind(this);this.setRequestHeaders();this.body=this.method=="post"?this.options.postBody||
params:null;this.transport.send(this.body);if(!this.options.asynchronous&&this.transport.overrideMimeType)this.onStateChange()}catch(e){this.dispatchException(e)}},onStateChange:function(){var readyState=this.transport.readyState;if(readyState>1&&!(readyState==4&&this._complete))this.respondToReadyState(this.transport.readyState)},setRequestHeaders:function(){var headers={"X-Requested-With":"XMLHttpRequest","X-Prototype-Version":Prototype.Version,"Accept":"text/javascript, text/html, application/xml, text/xml, */*"};
if(this.method=="post"){headers["Content-type"]=this.options.contentType+(this.options.encoding?"; charset="+this.options.encoding:"");if(this.transport.overrideMimeType&&(navigator.userAgent.match(/Gecko\/(\d{4})/)||[0,2005])[1]<2005)headers["Connection"]="close"}if(typeof this.options.requestHeaders=="object"){var extras=this.options.requestHeaders;if(Object.isFunction(extras.push))for(var i=0,length=extras.length;i<length;i+=2)headers[extras[i]]=extras[i+1];else $H(extras).each(function(pair){headers[pair.key]=
pair.value})}for(var name in headers)this.transport.setRequestHeader(name,headers[name])},success:function(){var status=this.getStatus();return!status||status>=200&&status<300||status==304},getStatus:function(){try{if(this.transport.status===1223)return 204;return this.transport.status||0}catch(e){return 0}},respondToReadyState:function(readyState){var state=Ajax.Request.Events[readyState],response=new Ajax.Response(this);if(state=="Complete"){try{this._complete=true;(this.options["on"+response.status]||
this.options["on"+(this.success()?"Success":"Failure")]||Prototype.emptyFunction)(response,response.headerJSON)}catch(e){this.dispatchException(e)}var contentType=response.getHeader("Content-type");if(this.options.evalJS=="force"||this.options.evalJS&&this.isSameOrigin()&&contentType&&contentType.match(/^\s*(text|application)\/(x-)?(java|ecma)script(;.*)?\s*$/i))this.evalResponse()}try{(this.options["on"+state]||Prototype.emptyFunction)(response,response.headerJSON);Ajax.Responders.dispatch("on"+
state,this,response,response.headerJSON)}catch(e){this.dispatchException(e)}if(state=="Complete")this.transport.onreadystatechange=Prototype.emptyFunction},isSameOrigin:function(){var m=this.url.match(/^\s*https?:\/\/[^\/]*/);return!m||m[0]=="#{protocol}//#{domain}#{port}".interpolate({protocol:location.protocol,domain:document.domain,port:location.port?":"+location.port:""})},getHeader:function(name){try{return this.transport.getResponseHeader(name)||null}catch(e){return null}},evalResponse:function(){try{return eval((this.transport.responseText||
"").unfilterJSON())}catch(e){this.dispatchException(e)}},dispatchException:function(exception){(this.options.onException||Prototype.emptyFunction)(this,exception);Ajax.Responders.dispatch("onException",this,exception)}});Ajax.Request.Events=["Uninitialized","Loading","Loaded","Interactive","Complete"];
Ajax.Response=Class.create({initialize:function(request){this.request=request;var transport=this.transport=request.transport,readyState=this.readyState=transport.readyState;if(readyState>2&&!Prototype.Browser.IE||readyState==4){this.status=this.getStatus();this.statusText=this.getStatusText();this.responseText=String.interpret(transport.responseText);this.headerJSON=this._getHeaderJSON()}if(readyState==4){var xml=transport.responseXML;this.responseXML=Object.isUndefined(xml)?null:xml;this.responseJSON=
this._getResponseJSON()}},status:0,statusText:"",getStatus:Ajax.Request.prototype.getStatus,getStatusText:function(){try{return this.transport.statusText||""}catch(e){return""}},getHeader:Ajax.Request.prototype.getHeader,getAllHeaders:function(){try{return this.getAllResponseHeaders()}catch(e){return null}},getResponseHeader:function(name){return this.transport.getResponseHeader(name)},getAllResponseHeaders:function(){return this.transport.getAllResponseHeaders()},_getHeaderJSON:function(){var json=
this.getHeader("X-JSON");if(!json)return null;json=decodeURIComponent(escape(json));try{return json.evalJSON(this.request.options.sanitizeJSON||!this.request.isSameOrigin())}catch(e){this.request.dispatchException(e)}},_getResponseJSON:function(){var options=this.request.options;if(!options.evalJSON||options.evalJSON!="force"&&!(this.getHeader("Content-type")||"").include("application/json")||this.responseText.blank())return null;try{return this.responseText.evalJSON(options.sanitizeJSON||!this.request.isSameOrigin())}catch(e){this.request.dispatchException(e)}}});
Ajax.Updater=Class.create(Ajax.Request,{initialize:function($super,container,url,options){this.container={success:container.success||container,failure:container.failure||(container.success?null:container)};options=Object.clone(options);var onComplete=options.onComplete;options.onComplete=function(response,json){this.updateContent(response.responseText);if(Object.isFunction(onComplete))onComplete(response,json)}.bind(this);$super(url,options)},updateContent:function(responseText){var receiver=this.container[this.success()?
"success":"failure"],options=this.options;if(!options.evalScripts)responseText=responseText.stripScripts();if(receiver=$(receiver))if(options.insertion)if(Object.isString(options.insertion)){var insertion={};insertion[options.insertion]=responseText;receiver.insert(insertion)}else options.insertion(receiver,responseText);else receiver.update(responseText)}});
Ajax.PeriodicalUpdater=Class.create(Ajax.Base,{initialize:function($super,container,url,options){$super(options);this.onComplete=this.options.onComplete;this.frequency=this.options.frequency||2;this.decay=this.options.decay||1;this.updater={};this.container=container;this.url=url;this.start()},start:function(){this.options.onComplete=this.updateComplete.bind(this);this.onTimerEvent()},stop:function(){this.updater.options.onComplete=undefined;clearTimeout(this.timer);(this.onComplete||Prototype.emptyFunction).apply(this,
arguments)},updateComplete:function(response){if(this.options.decay){this.decay=response.responseText==this.lastText?this.decay*this.options.decay:1;this.lastText=response.responseText}this.timer=this.onTimerEvent.bind(this).delay(this.decay*this.frequency)},onTimerEvent:function(){this.updater=new Ajax.Updater(this.container,this.url,this.options)}});
function $(element){if(arguments.length>1){for(var i=0,elements=[],length=arguments.length;i<length;i++)elements.push($(arguments[i]));return elements}if(Object.isString(element))element=document.getElementById(element);return Element.extend(element)}
if(Prototype.BrowserFeatures.XPath)document._getElementsByXPath=function(expression,parentElement){var results=[];var query=document.evaluate(expression,$(parentElement)||document,null,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,null);for(var i=0,length=query.snapshotLength;i<length;i++)results.push(Element.extend(query.snapshotItem(i)));return results};if(!Node)var Node={};
if(!Node.ELEMENT_NODE)Object.extend(Node,{ELEMENT_NODE:1,ATTRIBUTE_NODE:2,TEXT_NODE:3,CDATA_SECTION_NODE:4,ENTITY_REFERENCE_NODE:5,ENTITY_NODE:6,PROCESSING_INSTRUCTION_NODE:7,COMMENT_NODE:8,DOCUMENT_NODE:9,DOCUMENT_TYPE_NODE:10,DOCUMENT_FRAGMENT_NODE:11,NOTATION_NODE:12});
(function(global){function shouldUseCache(tagName,attributes){if(tagName==="select")return false;if("type"in attributes)return false;return true}var HAS_EXTENDED_CREATE_ELEMENT_SYNTAX=function(){try{var el=document.createElement('<input name="x">');return el.tagName.toLowerCase()==="input"&&el.name==="x"}catch(err){return false}}();var element=global.Element;global.Element=function(tagName,attributes){attributes=attributes||{};tagName=tagName.toLowerCase();var cache=Element.cache;if(HAS_EXTENDED_CREATE_ELEMENT_SYNTAX&&
attributes.name){tagName="<"+tagName+' name="'+attributes.name+'">';delete attributes.name;return Element.writeAttribute(document.createElement(tagName),attributes)}if(!cache[tagName])cache[tagName]=Element.extend(document.createElement(tagName));var node=shouldUseCache(tagName,attributes)?cache[tagName].cloneNode(false):document.createElement(tagName);return Element.writeAttribute(node,attributes)};Object.extend(global.Element,element||{});if(element)global.Element.prototype=element.prototype})(this);
Element.idCounter=1;Element.cache={};Element._purgeElement=function(element){var uid=element._prototypeUID;if(uid){Element.stopObserving(element);element._prototypeUID=void 0;delete Element.Storage[uid]}};
Element.Methods={visible:function(element){return $(element).style.display!="none"},toggle:function(element){element=$(element);Element[Element.visible(element)?"hide":"show"](element);return element},hide:function(element){element=$(element);element.style.display="none";return element},show:function(element){element=$(element);element.style.display="";return element},remove:function(element){element=$(element);element.parentNode.removeChild(element);return element},update:function(){var SELECT_ELEMENT_INNERHTML_BUGGY=
function(){var el=document.createElement("select"),isBuggy=true;el.innerHTML='<option value="test">test</option>';if(el.options&&el.options[0])isBuggy=el.options[0].nodeName.toUpperCase()!=="OPTION";el=null;return isBuggy}();var TABLE_ELEMENT_INNERHTML_BUGGY=function(){try{var el=document.createElement("table");if(el&&el.tBodies){el.innerHTML="<tbody><tr><td>test</td></tr></tbody>";var isBuggy=typeof el.tBodies[0]=="undefined";el=null;return isBuggy}}catch(e){return true}}();var LINK_ELEMENT_INNERHTML_BUGGY=
function(){try{var el=document.createElement("div");el.innerHTML="<link>";var isBuggy=el.childNodes.length===0;el=null;return isBuggy}catch(e){return true}}();var ANY_INNERHTML_BUGGY=SELECT_ELEMENT_INNERHTML_BUGGY||TABLE_ELEMENT_INNERHTML_BUGGY||LINK_ELEMENT_INNERHTML_BUGGY;var SCRIPT_ELEMENT_REJECTS_TEXTNODE_APPENDING=function(){var s=document.createElement("script"),isBuggy=false;try{s.appendChild(document.createTextNode(""));isBuggy=!s.firstChild||s.firstChild&&s.firstChild.nodeType!==3}catch(e){isBuggy=
true}s=null;return isBuggy}();function update(element,content){element=$(element);var purgeElement=Element._purgeElement;var descendants=element.getElementsByTagName("*"),i=descendants.length;while(i--)purgeElement(descendants[i]);if(content&&content.toElement)content=content.toElement();if(Object.isElement(content))return element.update().insert(content);content=Object.toHTML(content);var tagName=element.tagName.toUpperCase();if(tagName==="SCRIPT"&&SCRIPT_ELEMENT_REJECTS_TEXTNODE_APPENDING){element.text=
content;return element}if(ANY_INNERHTML_BUGGY)if(tagName in Element._insertionTranslations.tags){while(element.firstChild)element.removeChild(element.firstChild);Element._getContentFromAnonymousElement(tagName,content.stripScripts()).each(function(node){element.appendChild(node)})}else if(LINK_ELEMENT_INNERHTML_BUGGY&&Object.isString(content)&&content.indexOf("<link")>-1){while(element.firstChild)element.removeChild(element.firstChild);var nodes=Element._getContentFromAnonymousElement(tagName,content.stripScripts(),
true);nodes.each(function(node){element.appendChild(node)})}else element.innerHTML=content.stripScripts();else element.innerHTML=content.stripScripts();content.evalScripts.bind(content).defer();return element}return update}(),replace:function(element,content){element=$(element);if(content&&content.toElement)content=content.toElement();else if(!Object.isElement(content)){content=Object.toHTML(content);var range=element.ownerDocument.createRange();range.selectNode(element);content.evalScripts.bind(content).defer();
content=range.createContextualFragment(content.stripScripts())}element.parentNode.replaceChild(content,element);return element},insert:function(element,insertions){element=$(element);if(Object.isString(insertions)||Object.isNumber(insertions)||Object.isElement(insertions)||insertions&&(insertions.toElement||insertions.toHTML))insertions={bottom:insertions};var content,insert,tagName,childNodes;for(var position in insertions){content=insertions[position];position=position.toLowerCase();insert=Element._insertionTranslations[position];
if(content&&content.toElement)content=content.toElement();if(Object.isElement(content)){insert(element,content);continue}content=Object.toHTML(content);tagName=(position=="before"||position=="after"?element.parentNode:element).tagName.toUpperCase();childNodes=Element._getContentFromAnonymousElement(tagName,content.stripScripts());if(position=="top"||position=="after")childNodes.reverse();childNodes.each(insert.curry(element));content.evalScripts.bind(content).defer()}return element},wrap:function(element,
wrapper,attributes){element=$(element);if(Object.isElement(wrapper))$(wrapper).writeAttribute(attributes||{});else if(Object.isString(wrapper))wrapper=new Element(wrapper,attributes);else wrapper=new Element("div",wrapper);if(element.parentNode)element.parentNode.replaceChild(wrapper,element);wrapper.appendChild(element);return wrapper},inspect:function(element){element=$(element);var result="<"+element.tagName.toLowerCase();$H({"id":"id","className":"class"}).each(function(pair){var property=pair.first(),
attribute=pair.last(),value=(element[property]||"").toString();if(value)result+=" "+attribute+"="+value.inspect(true)});return result+">"},recursivelyCollect:function(element,property,maximumLength){element=$(element);maximumLength=maximumLength||-1;var elements=[];while(element=element[property]){if(element.nodeType==1)elements.push(Element.extend(element));if(elements.length==maximumLength)break}return elements},ancestors:function(element){return Element.recursivelyCollect(element,"parentNode")},
descendants:function(element){return Element.select(element,"*")},firstDescendant:function(element){element=$(element).firstChild;while(element&&element.nodeType!=1)element=element.nextSibling;return $(element)},immediateDescendants:function(element){var results=[],child=$(element).firstChild;while(child){if(child.nodeType===1)results.push(Element.extend(child));child=child.nextSibling}return results},previousSiblings:function(element,maximumLength){return Element.recursivelyCollect(element,"previousSibling")},
nextSiblings:function(element){return Element.recursivelyCollect(element,"nextSibling")},siblings:function(element){element=$(element);return Element.previousSiblings(element).reverse().concat(Element.nextSiblings(element))},match:function(element,selector){element=$(element);if(Object.isString(selector))return Prototype.Selector.match(element,selector);return selector.match(element)},up:function(element,expression,index){element=$(element);if(arguments.length==1)return $(element.parentNode);var ancestors=
Element.ancestors(element);return Object.isNumber(expression)?ancestors[expression]:Prototype.Selector.find(ancestors,expression,index)},down:function(element,expression,index){element=$(element);if(arguments.length==1)return Element.firstDescendant(element);return Object.isNumber(expression)?Element.descendants(element)[expression]:Element.select(element,expression)[index||0]},previous:function(element,expression,index){element=$(element);if(Object.isNumber(expression))index=expression,expression=
false;if(!Object.isNumber(index))index=0;if(expression)return Prototype.Selector.find(element.previousSiblings(),expression,index);else return element.recursivelyCollect("previousSibling",index+1)[index]},next:function(element,expression,index){element=$(element);if(Object.isNumber(expression))index=expression,expression=false;if(!Object.isNumber(index))index=0;if(expression)return Prototype.Selector.find(element.nextSiblings(),expression,index);else{var maximumLength=Object.isNumber(index)?index+
1:1;return element.recursivelyCollect("nextSibling",index+1)[index]}},select:function(element){element=$(element);var expressions=Array.prototype.slice.call(arguments,1).join(", ");return Prototype.Selector.select(expressions,element)},adjacent:function(element){element=$(element);var expressions=Array.prototype.slice.call(arguments,1).join(", ");return Prototype.Selector.select(expressions,element.parentNode).without(element)},identify:function(element){element=$(element);var id=Element.readAttribute(element,
"id");if(id)return id;do id="anonymous_element_"+Element.idCounter++;while($(id));Element.writeAttribute(element,"id",id);return id},readAttribute:function(element,name){element=$(element);if(Prototype.Browser.IE){var t=Element._attributeTranslations.read;if(t.values[name])return t.values[name](element,name);if(t.names[name])name=t.names[name];if(name.include(":"))return!element.attributes||!element.attributes[name]?null:element.attributes[name].value}return element.getAttribute(name)},writeAttribute:function(element,
name,value){element=$(element);var attributes={},t=Element._attributeTranslations.write;if(typeof name=="object")attributes=name;else attributes[name]=Object.isUndefined(value)?true:value;for(var attr in attributes){name=t.names[attr]||attr;value=attributes[attr];if(t.values[attr])name=t.values[attr](element,value);if(value===false||value===null)element.removeAttribute(name);else if(value===true)element.setAttribute(name,name);else element.setAttribute(name,value)}return element},getHeight:function(element){return Element.getDimensions(element).height},
getWidth:function(element){return Element.getDimensions(element).width},classNames:function(element){return new Element.ClassNames(element)},hasClassName:function(element,className){if(!(element=$(element)))return;var elementClassName=element.className;return elementClassName.length>0&&(elementClassName==className||(new RegExp("(^|\\s)"+className+"(\\s|$)")).test(elementClassName))},addClassName:function(element,className){if(!(element=$(element)))return;if(!Element.hasClassName(element,className))element.className+=
(element.className?" ":"")+className;return element},removeClassName:function(element,className){if(!(element=$(element)))return;element.className=element.className.replace(new RegExp("(^|\\s+)"+className+"(\\s+|$)")," ").strip();return element},toggleClassName:function(element,className){if(!(element=$(element)))return;return Element[Element.hasClassName(element,className)?"removeClassName":"addClassName"](element,className)},cleanWhitespace:function(element){element=$(element);var node=element.firstChild;
while(node){var nextNode=node.nextSibling;if(node.nodeType==3&&!/\S/.test(node.nodeValue))element.removeChild(node);node=nextNode}return element},empty:function(element){return $(element).innerHTML.blank()},descendantOf:function(element,ancestor){element=$(element),ancestor=$(ancestor);if(element.compareDocumentPosition)return(element.compareDocumentPosition(ancestor)&8)===8;if(ancestor.contains)return ancestor.contains(element)&&ancestor!==element;while(element=element.parentNode)if(element==ancestor)return true;
return false},scrollTo:function(element){element=$(element);var pos=Element.cumulativeOffset(element);window.scrollTo(pos[0],pos[1]);return element},getStyle:function(element,style){element=$(element);style=style=="float"?"cssFloat":style.camelize();var value=element.style[style];if(!value||value=="auto"){var css=document.defaultView.getComputedStyle(element,null);value=css?css[style]:null}if(style=="opacity")return value?parseFloat(value):1;return value=="auto"?null:value},getOpacity:function(element){return $(element).getStyle("opacity")},
setStyle:function(element,styles){element=$(element);var elementStyle=element.style,match;if(Object.isString(styles)){element.style.cssText+=";"+styles;return styles.include("opacity")?element.setOpacity(styles.match(/opacity:\s*(\d?\.?\d*)/)[1]):element}for(var property in styles)if(property=="opacity")element.setOpacity(styles[property]);else elementStyle[property=="float"||property=="cssFloat"?Object.isUndefined(elementStyle.styleFloat)?"cssFloat":"styleFloat":property]=styles[property];return element},
setOpacity:function(element,value){element=$(element);element.style.opacity=value==1||value===""?"":value<1.0E-5?0:value;return element},makePositioned:function(element){element=$(element);var pos=Element.getStyle(element,"position");if(pos=="static"||!pos){element._madePositioned=true;element.style.position="relative";if(Prototype.Browser.Opera){element.style.top=0;element.style.left=0}}return element},undoPositioned:function(element){element=$(element);if(element._madePositioned){element._madePositioned=
undefined;element.style.position=element.style.top=element.style.left=element.style.bottom=element.style.right=""}return element},makeClipping:function(element){element=$(element);if(element._overflow)return element;element._overflow=Element.getStyle(element,"overflow")||"auto";if(element._overflow!=="hidden")element.style.overflow="hidden";return element},undoClipping:function(element){element=$(element);if(!element._overflow)return element;element.style.overflow=element._overflow=="auto"?"":element._overflow;
element._overflow=null;return element},clonePosition:function(element,source){var options=Object.extend({setLeft:true,setTop:true,setWidth:true,setHeight:true,offsetTop:0,offsetLeft:0},arguments[2]||{});source=$(source);var p=Element.viewportOffset(source),delta=[0,0],parent=null;element=$(element);if(Element.getStyle(element,"position")=="absolute"){parent=Element.getOffsetParent(element);delta=Element.viewportOffset(parent)}if(parent==document.body){delta[0]-=document.body.offsetLeft;delta[1]-=
document.body.offsetTop}if(options.setLeft)element.style.left=p[0]-delta[0]+options.offsetLeft+"px";if(options.setTop)element.style.top=p[1]-delta[1]+options.offsetTop+"px";if(options.setWidth)element.style.width=source.offsetWidth+"px";if(options.setHeight)element.style.height=source.offsetHeight+"px";return element}};Object.extend(Element.Methods,{getElementsBySelector:Element.Methods.select,childElements:Element.Methods.immediateDescendants});
Element._attributeTranslations={write:{names:{className:"class",htmlFor:"for"},values:{}}};
if(Prototype.Browser.Opera){Element.Methods.getStyle=Element.Methods.getStyle.wrap(function(proceed,element,style){switch(style){case "height":case "width":if(!Element.visible(element))return null;var dim=parseInt(proceed(element,style),10);if(dim!==element["offset"+style.capitalize()])return dim+"px";var properties;if(style==="height")properties=["border-top-width","padding-top","padding-bottom","border-bottom-width"];else properties=["border-left-width","padding-left","padding-right","border-right-width"];
return properties.inject(dim,function(memo,property){var val=proceed(element,property);return val===null?memo:memo-parseInt(val,10)})+"px";default:return proceed(element,style)}});Element.Methods.readAttribute=Element.Methods.readAttribute.wrap(function(proceed,element,attribute){if(attribute==="title")return element.title;return proceed(element,attribute)})}else if(Prototype.Browser.IE){Element.Methods.getStyle=function(element,style){element=$(element);style=style=="float"||style=="cssFloat"?"styleFloat":
style.camelize();var value=element.style[style];if(!value&&element.currentStyle)value=element.currentStyle[style];if(style=="opacity"){if(value=(element.getStyle("filter")||"").match(/alpha\(opacity=(.*)\)/))if(value[1])return parseFloat(value[1])/100;return 1}if(value=="auto"){if((style=="width"||style=="height")&&element.getStyle("display")!="none")return element["offset"+style.capitalize()]+"px";return null}return value};Element.Methods.setOpacity=function(element,value){function stripAlpha(filter){return filter.replace(/alpha\([^\)]*\)/gi,
"")}element=$(element);var currentStyle=element.currentStyle;if(currentStyle&&!currentStyle.hasLayout||!currentStyle&&element.style.zoom=="normal")element.style.zoom=1;var filter=element.getStyle("filter"),style=element.style;if(value==1||value===""){(filter=stripAlpha(filter))?style.filter=filter:style.removeAttribute("filter");return element}else if(value<1.0E-5)value=0;style.filter=stripAlpha(filter)+"alpha(opacity="+value*100+")";return element};Element._attributeTranslations=function(){var classProp=
"className",forProp="for",el=document.createElement("div");el.setAttribute(classProp,"x");if(el.className!=="x"){el.setAttribute("class","x");if(el.className==="x")classProp="class"}el=null;el=document.createElement("label");el.setAttribute(forProp,"x");if(el.htmlFor!=="x"){el.setAttribute("htmlFor","x");if(el.htmlFor==="x")forProp="htmlFor"}el=null;return{read:{names:{"class":classProp,"className":classProp,"for":forProp,"htmlFor":forProp},values:{_getAttr:function(element,attribute){return element.getAttribute(attribute)},
_getAttr2:function(element,attribute){return element.getAttribute(attribute,2)},_getAttrNode:function(element,attribute){var node=element.getAttributeNode(attribute);return node?node.value:""},_getEv:function(){var el=document.createElement("div"),f;el.onclick=Prototype.emptyFunction;var value=el.getAttribute("onclick");if(String(value).indexOf("{")>-1)f=function(element,attribute){attribute=element.getAttribute(attribute);if(!attribute)return null;attribute=attribute.toString();attribute=attribute.split("{")[1];
attribute=attribute.split("}")[0];return attribute.strip()};else if(value==="")f=function(element,attribute){attribute=element.getAttribute(attribute);if(!attribute)return null;return attribute.strip()};el=null;return f}(),_flag:function(element,attribute){return $(element).hasAttribute(attribute)?attribute:null},style:function(element){return element.style.cssText.toLowerCase()},title:function(element){return element.title}}}}}();Element._attributeTranslations.write={names:Object.extend({cellpadding:"cellPadding",
cellspacing:"cellSpacing"},Element._attributeTranslations.read.names),values:{checked:function(element,value){element.checked=!!value},style:function(element,value){element.style.cssText=value?value:""}}};Element._attributeTranslations.has={};$w("colSpan rowSpan vAlign dateTime accessKey tabIndex "+"encType maxLength readOnly longDesc frameBorder").each(function(attr){Element._attributeTranslations.write.names[attr.toLowerCase()]=attr;Element._attributeTranslations.has[attr.toLowerCase()]=attr});
(function(v){Object.extend(v,{href:v._getAttr2,src:v._getAttr2,type:v._getAttr,action:v._getAttrNode,disabled:v._flag,checked:v._flag,readonly:v._flag,multiple:v._flag,onload:v._getEv,onunload:v._getEv,onclick:v._getEv,ondblclick:v._getEv,onmousedown:v._getEv,onmouseup:v._getEv,onmouseover:v._getEv,onmousemove:v._getEv,onmouseout:v._getEv,onfocus:v._getEv,onblur:v._getEv,onkeypress:v._getEv,onkeydown:v._getEv,onkeyup:v._getEv,onsubmit:v._getEv,onreset:v._getEv,onselect:v._getEv,onchange:v._getEv})})(Element._attributeTranslations.read.values);
if(Prototype.BrowserFeatures.ElementExtensions)(function(){function _descendants(element){var nodes=element.getElementsByTagName("*"),results=[];for(var i=0,node;node=nodes[i];i++)if(node.tagName!=="!")results.push(node);return results}Element.Methods.down=function(element,expression,index){element=$(element);if(arguments.length==1)return element.firstDescendant();return Object.isNumber(expression)?_descendants(element)[expression]:Element.select(element,expression)[index||0]}})()}else if(Prototype.Browser.Gecko&&
/rv:1\.8\.0/.test(navigator.userAgent))Element.Methods.setOpacity=function(element,value){element=$(element);element.style.opacity=value==1?0.999999:value===""?"":value<1.0E-5?0:value;return element};else if(Prototype.Browser.WebKit)Element.Methods.setOpacity=function(element,value){element=$(element);element.style.opacity=value==1||value===""?"":value<1.0E-5?0:value;if(value==1)if(element.tagName.toUpperCase()=="IMG"&&element.width){element.width++;element.width--}else try{var n=document.createTextNode(" ");
element.appendChild(n);element.removeChild(n)}catch(e){}return element};
if("outerHTML"in document.documentElement)Element.Methods.replace=function(element,content){element=$(element);if(content&&content.toElement)content=content.toElement();if(Object.isElement(content)){element.parentNode.replaceChild(content,element);return element}content=Object.toHTML(content);var parent=element.parentNode,tagName=parent.tagName.toUpperCase();if(Element._insertionTranslations.tags[tagName]){var nextSibling=element.next(),fragments=Element._getContentFromAnonymousElement(tagName,content.stripScripts());
parent.removeChild(element);if(nextSibling)fragments.each(function(node){parent.insertBefore(node,nextSibling)});else fragments.each(function(node){parent.appendChild(node)})}else element.outerHTML=content.stripScripts();content.evalScripts.bind(content).defer();return element};Element._returnOffset=function(l,t){var result=[l,t];result.left=l;result.top=t;return result};
Element._getContentFromAnonymousElement=function(tagName,html,force){var div=new Element("div"),t=Element._insertionTranslations.tags[tagName];var workaround=false;if(t)workaround=true;else if(force){workaround=true;t=["","",0]}if(workaround){div.innerHTML="&nbsp;"+t[0]+html+t[1];div.removeChild(div.firstChild);for(var i=t[2];i--;)div=div.firstChild}else div.innerHTML=html;return $A(div.childNodes)};
Element._insertionTranslations={before:function(element,node){element.parentNode.insertBefore(node,element)},top:function(element,node){element.insertBefore(node,element.firstChild)},bottom:function(element,node){element.appendChild(node)},after:function(element,node){element.parentNode.insertBefore(node,element.nextSibling)},tags:{TABLE:["<table>","</table>",1],TBODY:["<table><tbody>","</tbody></table>",2],TR:["<table><tbody><tr>","</tr></tbody></table>",3],TD:["<table><tbody><tr><td>","</td></tr></tbody></table>",
4],SELECT:["<select>","</select>",1]}};(function(){var tags=Element._insertionTranslations.tags;Object.extend(tags,{THEAD:tags.TBODY,TFOOT:tags.TBODY,TH:tags.TD})})();Element.Methods.Simulated={hasAttribute:function(element,attribute){attribute=Element._attributeTranslations.has[attribute]||attribute;var node=$(element).getAttributeNode(attribute);return!!(node&&node.specified)}};Element.Methods.ByTag={};Object.extend(Element,Element.Methods);
(function(div){if(!Prototype.BrowserFeatures.ElementExtensions&&div["__proto__"]){window.HTMLElement={};window.HTMLElement.prototype=div["__proto__"];Prototype.BrowserFeatures.ElementExtensions=true}div=null})(document.createElement("div"));
Element.extend=function(){function checkDeficiency(tagName){if(typeof window.Element!="undefined"){var proto=window.Element.prototype;if(proto){var id="_"+(Math.random()+"").slice(2),el=document.createElement(tagName);proto[id]="x";var isBuggy=el[id]!=="x";delete proto[id];el=null;return isBuggy}}return false}function extendElementWith(element,methods){for(var property in methods){var value=methods[property];if(Object.isFunction(value)&&!(property in element))element[property]=value.methodize()}}
var HTMLOBJECTELEMENT_PROTOTYPE_BUGGY=checkDeficiency("object");if(Prototype.BrowserFeatures.SpecificElementExtensions){if(HTMLOBJECTELEMENT_PROTOTYPE_BUGGY)return function(element){if(element&&typeof element._extendedByPrototype=="undefined"){var t=element.tagName;if(t&&/^(?:object|applet|embed)$/i.test(t)){extendElementWith(element,Element.Methods);extendElementWith(element,Element.Methods.Simulated);extendElementWith(element,Element.Methods.ByTag[t.toUpperCase()])}}return element};return Prototype.K}var Methods=
{},ByTag=Element.Methods.ByTag;var extend=Object.extend(function(element){if(!element||typeof element._extendedByPrototype!="undefined"||element.nodeType!=1||element==window)return element;var methods=Object.clone(Methods),tagName=element.tagName.toUpperCase();if(ByTag[tagName])Object.extend(methods,ByTag[tagName]);extendElementWith(element,methods);element._extendedByPrototype=Prototype.emptyFunction;return element},{refresh:function(){if(!Prototype.BrowserFeatures.ElementExtensions){Object.extend(Methods,
Element.Methods);Object.extend(Methods,Element.Methods.Simulated)}}});extend.refresh();return extend}();if(document.documentElement.hasAttribute)Element.hasAttribute=function(element,attribute){return element.hasAttribute(attribute)};else Element.hasAttribute=Element.Methods.Simulated.hasAttribute;
Element.addMethods=function(methods){var F=Prototype.BrowserFeatures,T=Element.Methods.ByTag;if(!methods){Object.extend(Form,Form.Methods);Object.extend(Form.Element,Form.Element.Methods);Object.extend(Element.Methods.ByTag,{"FORM":Object.clone(Form.Methods),"INPUT":Object.clone(Form.Element.Methods),"SELECT":Object.clone(Form.Element.Methods),"TEXTAREA":Object.clone(Form.Element.Methods),"BUTTON":Object.clone(Form.Element.Methods)})}if(arguments.length==2){var tagName=methods;methods=arguments[1]}if(!tagName)Object.extend(Element.Methods,
methods||{});else if(Object.isArray(tagName))tagName.each(extend);else extend(tagName);function extend(tagName){tagName=tagName.toUpperCase();if(!Element.Methods.ByTag[tagName])Element.Methods.ByTag[tagName]={};Object.extend(Element.Methods.ByTag[tagName],methods)}function copy(methods,destination,onlyIfAbsent){onlyIfAbsent=onlyIfAbsent||false;for(var property in methods){var value=methods[property];if(!Object.isFunction(value))continue;if(!onlyIfAbsent||!(property in destination))destination[property]=
value.methodize()}}function findDOMClass(tagName){var klass;var trans={"OPTGROUP":"OptGroup","TEXTAREA":"TextArea","P":"Paragraph","FIELDSET":"FieldSet","UL":"UList","OL":"OList","DL":"DList","DIR":"Directory","H1":"Heading","H2":"Heading","H3":"Heading","H4":"Heading","H5":"Heading","H6":"Heading","Q":"Quote","INS":"Mod","DEL":"Mod","A":"Anchor","IMG":"Image","CAPTION":"TableCaption","COL":"TableCol","COLGROUP":"TableCol","THEAD":"TableSection","TFOOT":"TableSection","TBODY":"TableSection","TR":"TableRow",
"TH":"TableCell","TD":"TableCell","FRAMESET":"FrameSet","IFRAME":"IFrame"};if(trans[tagName])klass="HTML"+trans[tagName]+"Element";if(window[klass])return window[klass];klass="HTML"+tagName+"Element";if(window[klass])return window[klass];klass="HTML"+tagName.capitalize()+"Element";if(window[klass])return window[klass];var element=document.createElement(tagName),proto=element["__proto__"]||element.constructor.prototype;element=null;return proto}var elementPrototype=window.HTMLElement?HTMLElement.prototype:
Element.prototype;if(F.ElementExtensions){copy(Element.Methods,elementPrototype);copy(Element.Methods.Simulated,elementPrototype,true)}if(F.SpecificElementExtensions)for(var tag in Element.Methods.ByTag){var klass=findDOMClass(tag);if(Object.isUndefined(klass))continue;copy(T[tag],klass.prototype)}Object.extend(Element,Element.Methods);delete Element.ByTag;if(Element.extend.refresh)Element.extend.refresh();Element.cache={}};
document.viewport={getDimensions:function(){return{width:this.getWidth(),height:this.getHeight()}},getScrollOffsets:function(){return Element._returnOffset(window.pageXOffset||document.documentElement.scrollLeft||document.body.scrollLeft,window.pageYOffset||document.documentElement.scrollTop||document.body.scrollTop)}};
(function(viewport){var B=Prototype.Browser,doc=document,element,property={};function getRootElement(){if(B.WebKit&&!doc.evaluate)return document;if(B.Opera&&window.parseFloat(window.opera.version())<9.5)return document.body;return document.documentElement}function define(D){if(!element)element=getRootElement();property[D]="client"+D;viewport["get"+D]=function(){return element[property[D]]};return viewport["get"+D]()}viewport.getWidth=define.curry("Width");viewport.getHeight=define.curry("Height")})(document.viewport);
Element.Storage={UID:1};
Element.addMethods({getStorage:function(element){if(!(element=$(element)))return;var uid;if(element===window)uid=0;else{if(typeof element._prototypeUID==="undefined")element._prototypeUID=Element.Storage.UID++;uid=element._prototypeUID}if(!Element.Storage[uid])Element.Storage[uid]=$H();return Element.Storage[uid]},store:function(element,key,value){if(!(element=$(element)))return;if(arguments.length===2)Element.getStorage(element).update(key);else Element.getStorage(element).set(key,value);return element},
retrieve:function(element,key,defaultValue){if(!(element=$(element)))return;var hash=Element.getStorage(element),value=hash.get(key);if(Object.isUndefined(value)){hash.set(key,defaultValue);value=defaultValue}return value},clone:function(element,deep){if(!(element=$(element)))return;var clone=element.cloneNode(deep);clone._prototypeUID=void 0;if(deep){var descendants=Element.select(clone,"*"),i=descendants.length;while(i--)descendants[i]._prototypeUID=void 0}return Element.extend(clone)},purge:function(element){if(!(element=
$(element)))return;var purgeElement=Element._purgeElement;purgeElement(element);var descendants=element.getElementsByTagName("*"),i=descendants.length;while(i--)purgeElement(descendants[i]);return null}});
(function(){function toDecimal(pctString){var match=pctString.match(/^(\d+)%?$/i);if(!match)return null;return Number(match[1])/100}function getPixelValue(value,property,context){var element=null;if(Object.isElement(value)){element=value;value=element.getStyle(property)}if(value===null)return null;if(/^(?:-)?\d+(\.\d+)?(px)?$/i.test(value))return window.parseFloat(value);var isPercentage=value.include("%"),isViewport=context===document.viewport;if(/\d/.test(value)&&element&&element.runtimeStyle&&
!(isPercentage&&isViewport)){var style=element.style.left,rStyle=element.runtimeStyle.left;element.runtimeStyle.left=element.currentStyle.left;element.style.left=value||0;value=element.style.pixelLeft;element.style.left=style;element.runtimeStyle.left=rStyle;return value}if(element&&isPercentage){context=context||element.parentNode;var decimal=toDecimal(value);var whole=null;var position=element.getStyle("position");var isHorizontal=property.include("left")||property.include("right")||property.include("width");
var isVertical=property.include("top")||property.include("bottom")||property.include("height");if(context===document.viewport)if(isHorizontal)whole=document.viewport.getWidth();else{if(isVertical)whole=document.viewport.getHeight()}else if(isHorizontal)whole=$(context).measure("width");else if(isVertical)whole=$(context).measure("height");return whole===null?0:whole*decimal}return 0}function toCSSPixels(number){if(Object.isString(number)&&number.endsWith("px"))return number;return number+"px"}function isDisplayed(element){var originalElement=
element;while(element&&element.parentNode){var display=element.getStyle("display");if(display==="none")return false;element=$(element.parentNode)}return true}var hasLayout=Prototype.K;if("currentStyle"in document.documentElement)hasLayout=function(element){if(!element.currentStyle.hasLayout)element.style.zoom=1;return element};function cssNameFor(key){if(key.include("border"))key=key+"-width";return key.camelize()}Element.Layout=Class.create(Hash,{initialize:function($super,element,preCompute){$super();
this.element=$(element);Element.Layout.PROPERTIES.each(function(property){this._set(property,null)},this);if(preCompute){this._preComputing=true;this._begin();Element.Layout.PROPERTIES.each(this._compute,this);this._end();this._preComputing=false}},_set:function(property,value){return Hash.prototype.set.call(this,property,value)},set:function(property,value){throw"Properties of Element.Layout are read-only.";},get:function($super,property){var value=$super(property);return value===null?this._compute(property):
value},_begin:function(){if(this._prepared)return;var element=this.element;if(isDisplayed(element)){this._prepared=true;return}var originalStyles={position:element.style.position||"",width:element.style.width||"",visibility:element.style.visibility||"",display:element.style.display||""};element.store("prototype_original_styles",originalStyles);var position=element.getStyle("position"),width=element.getStyle("width");if(width==="0px"||width===null){element.style.display="block";width=element.getStyle("width")}var context=
position==="fixed"?document.viewport:element.parentNode;element.setStyle({position:"absolute",visibility:"hidden",display:"block"});var positionedWidth=element.getStyle("width");var newWidth;if(width&&positionedWidth===width)newWidth=getPixelValue(element,"width",context);else if(position==="absolute"||position==="fixed")newWidth=getPixelValue(element,"width",context);else{var parent=element.parentNode,pLayout=$(parent).getLayout();newWidth=pLayout.get("width")-this.get("margin-left")-this.get("border-left")-
this.get("padding-left")-this.get("padding-right")-this.get("border-right")-this.get("margin-right")}element.setStyle({width:newWidth+"px"});this._prepared=true},_end:function(){var element=this.element;var originalStyles=element.retrieve("prototype_original_styles");element.store("prototype_original_styles",null);element.setStyle(originalStyles);this._prepared=false},_compute:function(property){var COMPUTATIONS=Element.Layout.COMPUTATIONS;if(!(property in COMPUTATIONS))throw"Property not found.";
return this._set(property,COMPUTATIONS[property].call(this,this.element))},toObject:function(){var args=$A(arguments);var keys=args.length===0?Element.Layout.PROPERTIES:args.join(" ").split(" ");var obj={};keys.each(function(key){if(!Element.Layout.PROPERTIES.include(key))return;var value=this.get(key);if(value!=null)obj[key]=value},this);return obj},toHash:function(){var obj=this.toObject.apply(this,arguments);return new Hash(obj)},toCSS:function(){var args=$A(arguments);var keys=args.length===0?
Element.Layout.PROPERTIES:args.join(" ").split(" ");var css={};keys.each(function(key){if(!Element.Layout.PROPERTIES.include(key))return;if(Element.Layout.COMPOSITE_PROPERTIES.include(key))return;var value=this.get(key);if(value!=null)css[cssNameFor(key)]=value+"px"},this);return css},inspect:function(){return"#<Element.Layout>"}});Object.extend(Element.Layout,{PROPERTIES:$w("height width top left right bottom border-left border-right border-top border-bottom padding-left padding-right padding-top padding-bottom margin-top margin-bottom margin-left margin-right padding-box-width padding-box-height border-box-width border-box-height margin-box-width margin-box-height"),
COMPOSITE_PROPERTIES:$w("padding-box-width padding-box-height margin-box-width margin-box-height border-box-width border-box-height"),COMPUTATIONS:{"height":function(element){if(!this._preComputing)this._begin();var bHeight=this.get("border-box-height");if(bHeight<=0){if(!this._preComputing)this._end();return 0}var bTop=this.get("border-top"),bBottom=this.get("border-bottom");var pTop=this.get("padding-top"),pBottom=this.get("padding-bottom");if(!this._preComputing)this._end();return bHeight-bTop-
bBottom-pTop-pBottom},"width":function(element){if(!this._preComputing)this._begin();var bWidth=this.get("border-box-width");if(bWidth<=0){if(!this._preComputing)this._end();return 0}var bLeft=this.get("border-left"),bRight=this.get("border-right");var pLeft=this.get("padding-left"),pRight=this.get("padding-right");if(!this._preComputing)this._end();return bWidth-bLeft-bRight-pLeft-pRight},"padding-box-height":function(element){var height=this.get("height"),pTop=this.get("padding-top"),pBottom=this.get("padding-bottom");
return height+pTop+pBottom},"padding-box-width":function(element){var width=this.get("width"),pLeft=this.get("padding-left"),pRight=this.get("padding-right");return width+pLeft+pRight},"border-box-height":function(element){if(!this._preComputing)this._begin();var height=element.offsetHeight;if(!this._preComputing)this._end();return height},"border-box-width":function(element){if(!this._preComputing)this._begin();var width=element.offsetWidth;if(!this._preComputing)this._end();return width},"margin-box-height":function(element){var bHeight=
this.get("border-box-height"),mTop=this.get("margin-top"),mBottom=this.get("margin-bottom");if(bHeight<=0)return 0;return bHeight+mTop+mBottom},"margin-box-width":function(element){var bWidth=this.get("border-box-width"),mLeft=this.get("margin-left"),mRight=this.get("margin-right");if(bWidth<=0)return 0;return bWidth+mLeft+mRight},"top":function(element){var offset=element.positionedOffset();return offset.top},"bottom":function(element){var offset=element.positionedOffset(),parent=element.getOffsetParent(),
pHeight=parent.measure("height");var mHeight=this.get("border-box-height");return pHeight-mHeight-offset.top},"left":function(element){var offset=element.positionedOffset();return offset.left},"right":function(element){var offset=element.positionedOffset(),parent=element.getOffsetParent(),pWidth=parent.measure("width");var mWidth=this.get("border-box-width");return pWidth-mWidth-offset.left},"padding-top":function(element){return getPixelValue(element,"paddingTop")},"padding-bottom":function(element){return getPixelValue(element,
"paddingBottom")},"padding-left":function(element){return getPixelValue(element,"paddingLeft")},"padding-right":function(element){return getPixelValue(element,"paddingRight")},"border-top":function(element){return getPixelValue(element,"borderTopWidth")},"border-bottom":function(element){return getPixelValue(element,"borderBottomWidth")},"border-left":function(element){return getPixelValue(element,"borderLeftWidth")},"border-right":function(element){return getPixelValue(element,"borderRightWidth")},
"margin-top":function(element){return getPixelValue(element,"marginTop")},"margin-bottom":function(element){return getPixelValue(element,"marginBottom")},"margin-left":function(element){return getPixelValue(element,"marginLeft")},"margin-right":function(element){return getPixelValue(element,"marginRight")}}});if("getBoundingClientRect"in document.documentElement)Object.extend(Element.Layout.COMPUTATIONS,{"right":function(element){var parent=hasLayout(element.getOffsetParent());var rect=element.getBoundingClientRect(),
pRect=parent.getBoundingClientRect();return(pRect.right-rect.right).round()},"bottom":function(element){var parent=hasLayout(element.getOffsetParent());var rect=element.getBoundingClientRect(),pRect=parent.getBoundingClientRect();return(pRect.bottom-rect.bottom).round()}});Element.Offset=Class.create({initialize:function(left,top){this.left=left.round();this.top=top.round();this[0]=this.left;this[1]=this.top},relativeTo:function(offset){return new Element.Offset(this.left-offset.left,this.top-offset.top)},
inspect:function(){return"#<Element.Offset left: #{left} top: #{top}>".interpolate(this)},toString:function(){return"[#{left}, #{top}]".interpolate(this)},toArray:function(){return[this.left,this.top]}});function getLayout(element,preCompute){return new Element.Layout(element,preCompute)}function measure(element,property){return $(element).getLayout().get(property)}function getDimensions(element){element=$(element);var display=Element.getStyle(element,"display");if(display&&display!=="none")return{width:element.offsetWidth,
height:element.offsetHeight};var style=element.style;var originalStyles={visibility:style.visibility,position:style.position,display:style.display};var newStyles={visibility:"hidden",display:"block"};if(originalStyles.position!=="fixed")newStyles.position="absolute";Element.setStyle(element,newStyles);var dimensions={width:element.offsetWidth,height:element.offsetHeight};Element.setStyle(element,originalStyles);return dimensions}function getOffsetParent(element){element=$(element);if(isDocument(element)||
isDetached(element)||isBody(element)||isHtml(element))return $(document.body);var isInline=Element.getStyle(element,"display")==="inline";if(!isInline&&element.offsetParent)return $(element.offsetParent);while((element=element.parentNode)&&element!==document.body)if(Element.getStyle(element,"position")!=="static")return isHtml(element)?$(document.body):$(element);return $(document.body)}function cumulativeOffset(element){element=$(element);var valueT=0,valueL=0;if(element.parentNode){do{valueT+=element.offsetTop||
0;valueL+=element.offsetLeft||0;element=element.offsetParent}while(element)}return new Element.Offset(valueL,valueT)}function positionedOffset(element){element=$(element);var layout=element.getLayout();var valueT=0,valueL=0;do{valueT+=element.offsetTop||0;valueL+=element.offsetLeft||0;element=element.offsetParent;if(element){if(isBody(element))break;var p=Element.getStyle(element,"position");if(p!=="static")break}}while(element);valueL-=layout.get("margin-top");valueT-=layout.get("margin-left");return new Element.Offset(valueL,
valueT)}function cumulativeScrollOffset(element){var valueT=0,valueL=0;do{valueT+=element.scrollTop||0;valueL+=element.scrollLeft||0;element=element.parentNode}while(element);return new Element.Offset(valueL,valueT)}function viewportOffset(forElement){element=$(element);var valueT=0,valueL=0,docBody=document.body;var element=forElement;do{valueT+=element.offsetTop||0;valueL+=element.offsetLeft||0;if(element.offsetParent==docBody&&Element.getStyle(element,"position")=="absolute")break}while(element=
element.offsetParent);element=forElement;do if(element!=docBody){valueT-=element.scrollTop||0;valueL-=element.scrollLeft||0}while(element=element.parentNode);return new Element.Offset(valueL,valueT)}function absolutize(element){element=$(element);if(Element.getStyle(element,"position")==="absolute")return element;var offsetParent=getOffsetParent(element);var eOffset=element.viewportOffset(),pOffset=offsetParent.viewportOffset();var offset=eOffset.relativeTo(pOffset);var layout=element.getLayout();
element.store("prototype_absolutize_original_styles",{left:element.getStyle("left"),top:element.getStyle("top"),width:element.getStyle("width"),height:element.getStyle("height")});element.setStyle({position:"absolute",top:offset.top+"px",left:offset.left+"px",width:layout.get("width")+"px",height:layout.get("height")+"px"});return element}function relativize(element){element=$(element);if(Element.getStyle(element,"position")==="relative")return element;var originalStyles=element.retrieve("prototype_absolutize_original_styles");
if(originalStyles)element.setStyle(originalStyles);return element}if(Prototype.Browser.IE){getOffsetParent=getOffsetParent.wrap(function(proceed,element){element=$(element);if(isDocument(element)||isDetached(element)||isBody(element)||isHtml(element))return $(document.body);var position=element.getStyle("position");if(position!=="static")return proceed(element);element.setStyle({position:"relative"});var value=proceed(element);element.setStyle({position:position});return value});positionedOffset=
positionedOffset.wrap(function(proceed,element){element=$(element);if(!element.parentNode)return new Element.Offset(0,0);var position=element.getStyle("position");if(position!=="static")return proceed(element);var offsetParent=element.getOffsetParent();if(offsetParent&&offsetParent.getStyle("position")==="fixed")hasLayout(offsetParent);element.setStyle({position:"relative"});var value=proceed(element);element.setStyle({position:position});return value})}else if(Prototype.Browser.Webkit)cumulativeOffset=
function(element){element=$(element);var valueT=0,valueL=0;do{valueT+=element.offsetTop||0;valueL+=element.offsetLeft||0;if(element.offsetParent==document.body)if(Element.getStyle(element,"position")=="absolute")break;element=element.offsetParent}while(element);return new Element.Offset(valueL,valueT)};Element.addMethods({getLayout:getLayout,measure:measure,getDimensions:getDimensions,getOffsetParent:getOffsetParent,cumulativeOffset:cumulativeOffset,positionedOffset:positionedOffset,cumulativeScrollOffset:cumulativeScrollOffset,
viewportOffset:viewportOffset,absolutize:absolutize,relativize:relativize});function isBody(element){return element.nodeName.toUpperCase()==="BODY"}function isHtml(element){return element.nodeName.toUpperCase()==="HTML"}function isDocument(element){return element.nodeType===Node.DOCUMENT_NODE}function isDetached(element){return element!==document.body&&!Element.descendantOf(element,document.body)}if("getBoundingClientRect"in document.documentElement)Element.addMethods({viewportOffset:function(element){element=
$(element);if(isDetached(element))return new Element.Offset(0,0);var rect=element.getBoundingClientRect(),docEl=document.documentElement;return new Element.Offset(rect.left-docEl.clientLeft,rect.top-docEl.clientTop)}})})();window.$$=function(){var expression=$A(arguments).join(", ");return Prototype.Selector.select(expression,document)};
Prototype.Selector=function(){function select(){throw new Error('Method "Prototype.Selector.select" must be defined.');}function match(){throw new Error('Method "Prototype.Selector.match" must be defined.');}function find(elements,expression,index){index=index||0;var match=Prototype.Selector.match,length=elements.length,matchIndex=0,i;for(i=0;i<length;i++)if(match(elements[i],expression)&&index==matchIndex++)return Element.extend(elements[i])}function extendElements(elements){for(var i=0,length=elements.length;i<
length;i++)Element.extend(elements[i]);return elements}var K=Prototype.K;return{select:select,match:match,find:find,extendElements:Element.extend===K?K:extendElements,extendElement:Element.extend}}();
(function(){var chunker=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]*\]|['"][^'"]*['"]|[^[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,done=0,toString=Object.prototype.toString,hasDuplicate=false,baseHasDuplicate=true;[0,0].sort(function(){baseHasDuplicate=false;return 0});var Sizzle=function(selector,context,results,seed){results=results||[];var origContext=context=context||document;if(context.nodeType!==1&&context.nodeType!==9)return[];if(!selector||typeof selector!=="string")return results;
var parts=[],m,set,checkSet,check,mode,extra,prune=true,contextXML=isXML(context),soFar=selector;while((chunker.exec(""),m=chunker.exec(soFar))!==null){soFar=m[3];parts.push(m[1]);if(m[2]){extra=m[3];break}}if(parts.length>1&&origPOS.exec(selector))if(parts.length===2&&Expr.relative[parts[0]])set=posProcess(parts[0]+parts[1],context);else{set=Expr.relative[parts[0]]?[context]:Sizzle(parts.shift(),context);while(parts.length){selector=parts.shift();if(Expr.relative[selector])selector+=parts.shift();
set=posProcess(selector,set)}}else{if(!seed&&parts.length>1&&context.nodeType===9&&!contextXML&&Expr.match.ID.test(parts[0])&&!Expr.match.ID.test(parts[parts.length-1])){var ret=Sizzle.find(parts.shift(),context,contextXML);context=ret.expr?Sizzle.filter(ret.expr,ret.set)[0]:ret.set[0]}if(context){var ret=seed?{expr:parts.pop(),set:makeArray(seed)}:Sizzle.find(parts.pop(),parts.length===1&&(parts[0]==="~"||parts[0]==="+")&&context.parentNode?context.parentNode:context,contextXML);set=ret.expr?Sizzle.filter(ret.expr,
ret.set):ret.set;if(parts.length>0)checkSet=makeArray(set);else prune=false;while(parts.length){var cur=parts.pop(),pop=cur;if(!Expr.relative[cur])cur="";else pop=parts.pop();if(pop==null)pop=context;Expr.relative[cur](checkSet,pop,contextXML)}}else checkSet=parts=[]}if(!checkSet)checkSet=set;if(!checkSet)throw"Syntax error, unrecognized expression: "+(cur||selector);if(toString.call(checkSet)==="[object Array]")if(!prune)results.push.apply(results,checkSet);else if(context&&context.nodeType===1)for(var i=
0;checkSet[i]!=null;i++){if(checkSet[i]&&(checkSet[i]===true||checkSet[i].nodeType===1&&contains(context,checkSet[i])))results.push(set[i])}else for(var i=0;checkSet[i]!=null;i++){if(checkSet[i]&&checkSet[i].nodeType===1)results.push(set[i])}else makeArray(checkSet,results);if(extra){Sizzle(extra,origContext,results,seed);Sizzle.uniqueSort(results)}return results};Sizzle.uniqueSort=function(results){if(sortOrder){hasDuplicate=baseHasDuplicate;results.sort(sortOrder);if(hasDuplicate)for(var i=1;i<
results.length;i++)if(results[i]===results[i-1])results.splice(i--,1)}return results};Sizzle.matches=function(expr,set){return Sizzle(expr,null,null,set)};Sizzle.find=function(expr,context,isXML){var set,match;if(!expr)return[];for(var i=0,l=Expr.order.length;i<l;i++){var type=Expr.order[i],match;if(match=Expr.leftMatch[type].exec(expr)){var left=match[1];match.splice(1,1);if(left.substr(left.length-1)!=="\\"){match[1]=(match[1]||"").replace(/\\/g,"");set=Expr.find[type](match,context,isXML);if(set!=
null){expr=expr.replace(Expr.match[type],"");break}}}}if(!set)set=context.getElementsByTagName("*");return{set:set,expr:expr}};Sizzle.filter=function(expr,set,inplace,not){var old=expr,result=[],curLoop=set,match,anyFound,isXMLFilter=set&&set[0]&&isXML(set[0]);while(expr&&set.length){for(var type in Expr.filter)if((match=Expr.match[type].exec(expr))!=null){var filter=Expr.filter[type],found,item;anyFound=false;if(curLoop==result)result=[];if(Expr.preFilter[type]){match=Expr.preFilter[type](match,
curLoop,inplace,result,not,isXMLFilter);if(!match)anyFound=found=true;else if(match===true)continue}if(match)for(var i=0;(item=curLoop[i])!=null;i++)if(item){found=filter(item,match,i,curLoop);var pass=not^!!found;if(inplace&&found!=null)if(pass)anyFound=true;else curLoop[i]=false;else if(pass){result.push(item);anyFound=true}}if(found!==undefined){if(!inplace)curLoop=result;expr=expr.replace(Expr.match[type],"");if(!anyFound)return[];break}}if(expr==old)if(anyFound==null)throw"Syntax error, unrecognized expression: "+
expr;else break;old=expr}return curLoop};var Expr=Sizzle.selectors={order:["ID","NAME","TAG"],match:{ID:/#((?:[\w\u00c0-\uFFFF-]|\\.)+)/,CLASS:/\.((?:[\w\u00c0-\uFFFF-]|\\.)+)/,NAME:/\[name=['"]*((?:[\w\u00c0-\uFFFF-]|\\.)+)['"]*\]/,ATTR:/\[\s*((?:[\w\u00c0-\uFFFF-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\((even|odd|[\dn+-]*)\))?/,POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF-]|\\.)+)(?:\((['"]*)((?:\([^\)]+\)|[^\2\(\)]*)+)\2\))?/},
leftMatch:{},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(elem){return elem.getAttribute("href")}},relative:{"+":function(checkSet,part,isXML){var isPartStr=typeof part==="string",isTag=isPartStr&&!/\W/.test(part),isPartStrNotTag=isPartStr&&!isTag;if(isTag&&!isXML)part=part.toUpperCase();for(var i=0,l=checkSet.length,elem;i<l;i++)if(elem=checkSet[i]){while((elem=elem.previousSibling)&&elem.nodeType!==1);checkSet[i]=isPartStrNotTag||elem&&elem.nodeName===part?elem||false:
elem===part}if(isPartStrNotTag)Sizzle.filter(part,checkSet,true)},">":function(checkSet,part,isXML){var isPartStr=typeof part==="string";if(isPartStr&&!/\W/.test(part)){part=isXML?part:part.toUpperCase();for(var i=0,l=checkSet.length;i<l;i++){var elem=checkSet[i];if(elem){var parent=elem.parentNode;checkSet[i]=parent.nodeName===part?parent:false}}}else{for(var i=0,l=checkSet.length;i<l;i++){var elem=checkSet[i];if(elem)checkSet[i]=isPartStr?elem.parentNode:elem.parentNode===part}if(isPartStr)Sizzle.filter(part,
checkSet,true)}},"":function(checkSet,part,isXML){var doneName=done++,checkFn=dirCheck;if(!/\W/.test(part)){var nodeCheck=part=isXML?part:part.toUpperCase();checkFn=dirNodeCheck}checkFn("parentNode",part,doneName,checkSet,nodeCheck,isXML)},"~":function(checkSet,part,isXML){var doneName=done++,checkFn=dirCheck;if(typeof part==="string"&&!/\W/.test(part)){var nodeCheck=part=isXML?part:part.toUpperCase();checkFn=dirNodeCheck}checkFn("previousSibling",part,doneName,checkSet,nodeCheck,isXML)}},find:{ID:function(match,
context,isXML){if(typeof context.getElementById!=="undefined"&&!isXML){var m=context.getElementById(match[1]);return m?[m]:[]}},NAME:function(match,context,isXML){if(typeof context.getElementsByName!=="undefined"){var ret=[],results=context.getElementsByName(match[1]);for(var i=0,l=results.length;i<l;i++)if(results[i].getAttribute("name")===match[1])ret.push(results[i]);return ret.length===0?null:ret}},TAG:function(match,context){return context.getElementsByTagName(match[1])}},preFilter:{CLASS:function(match,
curLoop,inplace,result,not,isXML){match=" "+match[1].replace(/\\/g,"")+" ";if(isXML)return match;for(var i=0,elem;(elem=curLoop[i])!=null;i++)if(elem)if(not^(elem.className&&(" "+elem.className+" ").indexOf(match)>=0)){if(!inplace)result.push(elem)}else if(inplace)curLoop[i]=false;return false},ID:function(match){return match[1].replace(/\\/g,"")},TAG:function(match,curLoop){for(var i=0;curLoop[i]===false;i++);return curLoop[i]&&isXML(curLoop[i])?match[1]:match[1].toUpperCase()},CHILD:function(match){if(match[1]==
"nth"){var test=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(match[2]=="even"&&"2n"||match[2]=="odd"&&"2n+1"||!/\D/.test(match[2])&&"0n+"+match[2]||match[2]);match[2]=test[1]+(test[2]||1)-0;match[3]=test[3]-0}match[0]=done++;return match},ATTR:function(match,curLoop,inplace,result,not,isXML){var name=match[1].replace(/\\/g,"");if(!isXML&&Expr.attrMap[name])match[1]=Expr.attrMap[name];if(match[2]==="~=")match[4]=" "+match[4]+" ";return match},PSEUDO:function(match,curLoop,inplace,result,not){if(match[1]==="not")if((chunker.exec(match[3])||
"").length>1||/^\w/.test(match[3]))match[3]=Sizzle(match[3],null,null,curLoop);else{var ret=Sizzle.filter(match[3],curLoop,inplace,true^not);if(!inplace)result.push.apply(result,ret);return false}else if(Expr.match.POS.test(match[0])||Expr.match.CHILD.test(match[0]))return true;return match},POS:function(match){match.unshift(true);return match}},filters:{enabled:function(elem){return elem.disabled===false&&elem.type!=="hidden"},disabled:function(elem){return elem.disabled===true},checked:function(elem){return elem.checked===
true},selected:function(elem){elem.parentNode.selectedIndex;return elem.selected===true},parent:function(elem){return!!elem.firstChild},empty:function(elem){return!elem.firstChild},has:function(elem,i,match){return!!Sizzle(match[3],elem).length},header:function(elem){return/h\d/i.test(elem.nodeName)},text:function(elem){return"text"===elem.type},radio:function(elem){return"radio"===elem.type},checkbox:function(elem){return"checkbox"===elem.type},file:function(elem){return"file"===elem.type},password:function(elem){return"password"===
elem.type},submit:function(elem){return"submit"===elem.type},image:function(elem){return"image"===elem.type},reset:function(elem){return"reset"===elem.type},button:function(elem){return"button"===elem.type||elem.nodeName.toUpperCase()==="BUTTON"},input:function(elem){return/input|select|textarea|button/i.test(elem.nodeName)}},setFilters:{first:function(elem,i){return i===0},last:function(elem,i,match,array){return i===array.length-1},even:function(elem,i){return i%2===0},odd:function(elem,i){return i%
2===1},lt:function(elem,i,match){return i<match[3]-0},gt:function(elem,i,match){return i>match[3]-0},nth:function(elem,i,match){return match[3]-0==i},eq:function(elem,i,match){return match[3]-0==i}},filter:{PSEUDO:function(elem,match,i,array){var name=match[1],filter=Expr.filters[name];if(filter)return filter(elem,i,match,array);else if(name==="contains")return(elem.textContent||elem.innerText||"").indexOf(match[3])>=0;else if(name==="not"){var not=match[3];for(var i=0,l=not.length;i<l;i++)if(not[i]===
elem)return false;return true}},CHILD:function(elem,match){var type=match[1],node=elem;switch(type){case "only":case "first":while(node=node.previousSibling)if(node.nodeType===1)return false;if(type=="first")return true;node=elem;case "last":while(node=node.nextSibling)if(node.nodeType===1)return false;return true;case "nth":var first=match[2],last=match[3];if(first==1&&last==0)return true;var doneName=match[0],parent=elem.parentNode;if(parent&&(parent.sizcache!==doneName||!elem.nodeIndex)){var count=
0;for(node=parent.firstChild;node;node=node.nextSibling)if(node.nodeType===1)node.nodeIndex=++count;parent.sizcache=doneName}var diff=elem.nodeIndex-last;if(first==0)return diff==0;else return diff%first==0&&diff/first>=0}},ID:function(elem,match){return elem.nodeType===1&&elem.getAttribute("id")===match},TAG:function(elem,match){return match==="*"&&elem.nodeType===1||elem.nodeName===match},CLASS:function(elem,match){return(" "+(elem.className||elem.getAttribute("class"))+" ").indexOf(match)>-1},
ATTR:function(elem,match){var name=match[1],result=Expr.attrHandle[name]?Expr.attrHandle[name](elem):elem[name]!=null?elem[name]:elem.getAttribute(name),value=result+"",type=match[2],check=match[4];return result==null?type==="!=":type==="="?value===check:type==="*="?value.indexOf(check)>=0:type==="~="?(" "+value+" ").indexOf(check)>=0:!check?value&&result!==false:type==="!="?value!=check:type==="^="?value.indexOf(check)===0:type==="$="?value.substr(value.length-check.length)===check:type==="|="?value===
check||value.substr(0,check.length+1)===check+"-":false},POS:function(elem,match,i,array){var name=match[2],filter=Expr.setFilters[name];if(filter)return filter(elem,i,match,array)}}};var origPOS=Expr.match.POS;for(var type in Expr.match){Expr.match[type]=new RegExp(Expr.match[type].source+/(?![^\[]*\])(?![^\(]*\))/.source);Expr.leftMatch[type]=new RegExp(/(^(?:.|\r|\n)*?)/.source+Expr.match[type].source)}var makeArray=function(array,results){array=Array.prototype.slice.call(array,0);if(results){results.push.apply(results,
array);return results}return array};try{Array.prototype.slice.call(document.documentElement.childNodes,0)}catch(e){makeArray=function(array,results){var ret=results||[];if(toString.call(array)==="[object Array]")Array.prototype.push.apply(ret,array);else if(typeof array.length==="number")for(var i=0,l=array.length;i<l;i++)ret.push(array[i]);else for(var i=0;array[i];i++)ret.push(array[i]);return ret}}var sortOrder;if(document.documentElement.compareDocumentPosition)sortOrder=function(a,b){if(!a.compareDocumentPosition||
!b.compareDocumentPosition){if(a==b)hasDuplicate=true;return 0}var ret=a.compareDocumentPosition(b)&4?-1:a===b?0:1;if(ret===0)hasDuplicate=true;return ret};else if("sourceIndex"in document.documentElement)sortOrder=function(a,b){if(!a.sourceIndex||!b.sourceIndex){if(a==b)hasDuplicate=true;return 0}var ret=a.sourceIndex-b.sourceIndex;if(ret===0)hasDuplicate=true;return ret};else if(document.createRange)sortOrder=function(a,b){if(!a.ownerDocument||!b.ownerDocument){if(a==b)hasDuplicate=true;return 0}var aRange=
a.ownerDocument.createRange(),bRange=b.ownerDocument.createRange();aRange.setStart(a,0);aRange.setEnd(a,0);bRange.setStart(b,0);bRange.setEnd(b,0);var ret=aRange.compareBoundaryPoints(Range.START_TO_END,bRange);if(ret===0)hasDuplicate=true;return ret};(function(){var form=document.createElement("div"),id="script"+(new Date).getTime();form.innerHTML="<a name='"+id+"'/>";var root=document.documentElement;root.insertBefore(form,root.firstChild);if(!!document.getElementById(id)){Expr.find.ID=function(match,
context,isXML){if(typeof context.getElementById!=="undefined"&&!isXML){var m=context.getElementById(match[1]);return m?m.id===match[1]||typeof m.getAttributeNode!=="undefined"&&m.getAttributeNode("id").nodeValue===match[1]?[m]:undefined:[]}};Expr.filter.ID=function(elem,match){var node=typeof elem.getAttributeNode!=="undefined"&&elem.getAttributeNode("id");return elem.nodeType===1&&node&&node.nodeValue===match}}root.removeChild(form);root=form=null})();(function(){var div=document.createElement("div");
div.appendChild(document.createComment(""));if(div.getElementsByTagName("*").length>0)Expr.find.TAG=function(match,context){var results=context.getElementsByTagName(match[1]);if(match[1]==="*"){var tmp=[];for(var i=0;results[i];i++)if(results[i].nodeType===1)tmp.push(results[i]);results=tmp}return results};div.innerHTML="<a href='#'></a>";if(div.firstChild&&typeof div.firstChild.getAttribute!=="undefined"&&div.firstChild.getAttribute("href")!=="#")Expr.attrHandle.href=function(elem){return elem.getAttribute("href",
2)};div=null})();if(document.querySelectorAll)(function(){var oldSizzle=Sizzle,div=document.createElement("div");div.innerHTML="<p class='TEST'></p>";if(div.querySelectorAll&&div.querySelectorAll(".TEST").length===0)return;Sizzle=function(query,context,extra,seed){context=context||document;if(!seed&&context.nodeType===9&&!isXML(context))try{return makeArray(context.querySelectorAll(query),extra)}catch(e){}return oldSizzle(query,context,extra,seed)};for(var prop in oldSizzle)Sizzle[prop]=oldSizzle[prop];
div=null})();if(document.getElementsByClassName&&document.documentElement.getElementsByClassName)(function(){var div=document.createElement("div");div.innerHTML="<div class='test e'></div><div class='test'></div>";if(div.getElementsByClassName("e").length===0)return;div.lastChild.className="e";if(div.getElementsByClassName("e").length===1)return;Expr.order.splice(1,0,"CLASS");Expr.find.CLASS=function(match,context,isXML){if(typeof context.getElementsByClassName!=="undefined"&&!isXML)return context.getElementsByClassName(match[1])};
div=null})();function dirNodeCheck(dir,cur,doneName,checkSet,nodeCheck,isXML){var sibDir=dir=="previousSibling"&&!isXML;for(var i=0,l=checkSet.length;i<l;i++){var elem=checkSet[i];if(elem){if(sibDir&&elem.nodeType===1){elem.sizcache=doneName;elem.sizset=i}elem=elem[dir];var match=false;while(elem){if(elem.sizcache===doneName){match=checkSet[elem.sizset];break}if(elem.nodeType===1&&!isXML){elem.sizcache=doneName;elem.sizset=i}if(elem.nodeName===cur){match=elem;break}elem=elem[dir]}checkSet[i]=match}}}
function dirCheck(dir,cur,doneName,checkSet,nodeCheck,isXML){var sibDir=dir=="previousSibling"&&!isXML;for(var i=0,l=checkSet.length;i<l;i++){var elem=checkSet[i];if(elem){if(sibDir&&elem.nodeType===1){elem.sizcache=doneName;elem.sizset=i}elem=elem[dir];var match=false;while(elem){if(elem.sizcache===doneName){match=checkSet[elem.sizset];break}if(elem.nodeType===1){if(!isXML){elem.sizcache=doneName;elem.sizset=i}if(typeof cur!=="string"){if(elem===cur){match=true;break}}else if(Sizzle.filter(cur,[elem]).length>
0){match=elem;break}}elem=elem[dir]}checkSet[i]=match}}}var contains=document.compareDocumentPosition?function(a,b){return a.compareDocumentPosition(b)&16}:function(a,b){return a!==b&&(a.contains?a.contains(b):true)};var isXML=function(elem){return elem.nodeType===9&&elem.documentElement.nodeName!=="HTML"||!!elem.ownerDocument&&elem.ownerDocument.documentElement.nodeName!=="HTML"};var posProcess=function(selector,context){var tmpSet=[],later="",match,root=context.nodeType?[context]:context;while(match=
Expr.match.PSEUDO.exec(selector)){later+=match[0];selector=selector.replace(Expr.match.PSEUDO,"")}selector=Expr.relative[selector]?selector+"*":selector;for(var i=0,l=root.length;i<l;i++)Sizzle(selector,root[i],tmpSet);return Sizzle.filter(later,tmpSet)};window.Sizzle=Sizzle})();Prototype._original_property=window.Sizzle;
(function(engine){var extendElements=Prototype.Selector.extendElements;function select(selector,scope){return extendElements(engine(selector,scope||document))}function match(element,selector){return engine.matches(selector,[element]).length==1}Prototype.Selector.engine=engine;Prototype.Selector.select=select;Prototype.Selector.match=match})(Sizzle);window.Sizzle=Prototype._original_property;delete Prototype._original_property;
var Form={reset:function(form){form=$(form);form.reset();return form},serializeElements:function(elements,options){if(typeof options!="object")options={hash:!!options};else if(Object.isUndefined(options.hash))options.hash=true;var key,value,submitted=false,submit=options.submit,accumulator,initial;if(options.hash){initial={};accumulator=function(result,key,value){if(key in result){if(!Object.isArray(result[key]))result[key]=[result[key]];result[key].push(value)}else result[key]=value;return result}}else{initial=
"";accumulator=function(result,key,value){return result+(result?"&":"")+encodeURIComponent(key)+"="+encodeURIComponent(value)}}return elements.inject(initial,function(result,element){if(!element.disabled&&element.name){key=element.name;value=$(element).getValue();if(value!=null&&element.type!="file"&&(element.type!="submit"||!submitted&&submit!==false&&(!submit||key==submit)&&(submitted=true)))result=accumulator(result,key,value)}return result})}};
Form.Methods={serialize:function(form,options){return Form.serializeElements(Form.getElements(form),options)},getElements:function(form){var elements=$(form).getElementsByTagName("*"),element,arr=[],serializers=Form.Element.Serializers;for(var i=0;element=elements[i];i++)arr.push(element);return arr.inject([],function(elements,child){if(serializers[child.tagName.toLowerCase()])elements.push(Element.extend(child));return elements})},getInputs:function(form,typeName,name){form=$(form);var inputs=form.getElementsByTagName("input");
if(!typeName&&!name)return $A(inputs).map(Element.extend);for(var i=0,matchingInputs=[],length=inputs.length;i<length;i++){var input=inputs[i];if(typeName&&input.type!=typeName||name&&input.name!=name)continue;matchingInputs.push(Element.extend(input))}return matchingInputs},disable:function(form){form=$(form);Form.getElements(form).invoke("disable");return form},enable:function(form){form=$(form);Form.getElements(form).invoke("enable");return form},findFirstElement:function(form){var elements=$(form).getElements().findAll(function(element){return"hidden"!=
element.type&&!element.disabled});var firstByIndex=elements.findAll(function(element){return element.hasAttribute("tabIndex")&&element.tabIndex>=0}).sortBy(function(element){return element.tabIndex}).first();return firstByIndex?firstByIndex:elements.find(function(element){return/^(?:input|select|textarea)$/i.test(element.tagName)})},focusFirstElement:function(form){form=$(form);var element=form.findFirstElement();if(element)element.activate();return form},request:function(form,options){form=$(form),
options=Object.clone(options||{});var params=options.parameters,action=form.readAttribute("action")||"";if(action.blank())action=window.location.href;options.parameters=form.serialize(true);if(params){if(Object.isString(params))params=params.toQueryParams();Object.extend(options.parameters,params)}if(form.hasAttribute("method")&&!options.method)options.method=form.method;return new Ajax.Request(action,options)}};
Form.Element={focus:function(element){$(element).focus();return element},select:function(element){$(element).select();return element}};
Form.Element.Methods={serialize:function(element){element=$(element);if(!element.disabled&&element.name){var value=element.getValue();if(value!=undefined){var pair={};pair[element.name]=value;return Object.toQueryString(pair)}}return""},getValue:function(element){element=$(element);var method=element.tagName.toLowerCase();return Form.Element.Serializers[method](element)},setValue:function(element,value){element=$(element);var method=element.tagName.toLowerCase();Form.Element.Serializers[method](element,
value);return element},clear:function(element){$(element).value="";return element},present:function(element){return $(element).value!=""},activate:function(element){element=$(element);try{element.focus();if(element.select&&(element.tagName.toLowerCase()!="input"||!/^(?:button|reset|submit)$/i.test(element.type)))element.select()}catch(e){}return element},disable:function(element){element=$(element);element.disabled=true;return element},enable:function(element){element=$(element);element.disabled=
false;return element}};var Field=Form.Element;var $F=Form.Element.Methods.getValue;
Form.Element.Serializers=function(){function input(element,value){switch(element.type.toLowerCase()){case "checkbox":case "radio":return inputSelector(element,value);default:return valueSelector(element,value)}}function inputSelector(element,value){if(Object.isUndefined(value))return element.checked?element.value:null;else element.checked=!!value}function valueSelector(element,value){if(Object.isUndefined(value))return element.value;else element.value=value}function select(element,value){if(Object.isUndefined(value))return(element.type===
"select-one"?selectOne:selectMany)(element);var opt,currentValue,single=!Object.isArray(value);for(var i=0,length=element.length;i<length;i++){opt=element.options[i];currentValue=this.optionValue(opt);if(single){if(currentValue==value){opt.selected=true;return}}else opt.selected=value.include(currentValue)}}function selectOne(element){var index=element.selectedIndex;return index>=0?optionValue(element.options[index]):null}function selectMany(element){var values,length=element.length;if(!length)return null;
for(var i=0,values=[];i<length;i++){var opt=element.options[i];if(opt.selected)values.push(optionValue(opt))}return values}function optionValue(opt){return Element.hasAttribute(opt,"value")?opt.value:opt.text}return{input:input,inputSelector:inputSelector,textarea:valueSelector,select:select,selectOne:selectOne,selectMany:selectMany,optionValue:optionValue,button:valueSelector}}();
Abstract.TimedObserver=Class.create(PeriodicalExecuter,{initialize:function($super,element,frequency,callback){$super(callback,frequency);this.element=$(element);this.lastValue=this.getValue()},execute:function(){var value=this.getValue();if(Object.isString(this.lastValue)&&Object.isString(value)?this.lastValue!=value:String(this.lastValue)!=String(value)){this.callback(this.element,value);this.lastValue=value}}});Form.Element.Observer=Class.create(Abstract.TimedObserver,{getValue:function(){return Form.Element.getValue(this.element)}});
Form.Observer=Class.create(Abstract.TimedObserver,{getValue:function(){return Form.serialize(this.element)}});
Abstract.EventObserver=Class.create({initialize:function(element,callback){this.element=$(element);this.callback=callback;this.lastValue=this.getValue();if(this.element.tagName.toLowerCase()=="form")this.registerFormCallbacks();else this.registerCallback(this.element)},onElementEvent:function(){var value=this.getValue();if(this.lastValue!=value){this.callback(this.element,value);this.lastValue=value}},registerFormCallbacks:function(){Form.getElements(this.element).each(this.registerCallback,this)},
registerCallback:function(element){if(element.type)switch(element.type.toLowerCase()){case "checkbox":case "radio":Event.observe(element,"click",this.onElementEvent.bind(this));break;default:Event.observe(element,"change",this.onElementEvent.bind(this));break}}});Form.Element.EventObserver=Class.create(Abstract.EventObserver,{getValue:function(){return Form.Element.getValue(this.element)}});Form.EventObserver=Class.create(Abstract.EventObserver,{getValue:function(){return Form.serialize(this.element)}});
(function(){var Event={KEY_BACKSPACE:8,KEY_TAB:9,KEY_RETURN:13,KEY_ESC:27,KEY_LEFT:37,KEY_UP:38,KEY_RIGHT:39,KEY_DOWN:40,KEY_DELETE:46,KEY_HOME:36,KEY_END:35,KEY_PAGEUP:33,KEY_PAGEDOWN:34,KEY_INSERT:45,cache:{}};var docEl=document.documentElement;var MOUSEENTER_MOUSELEAVE_EVENTS_SUPPORTED="onmouseenter"in docEl&&"onmouseleave"in docEl;var isIELegacyEvent=function(event){return false};if(window.attachEvent)if(window.addEventListener)isIELegacyEvent=function(event){return!(event instanceof window.Event)};
else isIELegacyEvent=function(event){return true};var _isButton;function _isButtonForDOMEvents(event,code){return event.which?event.which===code+1:event.button===code}var legacyButtonMap={0:1,1:4,2:2};function _isButtonForLegacyEvents(event,code){return event.button===legacyButtonMap[code]}function _isButtonForWebKit(event,code){switch(code){case 0:return event.which==1&&!event.metaKey;case 1:return event.which==2||event.which==1&&event.metaKey;case 2:return event.which==3;default:return false}}if(window.attachEvent)if(!window.addEventListener)_isButton=
_isButtonForLegacyEvents;else _isButton=function(event,code){return isIELegacyEvent(event)?_isButtonForLegacyEvents(event,code):_isButtonForDOMEvents(event,code)};else if(Prototype.Browser.WebKit)_isButton=_isButtonForWebKit;else _isButton=_isButtonForDOMEvents;function isLeftClick(event){return _isButton(event,0)}function isMiddleClick(event){return _isButton(event,1)}function isRightClick(event){return _isButton(event,2)}function element(event){event=Event.extend(event);var node=event.target,type=
event.type,currentTarget=event.currentTarget;if(currentTarget&&currentTarget.tagName)if(type==="load"||type==="error"||type==="click"&&currentTarget.tagName.toLowerCase()==="input"&&currentTarget.type==="radio")node=currentTarget;if(node.nodeType==Node.TEXT_NODE)node=node.parentNode;return Element.extend(node)}function findElement(event,expression){var element=Event.element(event);if(!expression)return element;while(element){if(Object.isElement(element)&&Prototype.Selector.match(element,expression))return Element.extend(element);
element=element.parentNode}}function pointer(event){return{x:pointerX(event),y:pointerY(event)}}function pointerX(event){var docElement=document.documentElement,body=document.body||{scrollLeft:0};return event.pageX||event.clientX+(docElement.scrollLeft||body.scrollLeft)-(docElement.clientLeft||0)}function pointerY(event){var docElement=document.documentElement,body=document.body||{scrollTop:0};return event.pageY||event.clientY+(docElement.scrollTop||body.scrollTop)-(docElement.clientTop||0)}function stop(event){Event.extend(event);
event.preventDefault();event.stopPropagation();event.stopped=true}Event.Methods={isLeftClick:isLeftClick,isMiddleClick:isMiddleClick,isRightClick:isRightClick,element:element,findElement:findElement,pointer:pointer,pointerX:pointerX,pointerY:pointerY,stop:stop};var methods=Object.keys(Event.Methods).inject({},function(m,name){m[name]=Event.Methods[name].methodize();return m});if(window.attachEvent){function _relatedTarget(event){var element;switch(event.type){case "mouseover":case "mouseenter":element=
event.fromElement;break;case "mouseout":case "mouseleave":element=event.toElement;break;default:return null}return Element.extend(element)}var additionalMethods={stopPropagation:function(){this.cancelBubble=true},preventDefault:function(){this.returnValue=false},inspect:function(){return"[object Event]"}};Event.extend=function(event,element){if(!event)return false;if(!isIELegacyEvent(event))return event;if(event._extendedByPrototype)return event;event._extendedByPrototype=Prototype.emptyFunction;
var pointer=Event.pointer(event);Object.extend(event,{target:event.srcElement||element,relatedTarget:_relatedTarget(event),pageX:pointer.x,pageY:pointer.y});Object.extend(event,methods);Object.extend(event,additionalMethods);return event}}else Event.extend=Prototype.K;if(window.addEventListener){Event.prototype=window.Event.prototype||document.createEvent("HTMLEvents").__proto__;Object.extend(Event.prototype,methods)}function _createResponder(element,eventName,handler){var registry=Element.retrieve(element,
"prototype_event_registry");if(Object.isUndefined(registry)){CACHE.push(element);registry=Element.retrieve(element,"prototype_event_registry",$H())}var respondersForEvent=registry.get(eventName);if(Object.isUndefined(respondersForEvent)){respondersForEvent=[];registry.set(eventName,respondersForEvent)}if(respondersForEvent.pluck("handler").include(handler))return false;var responder;if(eventName.include(":"))responder=function(event){if(Object.isUndefined(event.eventName))return false;if(event.eventName!==
eventName)return false;Event.extend(event,element);handler.call(element,event)};else if(!MOUSEENTER_MOUSELEAVE_EVENTS_SUPPORTED&&(eventName==="mouseenter"||eventName==="mouseleave")){if(eventName==="mouseenter"||eventName==="mouseleave")responder=function(event){Event.extend(event,element);var parent=event.relatedTarget;while(parent&&parent!==element)try{parent=parent.parentNode}catch(e){parent=element}if(parent===element)return;handler.call(element,event)}}else responder=function(event){Event.extend(event,
element);handler.call(element,event)};responder.handler=handler;respondersForEvent.push(responder);return responder}function _destroyCache(){for(var i=0,length=CACHE.length;i<length;i++){Event.stopObserving(CACHE[i]);CACHE[i]=null}}var CACHE=[];if(Prototype.Browser.IE)window.attachEvent("onunload",_destroyCache);if(Prototype.Browser.WebKit)window.addEventListener("unload",Prototype.emptyFunction,false);var _getDOMEventName=Prototype.K,translations={mouseenter:"mouseover",mouseleave:"mouseout"};if(!MOUSEENTER_MOUSELEAVE_EVENTS_SUPPORTED)_getDOMEventName=
function(eventName){return translations[eventName]||eventName};function observe(element,eventName,handler){element=$(element);var responder=_createResponder(element,eventName,handler);if(!responder)return element;if(eventName.include(":"))if(element.addEventListener)element.addEventListener("dataavailable",responder,false);else{element.attachEvent("ondataavailable",responder);element.attachEvent("onlosecapture",responder)}else{var actualEventName=_getDOMEventName(eventName);if(element.addEventListener)element.addEventListener(actualEventName,
responder,false);else element.attachEvent("on"+actualEventName,responder)}return element}function stopObserving(element,eventName,handler){element=$(element);var registry=Element.retrieve(element,"prototype_event_registry");if(!registry)return element;if(!eventName){registry.each(function(pair){var eventName=pair.key;stopObserving(element,eventName)});return element}var responders=registry.get(eventName);if(!responders)return element;if(!handler){responders.each(function(r){stopObserving(element,
eventName,r.handler)});return element}var i=responders.length,responder;while(i--)if(responders[i].handler===handler){responder=responders[i];break}if(!responder)return element;if(eventName.include(":"))if(element.removeEventListener)element.removeEventListener("dataavailable",responder,false);else{element.detachEvent("ondataavailable",responder);element.detachEvent("onlosecapture",responder)}else{var actualEventName=_getDOMEventName(eventName);if(element.removeEventListener)element.removeEventListener(actualEventName,
responder,false);else element.detachEvent("on"+actualEventName,responder)}registry.set(eventName,responders.without(responder));return element}function fire(element,eventName,memo,bubble){element=$(element);if(Object.isUndefined(bubble))bubble=true;if(element==document&&document.createEvent&&!element.dispatchEvent)element=document.documentElement;var event;if(document.createEvent){event=document.createEvent("HTMLEvents");event.initEvent("dataavailable",bubble,true)}else{event=document.createEventObject();
event.eventType=bubble?"ondataavailable":"onlosecapture"}event.eventName=eventName;event.memo=memo||{};if(document.createEvent)element.dispatchEvent(event);else element.fireEvent(event.eventType,event);return Event.extend(event)}Event.Handler=Class.create({initialize:function(element,eventName,selector,callback){this.element=$(element);this.eventName=eventName;this.selector=selector;this.callback=callback;this.handler=this.handleEvent.bind(this)},start:function(){Event.observe(this.element,this.eventName,
this.handler);return this},stop:function(){Event.stopObserving(this.element,this.eventName,this.handler);return this},handleEvent:function(event){var element=Event.findElement(event,this.selector);if(element)this.callback.call(this.element,event,element)}});function on(element,eventName,selector,callback){element=$(element);if(Object.isFunction(selector)&&Object.isUndefined(callback))callback=selector,selector=null;return(new Event.Handler(element,eventName,selector,callback)).start()}Object.extend(Event,
Event.Methods);Object.extend(Event,{fire:fire,observe:observe,stopObserving:stopObserving,on:on});Element.addMethods({fire:fire,observe:observe,stopObserving:stopObserving,on:on});Object.extend(document,{fire:fire.methodize(),observe:observe.methodize(),stopObserving:stopObserving.methodize(),on:on.methodize(),loaded:false});if(window.Event)Object.extend(window.Event,Event);else window.Event=Event})();
(function(){var timer;function fireContentLoadedEvent(){if(document.loaded)return;if(timer)window.clearTimeout(timer);document.loaded=true;document.fire("dom:loaded")}function checkReadyState(){if(document.readyState==="complete"){document.stopObserving("readystatechange",checkReadyState);fireContentLoadedEvent()}}function pollDoScroll(){try{document.documentElement.doScroll("left")}catch(e){timer=pollDoScroll.defer();return}fireContentLoadedEvent()}if(document.addEventListener)document.addEventListener("DOMContentLoaded",
fireContentLoadedEvent,false);else{document.observe("readystatechange",checkReadyState);if(window==top)timer=pollDoScroll.defer()}Event.observe(window,"load",fireContentLoadedEvent)})();Element.addMethods();Hash.toQueryString=Object.toQueryString;var Toggle={display:Element.toggle};Element.Methods.childOf=Element.Methods.descendantOf;
var Insertion={Before:function(element,content){return Element.insert(element,{before:content})},Top:function(element,content){return Element.insert(element,{top:content})},Bottom:function(element,content){return Element.insert(element,{bottom:content})},After:function(element,content){return Element.insert(element,{after:content})}};var $continue=new Error('"throw $continue" is deprecated, use "return" instead');
var Position={includeScrollOffsets:false,prepare:function(){this.deltaX=window.pageXOffset||document.documentElement.scrollLeft||document.body.scrollLeft||0;this.deltaY=window.pageYOffset||document.documentElement.scrollTop||document.body.scrollTop||0},within:function(element,x,y){if(this.includeScrollOffsets)return this.withinIncludingScrolloffsets(element,x,y);this.xcomp=x;this.ycomp=y;this.offset=Element.cumulativeOffset(element);return y>=this.offset[1]&&y<this.offset[1]+element.offsetHeight&&
x>=this.offset[0]&&x<this.offset[0]+element.offsetWidth},withinIncludingScrolloffsets:function(element,x,y){var offsetcache=Element.cumulativeScrollOffset(element);this.xcomp=x+offsetcache[0]-this.deltaX;this.ycomp=y+offsetcache[1]-this.deltaY;this.offset=Element.cumulativeOffset(element);return this.ycomp>=this.offset[1]&&this.ycomp<this.offset[1]+element.offsetHeight&&this.xcomp>=this.offset[0]&&this.xcomp<this.offset[0]+element.offsetWidth},overlap:function(mode,element){if(!mode)return 0;if(mode==
"vertical")return(this.offset[1]+element.offsetHeight-this.ycomp)/element.offsetHeight;if(mode=="horizontal")return(this.offset[0]+element.offsetWidth-this.xcomp)/element.offsetWidth},cumulativeOffset:Element.Methods.cumulativeOffset,positionedOffset:Element.Methods.positionedOffset,absolutize:function(element){Position.prepare();return Element.absolutize(element)},relativize:function(element){Position.prepare();return Element.relativize(element)},realOffset:Element.Methods.cumulativeScrollOffset,
offsetParent:Element.Methods.getOffsetParent,page:Element.Methods.viewportOffset,clone:function(source,target,options){options=options||{};return Element.clonePosition(target,source,options)}};
if(!document.getElementsByClassName)document.getElementsByClassName=function(instanceMethods){function iter(name){return name.blank()?null:"[contains(concat(' ', @class, ' '), ' "+name+" ')]"}instanceMethods.getElementsByClassName=Prototype.BrowserFeatures.XPath?function(element,className){className=className.toString().strip();var cond=/\s/.test(className)?$w(className).map(iter).join(""):iter(className);return cond?document._getElementsByXPath(".//*"+cond,element):[]}:function(element,className){className=
className.toString().strip();var elements=[],classNames=/\s/.test(className)?$w(className):null;if(!classNames&&!className)return elements;var nodes=$(element).getElementsByTagName("*");className=" "+className+" ";for(var i=0,child,cn;child=nodes[i];i++)if(child.className&&(cn=" "+child.className+" ")&&(cn.include(className)||classNames&&classNames.all(function(name){return!name.toString().blank()&&cn.include(" "+name+" ")})))elements.push(Element.extend(child));return elements};return function(className,
parentElement){return $(parentElement||document.body).getElementsByClassName(className)}}(Element.Methods);Element.ClassNames=Class.create();
Element.ClassNames.prototype={initialize:function(element){this.element=$(element)},_each:function(iterator){this.element.className.split(/\s+/).select(function(name){return name.length>0})._each(iterator)},set:function(className){this.element.className=className},add:function(classNameToAdd){if(this.include(classNameToAdd))return;this.set($A(this).concat(classNameToAdd).join(" "))},remove:function(classNameToRemove){if(!this.include(classNameToRemove))return;this.set($A(this).without(classNameToRemove).join(" "))},
toString:function(){return $A(this).join(" ")}};Object.extend(Element.ClassNames.prototype,Enumerable);
(function(){window.Selector=Class.create({initialize:function(expression){this.expression=expression.strip()},findElements:function(rootElement){return Prototype.Selector.select(this.expression,rootElement)},match:function(element){return Prototype.Selector.match(element,this.expression)},toString:function(){return this.expression},inspect:function(){return"#<Selector: "+this.expression+">"}});Object.extend(Selector,{matchElements:function(elements,expression){var match=Prototype.Selector.match,results=
[];for(var i=0,length=elements.length;i<length;i++){var element=elements[i];if(match(element,expression))results.push(Element.extend(element))}return results},findElement:function(elements,expression,index){index=index||0;var matchIndex=0,element;for(var i=0,length=elements.length;i<length;i++){element=elements[i];if(Prototype.Selector.match(element,expression)&&index===matchIndex++)return Element.extend(element)}},findChildElements:function(element,expressions){var selector=expressions.toArray().join(", ");
return Prototype.Selector.select(selector,element||document)}})})();
BrainstormJs.Controls.QuickSearchBox=Class.create({container:false,input:false,button:false,initialize:function(container){this.container=$(container);this.input=this.container.down("input.searchBox");this.button=this.container.down("input.searchButton");this.input.observe("focus",function(e){this.onFocus()}.bind(this));this.input.observe("blur",function(e){this.onBlur()}.bind(this));this.input.observe("keypress",function(e){this.onKeyPress(e)}.bind(this));this.button.observe("click",function(e){this.onButtonClick(e)}.bind(this));
if(this.input.value.strip()=="")this.input.value="Quick Search";else if(!this.input.hasClassName("active")&&this.input.value.strip()!="Quick Search")this.input.addClassName("active")},onFocus:function(){if(this.input.value.strip()=="Quick Search"||this.input.value.strip()==""){this.input.value="";this.input.addClassName("active")}},onBlur:function(){if(this.input.value.strip()=="Quick Search"||this.input.value.strip()==""){this.input.value="Quick Search";this.input.removeClassName("active")}},onKeyPress:function(e){this.input.addClassName("active");
if(e.keyCode==Event.KEY_RETURN&&this.input.value.strip()!=""){e.stop();this.redirectToSearch()}},onButtonClick:function(e){e.stop();this.redirectToSearch()},redirectToSearch:function(){document.location="/Search.aspx?find="+this.escapeUrl(this.input.value.strip())},escapeUrl:function(str){return escape(str).replace(/[+]/g,"%2B")}});function initSearchBox(){if(typeof BrainstormJs.Controls.QuickSearchBox!="undefined"&&$("quickSearch"))new BrainstormJs.Controls.QuickSearchBox("quickSearch")}
function initDatePicker(){window.dhx_globalImgPath="/Images/Libraries/dhtmlxCalendar"}initSearchBox();initDatePicker();
CookieJar=Class.create({appendString:"__CJ_",initialize:function(options){this.options={expires:3600,path:"",domain:"",secure:""};Object.extend(this.options,options||{});if(this.options.expires!=""){var date=new Date;date=new Date(date.getTime()+this.options.expires*1E3);this.options.expires="; expires="+date.toGMTString()}if(this.options.path!="")this.options.path="; path="+escape(this.options.path);if(this.options.domain!="")this.options.domain="; domain="+escape(this.options.domain);if(this.options.secure==
"secure")this.options.secure="; secure";else this.options.secure=""},put:function(name,value){name=this.appendString+name;cookie=this.options;var type=typeof value;switch(type){case "undefined":case "function":case "unknown":return false;case "boolean":case "string":case "number":value=String(value.toString())}var cookie_str=name+"="+escape(Object.toJSON(value));try{document.cookie=cookie_str+cookie.expires+cookie.path+cookie.domain+cookie.secure}catch(e){return false}return true},remove:function(name){name=
this.appendString+name;cookie=this.options;try{var date=new Date;date.setTime(date.getTime()-3600*1E3);var expires="; expires="+date.toGMTString();document.cookie=name+"="+expires+cookie.path+cookie.domain+cookie.secure}catch(e){return false}return true},get:function(name){name=this.appendString+name;var cookies=document.cookie.match(name+"=(.*?)(;|$)");if(cookies)return unescape(cookies[1]).evalJSON();else return null},empty:function(){keys=this.getKeys();size=keys.size();for(i=0;i<size;i++)this.remove(keys[i])},
getPack:function(){pack={};keys=this.getKeys();size=keys.size();for(i=0;i<size;i++)pack[keys[i]]=this.get(keys[i]);return pack},getKeys:function(){keys=$A();keyRe=/[^=; ]+(?=\=)/g;str=document.cookie;CJRe=new RegExp("^"+this.appendString);while((match=keyRe.exec(str))!=undefined)if(CJRe.test(match[0].strip()))keys.push(match[0].strip().gsub("^"+this.appendString,""));return keys}});
var Scriptaculous={Version:"1.9.0",require:function(libraryName){try{document.write('<script type="text/javascript" src="'+libraryName+'"><\/script>')}catch(e){var script=document.createElement("script");script.type="text/javascript";script.src=libraryName;document.getElementsByTagName("head")[0].appendChild(script)}},REQUIRED_PROTOTYPE:"1.6.0.3",load:function(){function convertVersionString(versionString){var v=versionString.replace(/_.*|\./g,"");v=parseInt(v+"0".times(4-v.length));return versionString.indexOf("_")>
-1?v-1:v}if(typeof Prototype=="undefined"||typeof Element=="undefined"||typeof Element.Methods=="undefined"||convertVersionString(Prototype.Version)<convertVersionString(Scriptaculous.REQUIRED_PROTOTYPE))throw"script.aculo.us requires the Prototype JavaScript framework >= "+Scriptaculous.REQUIRED_PROTOTYPE;var js=/scriptaculous\.js(\?.*)?$/;$$("script[src]").findAll(function(s){return s.src.match(js)}).each(function(s){var path=s.src.replace(js,""),includes=s.src.match(/\?.*load=([a-z,]*)/);(includes?
includes[1]:"effects,dragdrop,controls,slider").split(",").each(function(include){Scriptaculous.require(path+include+".js")})})}};Scriptaculous.load();
String.prototype.parseColor=function(){var color="#";if(this.slice(0,4)=="rgb("){var cols=this.slice(4,this.length-1).split(",");var i=0;do color+=parseInt(cols[i]).toColorPart();while(++i<3)}else if(this.slice(0,1)=="#"){if(this.length==4)for(var i=1;i<4;i++)color+=(this.charAt(i)+this.charAt(i)).toLowerCase();if(this.length==7)color=this.toLowerCase()}return color.length==7?color:arguments[0]||this};
Element.collectTextNodes=function(element){return $A($(element).childNodes).collect(function(node){return node.nodeType==3?node.nodeValue:node.hasChildNodes()?Element.collectTextNodes(node):""}).flatten().join("")};Element.collectTextNodesIgnoreClass=function(element,className){return $A($(element).childNodes).collect(function(node){return node.nodeType==3?node.nodeValue:node.hasChildNodes()&&!Element.hasClassName(node,className)?Element.collectTextNodesIgnoreClass(node,className):""}).flatten().join("")};
Element.setContentZoom=function(element,percent){element=$(element);element.setStyle({fontSize:percent/100+"em"});if(Prototype.Browser.WebKit)window.scrollBy(0,0);return element};Element.getInlineOpacity=function(element){return $(element).style.opacity||""};Element.forceRerendering=function(element){try{element=$(element);var n=document.createTextNode(" ");element.appendChild(n);element.removeChild(n)}catch(e){}};
var Effect={_elementDoesNotExistError:{name:"ElementDoesNotExistError",message:"The specified DOM element does not exist, but is required for this effect to operate"},Transitions:{linear:Prototype.K,sinoidal:function(pos){return-Math.cos(pos*Math.PI)/2+0.5},reverse:function(pos){return 1-pos},flicker:function(pos){var pos=-Math.cos(pos*Math.PI)/4+0.75+Math.random()/4;return pos>1?1:pos},wobble:function(pos){return-Math.cos(pos*Math.PI*9*pos)/2+0.5},pulse:function(pos,pulses){return-Math.cos(pos*((pulses||
5)-0.5)*2*Math.PI)/2+0.5},spring:function(pos){return 1-Math.cos(pos*4.5*Math.PI)*Math.exp(-pos*6)},none:function(pos){return 0},full:function(pos){return 1}},DefaultOptions:{duration:1,fps:100,sync:false,from:0,to:1,delay:0,queue:"parallel"},tagifyText:function(element){var tagifyStyle="position:relative";if(Prototype.Browser.IE)tagifyStyle+=";zoom:1";element=$(element);$A(element.childNodes).each(function(child){if(child.nodeType==3){child.nodeValue.toArray().each(function(character){element.insertBefore((new Element("span",
{style:tagifyStyle})).update(character==" "?String.fromCharCode(160):character),child)});Element.remove(child)}})},multiple:function(element,effect){var elements;if((typeof element=="object"||Object.isFunction(element))&&element.length)elements=element;else elements=$(element).childNodes;var options=Object.extend({speed:0.1,delay:0},arguments[2]||{});var masterDelay=options.delay;$A(elements).each(function(element,index){new effect(element,Object.extend(options,{delay:index*options.speed+masterDelay}))})},
PAIRS:{"slide":["SlideDown","SlideUp"],"blind":["BlindDown","BlindUp"],"appear":["Appear","Fade"]},toggle:function(element,effect,options){element=$(element);effect=(effect||"appear").toLowerCase();return Effect[Effect.PAIRS[effect][element.visible()?1:0]](element,Object.extend({queue:{position:"end",scope:element.id||"global",limit:1}},options||{}))}};Effect.DefaultOptions.transition=Effect.Transitions.sinoidal;
Effect.ScopedQueue=Class.create(Enumerable,{initialize:function(){this.effects=[];this.interval=null},_each:function(iterator){this.effects._each(iterator)},add:function(effect){var timestamp=(new Date).getTime();var position=Object.isString(effect.options.queue)?effect.options.queue:effect.options.queue.position;switch(position){case "front":this.effects.findAll(function(e){return e.state=="idle"}).each(function(e){e.startOn+=effect.finishOn;e.finishOn+=effect.finishOn});break;case "with-last":timestamp=
this.effects.pluck("startOn").max()||timestamp;break;case "end":timestamp=this.effects.pluck("finishOn").max()||timestamp;break}effect.startOn+=timestamp;effect.finishOn+=timestamp;if(!effect.options.queue.limit||this.effects.length<effect.options.queue.limit)this.effects.push(effect);if(!this.interval)this.interval=setInterval(this.loop.bind(this),15)},remove:function(effect){this.effects=this.effects.reject(function(e){return e==effect});if(this.effects.length==0){clearInterval(this.interval);this.interval=
null}},loop:function(){var timePos=(new Date).getTime();for(var i=0,len=this.effects.length;i<len;i++)this.effects[i]&&this.effects[i].loop(timePos)}});Effect.Queues={instances:$H(),get:function(queueName){if(!Object.isString(queueName))return queueName;return this.instances.get(queueName)||this.instances.set(queueName,new Effect.ScopedQueue)}};Effect.Queue=Effect.Queues.get("global");
Effect.Base=Class.create({position:null,start:function(options){if(options&&options.transition===false)options.transition=Effect.Transitions.linear;this.options=Object.extend(Object.extend({},Effect.DefaultOptions),options||{});this.currentFrame=0;this.state="idle";this.startOn=this.options.delay*1E3;this.finishOn=this.startOn+this.options.duration*1E3;this.fromToDelta=this.options.to-this.options.from;this.totalTime=this.finishOn-this.startOn;this.totalFrames=this.options.fps*this.options.duration;
this.render=function(){function dispatch(effect,eventName){if(effect.options[eventName+"Internal"])effect.options[eventName+"Internal"](effect);if(effect.options[eventName])effect.options[eventName](effect)}return function(pos){if(this.state==="idle"){this.state="running";dispatch(this,"beforeSetup");if(this.setup)this.setup();dispatch(this,"afterSetup")}if(this.state==="running"){pos=this.options.transition(pos)*this.fromToDelta+this.options.from;this.position=pos;dispatch(this,"beforeUpdate");if(this.update)this.update(pos);
dispatch(this,"afterUpdate")}}}();this.event("beforeStart");if(!this.options.sync)Effect.Queues.get(Object.isString(this.options.queue)?"global":this.options.queue.scope).add(this)},loop:function(timePos){if(timePos>=this.startOn){if(timePos>=this.finishOn){this.render(1);this.cancel();this.event("beforeFinish");if(this.finish)this.finish();this.event("afterFinish");return}var pos=(timePos-this.startOn)/this.totalTime,frame=(pos*this.totalFrames).round();if(frame>this.currentFrame){this.render(pos);
this.currentFrame=frame}}},cancel:function(){if(!this.options.sync)Effect.Queues.get(Object.isString(this.options.queue)?"global":this.options.queue.scope).remove(this);this.state="finished"},event:function(eventName){if(this.options[eventName+"Internal"])this.options[eventName+"Internal"](this);if(this.options[eventName])this.options[eventName](this)},inspect:function(){var data=$H();for(property in this)if(!Object.isFunction(this[property]))data.set(property,this[property]);return"#<Effect:"+data.inspect()+
",options:"+$H(this.options).inspect()+">"}});Effect.Parallel=Class.create(Effect.Base,{initialize:function(effects){this.effects=effects||[];this.start(arguments[1])},update:function(position){this.effects.invoke("render",position)},finish:function(position){this.effects.each(function(effect){effect.render(1);effect.cancel();effect.event("beforeFinish");if(effect.finish)effect.finish(position);effect.event("afterFinish")})}});
Effect.Tween=Class.create(Effect.Base,{initialize:function(object,from,to){object=Object.isString(object)?$(object):object;var args=$A(arguments),method=args.last(),options=args.length==5?args[3]:null;this.method=Object.isFunction(method)?method.bind(object):Object.isFunction(object[method])?object[method].bind(object):function(value){object[method]=value};this.start(Object.extend({from:from,to:to},options||{}))},update:function(position){this.method(position)}});
Effect.Event=Class.create(Effect.Base,{initialize:function(){this.start(Object.extend({duration:0},arguments[0]||{}))},update:Prototype.emptyFunction});
Effect.Opacity=Class.create(Effect.Base,{initialize:function(element){this.element=$(element);if(!this.element)throw Effect._elementDoesNotExistError;if(Prototype.Browser.IE&&!this.element.currentStyle.hasLayout)this.element.setStyle({zoom:1});var options=Object.extend({from:this.element.getOpacity()||0,to:1},arguments[1]||{});this.start(options)},update:function(position){this.element.setOpacity(position)}});
Effect.Move=Class.create(Effect.Base,{initialize:function(element){this.element=$(element);if(!this.element)throw Effect._elementDoesNotExistError;var options=Object.extend({x:0,y:0,mode:"relative"},arguments[1]||{});this.start(options)},setup:function(){this.element.makePositioned();this.originalLeft=parseFloat(this.element.getStyle("left")||"0");this.originalTop=parseFloat(this.element.getStyle("top")||"0");if(this.options.mode=="absolute"){this.options.x=this.options.x-this.originalLeft;this.options.y=
this.options.y-this.originalTop}},update:function(position){this.element.setStyle({left:(this.options.x*position+this.originalLeft).round()+"px",top:(this.options.y*position+this.originalTop).round()+"px"})}});Effect.MoveBy=function(element,toTop,toLeft){return new Effect.Move(element,Object.extend({x:toLeft,y:toTop},arguments[3]||{}))};
Effect.Scale=Class.create(Effect.Base,{initialize:function(element,percent){this.element=$(element);if(!this.element)throw Effect._elementDoesNotExistError;var options=Object.extend({scaleX:true,scaleY:true,scaleContent:true,scaleFromCenter:false,scaleMode:"box",scaleFrom:100,scaleTo:percent},arguments[2]||{});this.start(options)},setup:function(){this.restoreAfterFinish=this.options.restoreAfterFinish||false;this.elementPositioning=this.element.getStyle("position");this.originalStyle={};["top","left",
"width","height","fontSize"].each(function(k){this.originalStyle[k]=this.element.style[k]}.bind(this));this.originalTop=this.element.offsetTop;this.originalLeft=this.element.offsetLeft;var fontSize=this.element.getStyle("font-size")||"100%";["em","px","%","pt"].each(function(fontSizeType){if(fontSize.indexOf(fontSizeType)>0){this.fontSize=parseFloat(fontSize);this.fontSizeType=fontSizeType}}.bind(this));this.factor=(this.options.scaleTo-this.options.scaleFrom)/100;this.dims=null;if(this.options.scaleMode==
"box")this.dims=[this.element.offsetHeight,this.element.offsetWidth];if(/^content/.test(this.options.scaleMode))this.dims=[this.element.scrollHeight,this.element.scrollWidth];if(!this.dims)this.dims=[this.options.scaleMode.originalHeight,this.options.scaleMode.originalWidth]},update:function(position){var currentScale=this.options.scaleFrom/100+this.factor*position;if(this.options.scaleContent&&this.fontSize)this.element.setStyle({fontSize:this.fontSize*currentScale+this.fontSizeType});this.setDimensions(this.dims[0]*
currentScale,this.dims[1]*currentScale)},finish:function(position){if(this.restoreAfterFinish)this.element.setStyle(this.originalStyle)},setDimensions:function(height,width){var d={};if(this.options.scaleX)d.width=width.round()+"px";if(this.options.scaleY)d.height=height.round()+"px";if(this.options.scaleFromCenter){var topd=(height-this.dims[0])/2;var leftd=(width-this.dims[1])/2;if(this.elementPositioning=="absolute"){if(this.options.scaleY)d.top=this.originalTop-topd+"px";if(this.options.scaleX)d.left=
this.originalLeft-leftd+"px"}else{if(this.options.scaleY)d.top=-topd+"px";if(this.options.scaleX)d.left=-leftd+"px"}}this.element.setStyle(d)}});
Effect.Highlight=Class.create(Effect.Base,{initialize:function(element){this.element=$(element);if(!this.element)throw Effect._elementDoesNotExistError;var options=Object.extend({startcolor:"#ffff99"},arguments[1]||{});this.start(options)},setup:function(){if(this.element.getStyle("display")=="none"){this.cancel();return}this.oldStyle={};if(!this.options.keepBackgroundImage){this.oldStyle.backgroundImage=this.element.getStyle("background-image");this.element.setStyle({backgroundImage:"none"})}if(!this.options.endcolor)this.options.endcolor=
this.element.getStyle("background-color").parseColor("#ffffff");if(!this.options.restorecolor)this.options.restorecolor=this.element.getStyle("background-color");this._base=$R(0,2).map(function(i){return parseInt(this.options.startcolor.slice(i*2+1,i*2+3),16)}.bind(this));this._delta=$R(0,2).map(function(i){return parseInt(this.options.endcolor.slice(i*2+1,i*2+3),16)-this._base[i]}.bind(this))},update:function(position){this.element.setStyle({backgroundColor:$R(0,2).inject("#",function(m,v,i){return m+
(this._base[i]+this._delta[i]*position).round().toColorPart()}.bind(this))})},finish:function(){this.element.setStyle(Object.extend(this.oldStyle,{backgroundColor:this.options.restorecolor}))}});
Effect.ScrollTo=function(element){var options=arguments[1]||{},scrollOffsets=document.viewport.getScrollOffsets(),elementOffsets=$(element).cumulativeOffset();if(options.offset)elementOffsets[1]+=options.offset;return new Effect.Tween(null,scrollOffsets.top,elementOffsets[1],options,function(p){scrollTo(scrollOffsets.left,p.round())})};
Effect.Fade=function(element){element=$(element);var oldOpacity=element.getInlineOpacity();var options=Object.extend({from:element.getOpacity()||1,to:0,afterFinishInternal:function(effect){if(effect.options.to!=0)return;effect.element.hide().setStyle({opacity:oldOpacity})}},arguments[1]||{});return new Effect.Opacity(element,options)};
Effect.Appear=function(element){element=$(element);var options=Object.extend({from:element.getStyle("display")=="none"?0:element.getOpacity()||0,to:1,afterFinishInternal:function(effect){effect.element.forceRerendering()},beforeSetup:function(effect){effect.element.setOpacity(effect.options.from).show()}},arguments[1]||{});return new Effect.Opacity(element,options)};
Effect.Puff=function(element){element=$(element);var oldStyle={opacity:element.getInlineOpacity(),position:element.getStyle("position"),top:element.style.top,left:element.style.left,width:element.style.width,height:element.style.height};return new Effect.Parallel([new Effect.Scale(element,200,{sync:true,scaleFromCenter:true,scaleContent:true,restoreAfterFinish:true}),new Effect.Opacity(element,{sync:true,to:0})],Object.extend({duration:1,beforeSetupInternal:function(effect){Position.absolutize(effect.effects[0].element)},
afterFinishInternal:function(effect){effect.effects[0].element.hide().setStyle(oldStyle)}},arguments[1]||{}))};Effect.BlindUp=function(element){element=$(element);element.makeClipping();return new Effect.Scale(element,0,Object.extend({scaleContent:false,scaleX:false,restoreAfterFinish:true,afterFinishInternal:function(effect){effect.element.hide().undoClipping()}},arguments[1]||{}))};
Effect.BlindDown=function(element){element=$(element);var elementDimensions=element.getDimensions();return new Effect.Scale(element,100,Object.extend({scaleContent:false,scaleX:false,scaleFrom:0,scaleMode:{originalHeight:elementDimensions.height,originalWidth:elementDimensions.width},restoreAfterFinish:true,afterSetup:function(effect){effect.element.makeClipping().setStyle({height:"0px"}).show()},afterFinishInternal:function(effect){effect.element.undoClipping()}},arguments[1]||{}))};
Effect.SwitchOff=function(element){element=$(element);var oldOpacity=element.getInlineOpacity();return new Effect.Appear(element,Object.extend({duration:0.4,from:0,transition:Effect.Transitions.flicker,afterFinishInternal:function(effect){new Effect.Scale(effect.element,1,{duration:0.3,scaleFromCenter:true,scaleX:false,scaleContent:false,restoreAfterFinish:true,beforeSetup:function(effect){effect.element.makePositioned().makeClipping()},afterFinishInternal:function(effect){effect.element.hide().undoClipping().undoPositioned().setStyle({opacity:oldOpacity})}})}},
arguments[1]||{}))};
Effect.DropOut=function(element){element=$(element);var oldStyle={top:element.getStyle("top"),left:element.getStyle("left"),opacity:element.getInlineOpacity()};return new Effect.Parallel([new Effect.Move(element,{x:0,y:100,sync:true}),new Effect.Opacity(element,{sync:true,to:0})],Object.extend({duration:0.5,beforeSetup:function(effect){effect.effects[0].element.makePositioned()},afterFinishInternal:function(effect){effect.effects[0].element.hide().undoPositioned().setStyle(oldStyle)}},arguments[1]||
{}))};
Effect.Shake=function(element){element=$(element);var options=Object.extend({distance:20,duration:0.5},arguments[1]||{});var distance=parseFloat(options.distance);var split=parseFloat(options.duration)/10;var oldStyle={top:element.getStyle("top"),left:element.getStyle("left")};return new Effect.Move(element,{x:distance,y:0,duration:split,afterFinishInternal:function(effect){new Effect.Move(effect.element,{x:-distance*2,y:0,duration:split*2,afterFinishInternal:function(effect){new Effect.Move(effect.element,{x:distance*
2,y:0,duration:split*2,afterFinishInternal:function(effect){new Effect.Move(effect.element,{x:-distance*2,y:0,duration:split*2,afterFinishInternal:function(effect){new Effect.Move(effect.element,{x:distance*2,y:0,duration:split*2,afterFinishInternal:function(effect){new Effect.Move(effect.element,Object.extend({x:-distance,y:0,duration:split,afterFinishInternal:function(effect){effect.element.undoPositioned().setStyle(oldStyle)}},options))}})}})}})}})}})};
Effect.SlideDown=function(element){element=$(element).cleanWhitespace();var oldInnerBottom=element.down().getStyle("bottom");var elementDimensions=element.getDimensions();return new Effect.Scale(element,100,Object.extend({scaleContent:false,scaleX:false,scaleFrom:window.opera?0:1,scaleMode:{originalHeight:elementDimensions.height,originalWidth:elementDimensions.width},restoreAfterFinish:true,afterSetup:function(effect){effect.element.makePositioned();effect.element.down().makePositioned();if(window.opera)effect.element.setStyle({top:""});
effect.element.makeClipping().setStyle({height:"0px"}).show()},afterUpdateInternal:function(effect){effect.element.down().setStyle({bottom:effect.dims[0]-effect.element.clientHeight+"px"})},afterFinishInternal:function(effect){effect.element.undoClipping().undoPositioned();effect.element.down().undoPositioned().setStyle({bottom:oldInnerBottom})}},arguments[1]||{}))};
Effect.SlideUp=function(element){element=$(element).cleanWhitespace();var oldInnerBottom=element.down().getStyle("bottom");var elementDimensions=element.getDimensions();return new Effect.Scale(element,window.opera?0:1,Object.extend({scaleContent:false,scaleX:false,scaleMode:"box",scaleFrom:100,scaleMode:{originalHeight:elementDimensions.height,originalWidth:elementDimensions.width},restoreAfterFinish:true,afterSetup:function(effect){effect.element.makePositioned();effect.element.down().makePositioned();
if(window.opera)effect.element.setStyle({top:""});effect.element.makeClipping().show()},afterUpdateInternal:function(effect){effect.element.down().setStyle({bottom:effect.dims[0]-effect.element.clientHeight+"px"})},afterFinishInternal:function(effect){effect.element.hide().undoClipping().undoPositioned();effect.element.down().undoPositioned().setStyle({bottom:oldInnerBottom})}},arguments[1]||{}))};
Effect.Squish=function(element){return new Effect.Scale(element,window.opera?1:0,{restoreAfterFinish:true,beforeSetup:function(effect){effect.element.makeClipping()},afterFinishInternal:function(effect){effect.element.hide().undoClipping()}})};
Effect.Grow=function(element){element=$(element);var options=Object.extend({direction:"center",moveTransition:Effect.Transitions.sinoidal,scaleTransition:Effect.Transitions.sinoidal,opacityTransition:Effect.Transitions.full},arguments[1]||{});var oldStyle={top:element.style.top,left:element.style.left,height:element.style.height,width:element.style.width,opacity:element.getInlineOpacity()};var dims=element.getDimensions();var initialMoveX,initialMoveY;var moveX,moveY;switch(options.direction){case "top-left":initialMoveX=
initialMoveY=moveX=moveY=0;break;case "top-right":initialMoveX=dims.width;initialMoveY=moveY=0;moveX=-dims.width;break;case "bottom-left":initialMoveX=moveX=0;initialMoveY=dims.height;moveY=-dims.height;break;case "bottom-right":initialMoveX=dims.width;initialMoveY=dims.height;moveX=-dims.width;moveY=-dims.height;break;case "center":initialMoveX=dims.width/2;initialMoveY=dims.height/2;moveX=-dims.width/2;moveY=-dims.height/2;break}return new Effect.Move(element,{x:initialMoveX,y:initialMoveY,duration:0.01,
beforeSetup:function(effect){effect.element.hide().makeClipping().makePositioned()},afterFinishInternal:function(effect){new Effect.Parallel([new Effect.Opacity(effect.element,{sync:true,to:1,from:0,transition:options.opacityTransition}),new Effect.Move(effect.element,{x:moveX,y:moveY,sync:true,transition:options.moveTransition}),new Effect.Scale(effect.element,100,{scaleMode:{originalHeight:dims.height,originalWidth:dims.width},sync:true,scaleFrom:window.opera?1:0,transition:options.scaleTransition,
restoreAfterFinish:true})],Object.extend({beforeSetup:function(effect){effect.effects[0].element.setStyle({height:"0px"}).show()},afterFinishInternal:function(effect){effect.effects[0].element.undoClipping().undoPositioned().setStyle(oldStyle)}},options))}})};
Effect.Shrink=function(element){element=$(element);var options=Object.extend({direction:"center",moveTransition:Effect.Transitions.sinoidal,scaleTransition:Effect.Transitions.sinoidal,opacityTransition:Effect.Transitions.none},arguments[1]||{});var oldStyle={top:element.style.top,left:element.style.left,height:element.style.height,width:element.style.width,opacity:element.getInlineOpacity()};var dims=element.getDimensions();var moveX,moveY;switch(options.direction){case "top-left":moveX=moveY=0;break;
case "top-right":moveX=dims.width;moveY=0;break;case "bottom-left":moveX=0;moveY=dims.height;break;case "bottom-right":moveX=dims.width;moveY=dims.height;break;case "center":moveX=dims.width/2;moveY=dims.height/2;break}return new Effect.Parallel([new Effect.Opacity(element,{sync:true,to:0,from:1,transition:options.opacityTransition}),new Effect.Scale(element,window.opera?1:0,{sync:true,transition:options.scaleTransition,restoreAfterFinish:true}),new Effect.Move(element,{x:moveX,y:moveY,sync:true,
transition:options.moveTransition})],Object.extend({beforeStartInternal:function(effect){effect.effects[0].element.makePositioned().makeClipping()},afterFinishInternal:function(effect){effect.effects[0].element.hide().undoClipping().undoPositioned().setStyle(oldStyle)}},options))};
Effect.Pulsate=function(element){element=$(element);var options=arguments[1]||{},oldOpacity=element.getInlineOpacity(),transition=options.transition||Effect.Transitions.linear,reverser=function(pos){return 1-transition(-Math.cos(pos*(options.pulses||5)*2*Math.PI)/2+0.5)};return new Effect.Opacity(element,Object.extend(Object.extend({duration:2,from:0,afterFinishInternal:function(effect){effect.element.setStyle({opacity:oldOpacity})}},options),{transition:reverser}))};
Effect.Fold=function(element){element=$(element);var oldStyle={top:element.style.top,left:element.style.left,width:element.style.width,height:element.style.height};element.makeClipping();return new Effect.Scale(element,5,Object.extend({scaleContent:false,scaleX:false,afterFinishInternal:function(effect){new Effect.Scale(element,1,{scaleContent:false,scaleY:false,afterFinishInternal:function(effect){effect.element.hide().undoClipping().setStyle(oldStyle)}})}},arguments[1]||{}))};
Effect.Morph=Class.create(Effect.Base,{initialize:function(element){this.element=$(element);if(!this.element)throw Effect._elementDoesNotExistError;var options=Object.extend({style:{}},arguments[1]||{});if(!Object.isString(options.style))this.style=$H(options.style);else if(options.style.include(":"))this.style=options.style.parseStyle();else{this.element.addClassName(options.style);this.style=$H(this.element.getStyles());this.element.removeClassName(options.style);var css=this.element.getStyles();
this.style=this.style.reject(function(style){return style.value==css[style.key]});options.afterFinishInternal=function(effect){effect.element.addClassName(effect.options.style);effect.transforms.each(function(transform){effect.element.style[transform.style]=""})}}this.start(options)},setup:function(){function parseColor(color){if(!color||["rgba(0, 0, 0, 0)","transparent"].include(color))color="#ffffff";color=color.parseColor();return $R(0,2).map(function(i){return parseInt(color.slice(i*2+1,i*2+3),
16)})}this.transforms=this.style.map(function(pair){var property=pair[0],value=pair[1],unit=null;if(value.parseColor("#zzzzzz")!="#zzzzzz"){value=value.parseColor();unit="color"}else if(property=="opacity"){value=parseFloat(value);if(Prototype.Browser.IE&&!this.element.currentStyle.hasLayout)this.element.setStyle({zoom:1})}else if(Element.CSS_LENGTH.test(value)){var components=value.match(/^([\+\-]?[0-9\.]+)(.*)$/);value=parseFloat(components[1]);unit=components.length==3?components[2]:null}var originalValue=
this.element.getStyle(property);return{style:property.camelize(),originalValue:unit=="color"?parseColor(originalValue):parseFloat(originalValue||0),targetValue:unit=="color"?parseColor(value):value,unit:unit}}.bind(this)).reject(function(transform){return transform.originalValue==transform.targetValue||transform.unit!="color"&&(isNaN(transform.originalValue)||isNaN(transform.targetValue))})},update:function(position){var style={},transform,i=this.transforms.length;while(i--)style[(transform=this.transforms[i]).style]=
transform.unit=="color"?"#"+Math.round(transform.originalValue[0]+(transform.targetValue[0]-transform.originalValue[0])*position).toColorPart()+Math.round(transform.originalValue[1]+(transform.targetValue[1]-transform.originalValue[1])*position).toColorPart()+Math.round(transform.originalValue[2]+(transform.targetValue[2]-transform.originalValue[2])*position).toColorPart():(transform.originalValue+(transform.targetValue-transform.originalValue)*position).toFixed(3)+(transform.unit===null?"":transform.unit);
this.element.setStyle(style,true)}});
Effect.Transform=Class.create({initialize:function(tracks){this.tracks=[];this.options=arguments[1]||{};this.addTracks(tracks)},addTracks:function(tracks){tracks.each(function(track){track=$H(track);var data=track.values().first();this.tracks.push($H({ids:track.keys().first(),effect:Effect.Morph,options:{style:data}}))}.bind(this));return this},play:function(){return new Effect.Parallel(this.tracks.map(function(track){var ids=track.get("ids"),effect=track.get("effect"),options=track.get("options");
var elements=[$(ids)||$$(ids)].flatten();return elements.map(function(e){return new effect(e,Object.extend({sync:true},options))})}).flatten(),this.options)}});
Element.CSS_PROPERTIES=$w("backgroundColor backgroundPosition borderBottomColor borderBottomStyle "+"borderBottomWidth borderLeftColor borderLeftStyle borderLeftWidth "+"borderRightColor borderRightStyle borderRightWidth borderSpacing "+"borderTopColor borderTopStyle borderTopWidth bottom clip color "+"fontSize fontWeight height left letterSpacing lineHeight "+"marginBottom marginLeft marginRight marginTop markerOffset maxHeight "+"maxWidth minHeight minWidth opacity outlineColor outlineOffset "+
"outlineWidth paddingBottom paddingLeft paddingRight paddingTop "+"right textIndent top width wordSpacing zIndex");Element.CSS_LENGTH=/^(([\+\-]?[0-9\.]+)(em|ex|px|in|cm|mm|pt|pc|\%))|0$/;String.__parseStyleElement=document.createElement("div");
String.prototype.parseStyle=function(){var style,styleRules=$H();if(Prototype.Browser.WebKit)style=(new Element("div",{style:this})).style;else{String.__parseStyleElement.innerHTML='<div style="'+this+'"></div>';style=String.__parseStyleElement.childNodes[0].style}Element.CSS_PROPERTIES.each(function(property){if(style[property])styleRules.set(property,style[property])});if(Prototype.Browser.IE&&this.include("opacity"))styleRules.set("opacity",this.match(/opacity:\s*((?:0|1)?(?:\.\d*)?)/)[1]);return styleRules};
if(document.defaultView&&document.defaultView.getComputedStyle)Element.getStyles=function(element){var css=document.defaultView.getComputedStyle($(element),null);return Element.CSS_PROPERTIES.inject({},function(styles,property){styles[property]=css[property];return styles})};else Element.getStyles=function(element){element=$(element);var css=element.currentStyle,styles;styles=Element.CSS_PROPERTIES.inject({},function(results,property){results[property]=css[property];return results});if(!styles.opacity)styles.opacity=
element.getOpacity();return styles};Effect.Methods={morph:function(element,style){element=$(element);new Effect.Morph(element,Object.extend({style:style},arguments[2]||{}));return element},visualEffect:function(element,effect,options){element=$(element);var s=effect.dasherize().camelize(),klass=s.charAt(0).toUpperCase()+s.substring(1);new Effect[klass](element,options);return element},highlight:function(element,options){element=$(element);new Effect.Highlight(element,options);return element}};
$w("fade appear grow shrink fold blindUp blindDown slideUp slideDown "+"pulsate shake puff squish switchOff dropOut").each(function(effect){Effect.Methods[effect]=function(element,options){element=$(element);Effect[effect.charAt(0).toUpperCase()+effect.substring(1)](element,options);return element}});$w("getInlineOpacity forceRerendering setContentZoom collectTextNodes collectTextNodesIgnoreClass getStyles").each(function(f){Effect.Methods[f]=Element[f]});Element.addMethods(Effect.Methods);
var Prototip={Version:"2.2.3"};var Tips={options:{paths:{images:"/Scripts/Libraries/Prototip/images/prototip/",javascript:"/Scripts/Libraries/Prototip/js/"},zIndex:6E3}};Prototip.Styles=null;
eval(function(p,a,c,k,e,r){e=function(c){return(c<a?"":e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!"".replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return"\\w+"};c=1}while(c--)if(k[c])p=p.replace(new RegExp("\\b"+e(c)+"\\b","g"),k[c]);return p}('S.17(18,{4w:"1.7",2P:{2a:!!15.4x("2a").3y},3z:B(d){4y{15.4z("<2l 3A=\'3B/1D\' 1J=\'"+d+"\'><\\/2l>")}4A(c){$$("4B")[0].Q(P M("2l",{1J:d,3A:"3B/1D"}))}},3C:B(){3.3D("2Q");C b=/1K([\\w\\d-2R.]+)?\\.3E(.*)/;3.2S=(($$("2l[1J]").4C(B(a){W a.1J.2b(b)})||{}).1J||"").2T(b,""),E.2c=B(c){W{12:/^(3F?:\\/\\/|\\/)/.3G(c.12)?c.12:3.2S+c.12,1D:/^(3F?:\\/\\/|\\/)/.3G(c.1D)?c.1D:3.2S+c.1D}}.1h(3)(E.9.2c),18.2m||3.3z(E.2c.1D+"3H.3E"),3.2P.2a||(15.4D<8||15.3I.2n?15.1e("3J:2U",B(){C c=15.4E();c.4F="2n\\\\:*{4G:2V(#2o#3K)}"}):15.3I.2W("2n","4H:4I-4J-4K:4L","#2o#3K")),E.2p(),M.1e(2X,"2Y",3.2Y)},3D:B(b){N(4M 2X[b]=="4N"||3.2Z(2X[b].4O)<3.2Z(3["3L"+b])){3M"18 4P "+b+" >= "+3["3L"+b]}},2Z:B(d){C c=d.2T(/2R.*|\\./g,"");c=4Q(c+"0".4R(4-c.1W));W d.4S("2R")>-1?c-1:c},30:B(b){W b>0?-1*b:b.4T()},2Y:B(){E.3N()}}),S.17(E,B(){B b(c){c&&(c.3O(),c.1a&&(c.K.1L(),E.1m&&c.1p.1L()),E.1q=E.1q.3P(c))}W{1q:[],1b:[],2p:B(){3.2q=3.1r},2e:{H:"31",31:"H",F:"1s",1s:"F",1X:"1X",1f:"1i",1i:"1f"},3Q:{O:"1f",L:"1i"},32:B(c){W!1Y[1]?c:3.2e[c]},1m:B(d){C c=(P 4U("4V ([\\\\d.]+)")).4W(d);W c?3R(c[1])<7:!1}(4X.4Y),33:2Q.4Z.51&&!15.52,2W:B(c){3.1q.2f(c)},1L:B(a){C l,k=[];1Z(C j=0,i=3.1q.1W;j<i;j++){C h=3.1q[j];l||h.I!=$(a)?h.I.3S||k.2f(h):l=h}b(l);1Z(C j=0,i=k.1W;j<i;j++){C h=k[j];b(h)}a.1K=2g},3N:B(){1Z(C a=0,d=3.1q.1W;a<d;a++){b(3.1q[a])}},2r:B(e){N(e!=3.3T){N(3.1b.1W===0){3.2q=3.9.1r;1Z(C d=0,f=3.1q.1W;d<f;d++){3.1q[d].K.D({1r:3.9.1r})}}e.K.D({1r:3.2q++}),e.X&&e.X.D({1r:3.2q}),3.3T=e}},3U:B(c){3.34(c),3.1b.2f(c)},34:B(c){3.1b=3.1b.3P(c)},3V:B(){E.1b.1M("10")},11:B(v,u){v=$(v),u=$(u);C t=S.17({1g:{x:0,y:0},T:!1},1Y[2]||{}),s=t.1t||u.2s();s.H+=t.1g.x,s.F+=t.1g.y;C r=t.1t?[0,0]:u.3W(),q=15.1E.2t(),p=t.1t?"20":"1c";s.H+=-1*(r[0]-q[0]),s.F+=-1*(r[1]-q[1]);N(t.1t){C o=[0,0];o.O=0,o.L=0}C n={I:v.21()},m={I:S.2h(s)};n[p]=t.1t?o:u.21(),m[p]=S.2h(s);1Z(C l 3X m){3Y(t[l]){Y"53":Y"54":m[l].H+=n[l].O;1j;Y"55":m[l].H+=n[l].O/2;1j;Y"56":m[l].H+=n[l].O,m[l].F+=n[l].L/2;1j;Y"57":Y"58":m[l].F+=n[l].L;1j;Y"59":Y"5a":m[l].H+=n[l].O,m[l].F+=n[l].L;1j;Y"5b":m[l].H+=n[l].O/2,m[l].F+=n[l].L;1j;Y"5c":m[l].F+=n[l].L/2}}s.H+=-1*(m.I.H-m[p].H),s.F+=-1*(m.I.F-m[p].F),t.T&&v.D({H:s.H+"G",F:s.F+"G"});W s}}}()),E.2p();C 5d=5e.3Z({2p:B(g,f){3.I=$(g);N(!3.I){3M"18: M 5f 5g, 5h 3Z a 1a."}E.1L(3.I);C j=S.2u(f)||S.35(f),i=j?1Y[2]||[]:f;3.1u=j?f:2g,i.22&&(i=S.17(S.2h(18.2m[i.22]),i)),3.9=S.17(S.17({1n:!1,1k:0,36:"#5i",1o:0,R:E.9.R,1d:E.9.5j,1y:!i.13||i.13!="23"?0.14:!1,1v:!1,1l:"1N",40:!1,11:i.11,1g:i.11?{x:0,y:0}:{x:16,y:16},1O:i.11&&!i.11.1t?!0:!1,13:"2v",J:!1,22:"2o",1c:3.I,19:!1,1E:i.11&&!i.11.1t?!1:!0,O:!1},18.2m["2o"]),i),3.1c=$(3.9.1c),3.1o=3.9.1o,3.1k=3.1o>3.9.1k?3.1o:3.9.1k,3.9.12?3.12=3.9.12.41("://")?3.9.12:E.2c.12+3.9.12:3.12=E.2c.12+"3H/"+(3.9.22||"")+"/",3.12.5k("/")||(3.12+="/"),S.2u(3.9.J)&&(3.9.J={T:3.9.J}),3.9.J.T&&(3.9.J=S.17(S.2h(18.2m[3.9.22].J)||{},3.9.J),3.9.J.T=[3.9.J.T.2b(/[a-z]+/)[0].2w(),3.9.J.T.2b(/[A-Z][a-z]+/)[0].2w()],3.9.J.1F=["H","31"].5l(3.9.J.T[0])?"1f":"1i",3.1w={1f:!1,1i:!1}),3.9.1n&&(3.9.1n.9=S.17({37:2Q.5m},3.9.1n.9||{}));N(3.9.11.1t){C h=3.9.11.1x.2b(/[a-z]+/)[0].2w();3.20=E.2e[h]+E.2e[3.9.11.1x.2b(/[A-Z][a-z]+/)[0].2w()].2x()}3.42=E.33&&3.1o,3.43(),E.2W(3),3.44(),18.17(3)},43:B(){3.K=(P M("V",{R:"1K"})).D({1r:E.9.1r}),3.42&&(3.K.10=B(){3.D("H:-45;F:-45;1P:2y;");W 3},3.K.U=B(){3.D("1P:1b");W 3},3.K.1b=B(){W 3.38("1P")=="1b"&&3R(3.38("F").2T("G",""))>-5n}),3.K.10(),E.1m&&(3.1p=(P M("5o",{R:"1p",1J:"1D:5p;",5q:0})).D({2z:"2i",1r:E.9.1r-1,5r:0})),3.9.1n&&(3.1Q=3.1Q.39(3.3a)),3.1x=P M("V",{R:"1u"}),3.19=(P M("V",{R:"19"})).10();N(3.9.1d||3.9.1l.I&&3.9.1l.I=="1d"){3.1d=(P M("V",{R:"2j"})).24(3.12+"2j.2A")}},2B:B(){N(15.2U){3.3b(),3.46=!0;W!0}N(!3.46){15.1e("3J:2U",3.3b);W!1}},3b:B(){$(15.3c).Q(3.K),E.1m&&$(15.3c).Q(3.1p),3.9.1n&&$(15.3c).Q(3.X=(P M("V",{R:"5s"})).24(3.12+"X.5t").10());C i="K";N(3.9.J.T){3.J=(P M("V",{R:"5u"})).D({L:3.9.J[3.9.J.1F=="1i"?"L":"O"]+"G"});C h=3.9.J.1F=="1f";3[i].Q(3.3d=(P M("V",{R:"5v 2C"})).Q(3.47=P M("V",{R:"5w 2C"}))),3.J.Q(3.1R=(P M("V",{R:"5x"})).D({L:3.9.J[h?"O":"L"]+"G",O:3.9.J[h?"L":"O"]+"G"})),E.1m&&!3.9.J.T[1].48().41("5y")&&3.1R.D({2z:"5z"}),i="47"}N(3.1k){C n=3.1k,m;3[i].Q(3.25=(P M("5A",{R:"25"})).Q(3.26=(P M("3e",{R:"26 3f"})).D("L: "+n+"G").Q((P M("V",{R:"2D 5B"})).Q(P M("V",{R:"27"}))).Q(m=(P M("V",{R:"5C"})).D({L:n+"G"}).Q((P M("V",{R:"49"})).D({1z:"0 "+n+"G",L:n+"G"}))).Q((P M("V",{R:"2D 5D"})).Q(P M("V",{R:"27"})))).Q(3.3g=(P M("3e",{R:"3g 3f"})).Q(3.3h=(P M("V",{R:"3h"})).D("2E: 0 "+n+"G"))).Q(3.4a=(P M("3e",{R:"4a 3f"})).D("L: "+n+"G").Q((P M("V",{R:"2D 5E"})).Q(P M("V",{R:"27"}))).Q(m.5F(!0)).Q((P M("V",{R:"2D 5G"})).Q(P M("V",{R:"27"}))))),i="3h";C l=3.25.3i(".27");$w("5H 5I 5J 5K").4b(B(d,c){3.1o>0?18.4c(l[c],d,{1S:3.9.36,1k:n,1o:3.9.1o}):l[c].2F("4d"),l[c].D({O:n+"G",L:n+"G"}).2F("27"+d.2x())}.1h(3)),3.25.3i(".49",".3g",".4d").1M("D",{1S:3.9.36})}3[i].Q(3.1a=(P M("V",{R:"1a "+3.9.R})).Q(3.28=(P M("V",{R:"28"})).Q(3.19)));N(3.9.O){C k=3.9.O;S.5L(k)&&(k+="G"),3.1a.D("O:"+k)}N(3.J){C j={};j[3.9.J.1F=="1f"?"F":"1s"]=3.J,3.K.Q(j),3.2k()}3.1a.Q(3.1x),3.9.1n||3.3j({19:3.9.19,1u:3.1u})},3j:B(g){C f=3.K.38("1P");3.K.D("L:1T;O:1T;1P:2y").U(),3.1k&&(3.26.D("L:0"),3.26.D("L:0")),g.19?(3.19.U().4e(g.19),3.28.U()):3.1d||(3.19.10(),3.28.10()),S.35(g.1u)&&g.1u.U(),(S.2u(g.1u)||S.35(g.1u))&&3.1x.4e(g.1u),3.1a.D({O:3.1a.4f()+"G"}),3.K.D("1P:1b").U(),3.1a.U();C j=3.1a.21(),i={O:j.O+"G"},h=[3.K];E.1m&&h.2f(3.1p),3.1d&&(3.19.U().Q({F:3.1d}),3.28.U()),(g.19||3.1d)&&3.28.D("O: 3k%"),i.L=2g,3.K.D({1P:f}),3.1x.2F("2C"),(g.19||3.1d)&&3.19.2F("2C"),3.1k&&(3.26.D("L:"+3.1k+"G"),3.26.D("L:"+3.1k+"G"),i="O: "+(j.O+2*3.1k)+"G",h.2f(3.25)),h.1M("D",i),3.J&&(3.2k(),3.9.J.1F=="1f"&&3.K.D({O:3.K.4f()+3.9.J.L+"G"})),3.K.10()},44:B(){3.3l=3.1Q.1A(3),3.2G=3.10.1A(3),3.9.1O&&3.9.13=="2v"&&(3.9.13="3m"),3.9.13&&3.9.13==3.9.1l&&(3.1U=3.4g.1A(3),3.I.1e(3.9.13,3.1U)),3.1d&&3.1d.1e("3m",B(b){b.24(3.12+"5M.2A")}.1h(3,3.1d)).1e("3n",B(b){b.24(3.12+"2j.2A")}.1h(3,3.1d));C e={I:3.1U?[]:[3.I],1c:3.1U?[]:[3.1c],1x:3.1U?[]:[3.K],1d:[],2i:[]},d=3.9.1l.I;3.3o=d||(3.9.1l?"I":"2i"),3.1V=e[3.3o],!3.1V&&d&&S.2u(d)&&(3.1V=3.1x.3i(d)),$w("U 10").4b(B(h){C g=h.2x(),i=3.9[h+"4h"].5N||3.9[h+"4h"];i=="3m"?i=="3p":i=="3n"&&i=="1N",3[h+"5O"]=i}.1h(3)),!3.1U&&3.9.13&&3.I.1e(3.9.13,3.3l),3.1V&&3.9.1l&&3.1V.1M("1e",3.3q,3.2G),!3.9.1O&&3.9.13=="23"&&(3.2H=3.T.1A(3),3.I.1e("2v",3.2H)),3.4i=3.10.39(B(h,g){C i=g.5P(".2j");i&&(i.5Q(),g.5R(),h(g))}).1A(3),(3.1d||3.9.1l&&3.9.1l.I==".2j")&&3.K.1e("23",3.4i),3.9.13!="23"&&3.3o!="I"&&(3.2I=B(){3.1G("U")}.1A(3),3.I.1e("1N",3.2I));N(3.9.1l||3.9.1v){C f=[3.I,3.K];3.3r=B(){E.2r(3),3.2J()}.1A(3),3.3s=3.1v.1A(3),f.1M("1e","3p",3.3r).1M("1e","1N",3.3s)}3.9.1n&&3.9.13!="23"&&(3.2K=3.4j.1A(3),3.I.1e("1N",3.2K))},3O:B(){3.9.13&&3.9.13==3.9.1l?3.I.1B(3.9.13,3.1U):(3.9.13&&3.I.1B(3.9.13,3.3l),3.1V&&3.9.1l&&3.3q&&3.2G&&3.1V.1M("1B",3.3q,3.2G)),3.2H&&3.I.1B("2v",3.2H),3.2I&&3.I.1B("3n",3.2I),3.K.1B(),(3.9.1l||3.9.1v)&&3.I.1B("3p",3.3r).1B("1N",3.3s),3.2K&&3.I.1B("1N",3.2K)},3a:B(g,f){N(!3.1a){N(!3.2B()){W}}3.T(f);N(!3.2L){N(3.3t){g(f);W}3.2L=!0;C j={1C:{1H:0,1I:0}};N(f.4k){C i=f.4k(),j={1C:{1H:i.x,1I:i.y}}}29{f.1C&&(j.1C=f.1C)}C h=S.2h(3.9.1n.9);h.37=h.37.39(B(d,c){3.3j({19:3.9.19,1u:c.5S}),3.T(j),B(){d(c);C a=3.X&&3.X.1b();3.X&&(3.1G("X"),3.X.1L(),3.X=2g),a&&3.U(),3.3t=!0,3.2L=2g}.1h(3).1y(0.6)}.1h(3)),3.5T=M.U.1y(3.9.1y,3.X),3.K.10(),3.2L=!0,3.X.U(),3.5U=B(){P 5V.5W(3.9.1n.2V,h)}.1h(3).1y(3.9.1y);W!1}},4j:B(){3.1G("X")},1Q:B(b){N(!3.1a){N(!3.2B()){W}}3.T(b);3.K.1b()||(3.1G("U"),3.5X=3.U.1h(3).1y(3.9.1y))},1G:B(b){3[b+"4l"]&&5Y(3[b+"4l"])},U:B(){3.K.1b()||(E.1m&&3.1p.U(),3.9.40&&E.3V(),E.3U(3),3.1a.U(),3.K.U(),3.J&&3.J.U(),3.I.4m("1K:5Z"))},1v:B(b){3.9.1n&&(3.X&&3.9.13!="23"&&3.X.10());3.9.1v&&(3.2J(),3.60=3.10.1h(3).1y(3.9.1v))},2J:B(){3.9.1v&&3.1G("1v")},10:B(){3.1G("U"),3.1G("X");3.K.1b()&&3.4n()},4n:B(){E.1m&&3.1p.10(),3.X&&3.X.10(),3.K.10(),(3.25||3.1a).U(),E.34(3),3.I.4m("1K:2y")},4g:B(b){3.K&&3.K.1b()?3.10(b):3.1Q(b)},2k:B(){C h=3.9.J,g=1Y[0]||3.1w,l=E.32(h.T[0],g[h.1F]),k=E.32(h.T[1],g[E.2e[h.1F]]),j=3.1o||0;3.1R.24(3.12+l+k+".2A");N(h.1F=="1f"){C i=l=="H"?h.L:0;3.3d.D("H: "+i+"G;"),3.1R.D({"2M":l}),3.J.D({H:0,F:k=="1s"?"3k%":k=="1X"?"50%":0,61:(k=="1s"?-1*h.O:k=="1X"?-0.5*h.O:0)+(k=="1s"?-1*j:k=="F"?j:0)+"G"})}29{3.3d.D(l=="F"?"1z: 0; 2E: "+h.L+"G 0 0 0;":"2E: 0; 1z: 0 0 "+h.L+"G 0;"),3.J.D(l=="F"?"F: 0; 1s: 1T;":"F: 1T; 1s: 0;"),3.1R.D({1z:0,"2M":k!="1X"?k:"2i"}),k=="1X"?3.1R.D("1z: 0 1T;"):3.1R.D("1z-"+k+": "+j+"G;"),E.33&&(l=="1s"?(3.J.D({T:"4o",62:"63",F:"1T",1s:"1T","2M":"H",O:"3k%",1z:-1*h.L+"G 0 0 0"}),3.J.22.2z="4p"):3.J.D({T:"4q","2M":"2i",1z:0}))}3.1w=g},T:B(z){N(!3.1a){N(!3.2B()){W}}E.2r(3);N(E.1m){C y=3.K.21();(!3.2N||3.2N.L!=y.L||3.2N.O!=y.O)&&3.1p.D({O:y.O+"G",L:y.L+"G"}),3.2N=y}N(3.9.11){C x,w;N(3.20){C v=15.1E.2t(),u=z.1C||{},t,s=2;3Y(3.20.48()){Y"64":Y"65":t={x:0-s,y:0-s};1j;Y"66":t={x:0,y:0-s};1j;Y"67":Y"68":t={x:s,y:0-s};1j;Y"69":t={x:s,y:0};1j;Y"6a":Y"6b":t={x:s,y:s};1j;Y"6c":t={x:0,y:s};1j;Y"6d":Y"6e":t={x:0-s,y:s};1j;Y"6f":t={x:0-s,y:0}}t.x+=3.9.1g.x,t.y+=3.9.1g.y,x=S.17({1g:t},{I:3.9.11.1x,20:3.20,1t:{F:u.1I||2O.1I(z)-v.F,H:u.1H||2O.1H(z)-v.H}}),w=E.11(3.K,3.1c,x);N(3.9.1E){C r=3.3u(w),q=r.1w;w=r.T,w.H+=q.1i?2*18.30(t.x-3.9.1g.x):0,w.F+=q.1i?2*18.30(t.y-3.9.1g.y):0,3.J&&(3.1w.1f!=q.1f||3.1w.1i!=q.1i)&&3.2k(q)}w={H:w.H+"G",F:w.F+"G"},3.K.D(w)}29{x=S.17({1g:3.9.1g},{I:3.9.11.1x,1c:3.9.11.1c}),w=E.11(3.K,3.1c,S.17({T:!0},x)),w={H:w.H+"G",F:w.F+"G"}}N(3.X){C p=E.11(3.X,3.1c,S.17({T:!0},x))}E.1m&&3.1p.D(w)}29{C o=3.1c.2s(),u=z.1C||{},w={H:(3.9.1O?o[0]:u.1H||2O.1H(z))+3.9.1g.x,F:(3.9.1O?o[1]:u.1I||2O.1I(z))+3.9.1g.y};N(!3.9.1O&&3.I!==3.1c){C n=3.I.2s();w.H+=-1*(n[0]-o[0]),w.F+=-1*(n[1]-o[1])}N(!3.9.1O&&3.9.1E){C r=3.3u(w),q=r.1w;w=r.T,3.J&&(3.1w.1f!=q.1f||3.1w.1i!=q.1i)&&3.2k(q)}w={H:w.H+"G",F:w.F+"G"},3.K.D(w),3.X&&3.X.D(w),E.1m&&3.1p.D(w)}},3u:B(i){C h={1f:!1,1i:!1},n=3.K.21(),m=15.1E.2t(),l=15.1E.21(),k={H:"O",F:"L"};1Z(C j 3X k){i[j]+n[k[j]]-m[j]>l[k[j]]&&(i[j]=i[j]-(n[k[j]]+2*3.9.1g[j=="H"?"x":"y"]),3.J&&(h[E.3Q[k[j]]]=!0))}W{T:i,1w:h}}});S.17(18,{4c:B(t,s){C r=1Y[2]||3.9,q=r.1o,p=r.1k,o={F:s.4r(0)=="t",H:s.4r(1)=="l"};N(3.2P.2a){C n=P M("2a",{R:"6g"+s.2x(),O:p+"G",L:p+"G"});t.Q(n);C m=n.3y("2d");m.6h=r.1S,m.6i(o.H?q:p-q,o.F?q:p-q,q,0,6j.6k*2,!0),m.6l(),m.4s(o.H?q:0,0,p-q,p),m.4s(0,o.F?q:0,p,p-q)}29{C l;t.Q(l=(P M("V")).D({O:p+"G",L:p+"G",1z:0,2E:0,2z:"4p",T:"4o",6m:"2y"}));C k=(P M("2n:6n",{6o:r.1S,6p:"6q",6r:r.1S,6s:(q/p*0.5).6t(2)})).D({O:2*p-1+"G",L:2*p-1+"G",T:"4q",H:(o.H?0:-1*p)+"G",F:(o.F?0:-1*p)+"G"});l.Q(k),k.4t=k.4t}}}),M.6u({24:B(e,d){e=$(e);C f=S.17({4u:"F H",3v:"6v-3v",3w:"6w",1S:""},1Y[2]||{});e.D(E.1m?{6x:"6y:6z.6A.6B(1J=\'"+d+"\'\', 3w=\'"+f.3w+"\')"}:{6C:f.1S+" 2V("+d+") "+f.4u+" "+f.3v});W e}}),18.3x={4v:B(b){N(b.I&&!b.I.3S){W!0}W!1},U:B(){N(!18.3x.4v(3)){E.2r(3),3.2J();C f={};N(3.9.11&&!3.9.11.1t){f.1C={1H:0,1I:0}}29{C e=3.1c.2s(),h=3.1c.3W(),g=15.1E.2t();e.H+=-1*(h[0]-g[0]),e.F+=-1*(h[1]-g[1]),f.1C={1H:e.H,1I:e.F}}3.9.1n&&!3.3t?3.3a(3.1Q,f):3.1Q(f),3.1v()}}},18.17=B(b){b.I.1K={},S.17(b.I.1K,{U:18.3x.U.1h(b),10:b.10.1h(b),1L:E.1L.1h(E,b.I)})},18.3C();',
62,411,"|||this||||||options||||||||||||||||||||||||||||function|var|setStyle|Tips|top|px|left|element|stem|wrapper|height|Element|if|width|new|insert|className|Object|position|show|div|return|loader|case||hide|hook|images|showOn||document||extend|Prototip|title|tooltip|visible|target|closeButton|observe|horizontal|offset|bind|vertical|break|border|hideOn|fixIE|ajax|radius|iframeShim|tips|zIndex|bottom|mouse|content|hideAfter|stemInverse|tip|delay|margin|bindAsEventListener|stopObserving|fakePointer|javascript|viewport|orientation|clearTimer|pointerX|pointerY|src|prototip|remove|invoke|mouseleave|fixed|visibility|showDelayed|stemImage|backgroundColor|auto|eventToggle|hideTargets|length|middle|arguments|for|mouseHook|getDimensions|style|click|setPngBackground|borderFrame|borderTop|prototip_Corner|toolbar|else|canvas|match|paths||_inverse|push|null|clone|none|close|positionStem|script|Styles|ns_vml|default|initialize|zIndexTop|raise|cumulativeOffset|getScrollOffsets|isString|mousemove|toLowerCase|capitalize|hidden|display|png|build|clearfix|prototip_CornerWrapper|padding|addClassName|eventHide|eventPosition|eventCheckDelay|cancelHideAfter|ajaxHideEvent|ajaxContentLoading|float|iframeShimDimensions|Event|support|Prototype|_|path|replace|loaded|url|add|window|unload|convertVersionString|toggleInt|right|inverseStem|WebKit419|removeVisible|isElement|borderColor|onComplete|getStyle|wrap|ajaxShow|_build|body|stemWrapper|li|borderRow|borderMiddle|borderCenter|select|_update|100|eventShow|mouseover|mouseout|hideElement|mouseenter|hideAction|activityEnter|activityLeave|ajaxContentLoaded|getPositionWithinViewport|repeat|sizingMethod|Methods|getContext|insertScript|type|text|start|require|js|https|test|styles|namespaces|dom|VML|REQUIRED_|throw|removeAll|deactivate|without|_stemTranslation|parseFloat|parentNode|_highest|addVisibile|hideAll|cumulativeScrollOffset|in|switch|create|hideOthers|include|fixSafari2|setup|activate|9500px|_isBuilding|stemBox|toUpperCase|prototip_Between|borderBottom|each|createCorner|prototip_Fill|update|getWidth|toggle|On|buttonEvent|ajaxHide|pointer|Timer|fire|afterHide|relative|block|absolute|charAt|fillRect|outerHTML|align|hold|REQUIRED_Prototype|createElement|try|write|catch|head|find|documentMode|createStyleSheet|cssText|behavior|urn|schemas|microsoft|com|vml|typeof|undefined|Version|requires|parseInt|times|indexOf|abs|RegExp|MSIE|exec|navigator|userAgent|Browser||WebKit|evaluate|topRight|rightTop|topMiddle|rightMiddle|bottomLeft|leftBottom|bottomRight|rightBottom|bottomMiddle|leftMiddle|Tip|Class|not|available|cannot|000000|closeButtons|endsWith|member|emptyFunction|9500|iframe|false|frameBorder|opacity|prototipLoader|gif|prototip_Stem|prototip_StemWrapper|prototip_StemBox|prototip_StemImage|MIDDLE|inline|ul|prototip_CornerWrapperTopLeft|prototip_BetweenCorners|prototip_CornerWrapperTopRight|prototip_CornerWrapperBottomLeft|cloneNode|prototip_CornerWrapperBottomRight|tl|tr|bl|br|isNumber|close_hover|event|Action|findElement|blur|stop|responseText|loaderTimer|ajaxTimer|Ajax|Request|showTimer|clearTimeout|shown|hideAfterTimer|marginTop|clear|both|LEFTTOP|TOPLEFT|TOPMIDDLE|TOPRIGHT|RIGHTTOP|RIGHTMIDDLE|RIGHTBOTTOM|BOTTOMRIGHT|BOTTOMMIDDLE|BOTTOMLEFT|LEFTBOTTOM|LEFTMIDDLE|cornerCanvas|fillStyle|arc|Math|PI|fill|overflow|roundrect|fillcolor|strokeWeight|1px|strokeColor|arcSize|toFixed|addMethods|no|scale|filter|progid|DXImageTransform|Microsoft|AlphaImageLoader|background".split("|"),
0,{}));Position.getWindowSize=function(w){var viewportSize=document.viewport.getDimensions();var documentHeight=document.documentElement.scrollHeight;return{width:viewportSize.width,height:documentHeight}};
var ExposeInstances={instances:[],uniqueId:0,zIndexOffset:0,add:function(instance){this.instances.push(instance)},remove:function(exposeToRemove){this.instances=this.instances.reject(function(expose){return expose.getUniqueId()==exposeToRemove.getUniqueId()})},getUniqueId:function(){return this.uniqueId++},getZIndexOffset:function(){return this.zIndexOffset+=2},fitAllToWindow:function(){for(var i=0,j=this.instances.length;i<j;i++)this.instances[i].fit()},sleepOthers:function(){for(var i=0,j=this.instances.length;i<
j;i++)this.instances[i].sleep()},wakeOthers:function(){for(var i=0,j=this.instances.length;i<j;i++)this.instances[i].wake()}};
Expose=Class.create({Version:"1.2.3_prototype",options:{maskIdPrefix:"exposeMask",appearDuration:1,fadeDuration:0.5,closeOnClick:true,closeOnEsc:true,zIndexBase:4E3,opacity:0.8,startOpacity:0,color:"#fff",onLoad:null,onClose:null,detectPrototip:false},uniqueId:false,zIndex:0,mask:false,elements:false,exposed:false,loaded:false,sleeping:false,config:false,overlayIndex:0,previousPrototipZindex:0,fxOnDocumentKeypress:false,fxOnMaskClick:false,fxOnWindowResize:false,initialize:function(elements,customOptions){Object.extend(this.options,
customOptions||{});this.elements=(new Array(elements)).flatten();if(!this.elements.length||this.elements.length<1){console.error("Expose requires at least one element.");return}this.uniqueId=ExposeInstances.getUniqueId();this.zIndex=this.options.zIndexBase+ExposeInstances.getZIndexOffset();var maskId=this.options.maskIdPrefix+"-"+this.uniqueId;this.mask=$(maskId);if(!this.mask){this.mask=new Element("div",{"id":maskId});$(document.body).insert({top:this.mask})}var size=Position.getWindowSize();this.mask.setStyle({position:"absolute",
top:"0px",left:"0px",width:size.width+"px",height:size.height+"px",display:"none",opacity:this.options.startOpacity,zIndex:this.zIndex});if(this.options.color)this.mask.setStyle({backgroundColor:this.options.color});if(this.options.closeOnEsc){this.fxOnDocumentKeypress=function(e){if(!this.sleeping&&e.keyCode==27)this.close()}.bind(this);$(document).observe("keypress",this.fxOnDocumentKeypress)}if(this.options.closeOnClick){this.fxOnMaskClick=function(e){this.close()}.bind(this);this.mask.observe("click",
this.fxOnMaskClick)}this.fxOnWindowResize=function(){this.fit()}.bind(this);Event.observe(window,"resize",this.fxOnWindowResize);this.exposeElements();if(this.options.detectPrototip)if(typeof Prototip=="undefined"||typeof Tips=="undefined")console.error("Expose could not detect Prototip2");else{this.previousPrototipZindex=Tips.options.zIndex;Tips.options.zIndex=this.zIndex+1}ExposeInstances.sleepOthers();ExposeInstances.add(this);this.mask.setStyle({display:"block"});this.mask.appear({duration:this.options.appearDuration,
from:0,to:this.options.opacity,afterFinish:function(){this.fit();if(this.options.onLoad)this.options.onLoad()}.bind(this)});this.loaded=true},close:function(){if(this.loaded){if(this.options.onBeforeClose)if(this.options.onBeforeClose()===false)return;if(this.options.detectPrototip&&this.previousPrototipZindex)Tips.options.zIndex=this.previousPrototipZindex;if(this.options.closeOnEsc&&this.fxOnDocumentKeypress)$(document).stopObserving("keypress",this.fxOnDocumentKeypress);if(this.options.closeOnClick&&
this.fxOnMaskClick)this.mask.stopObserving("click",this.fxOnMaskClick);Event.stopObserving(window,"resize",this.fxOnWindowResize);this.mask.fade({duration:this.options.fadeDuration,afterFinish:function(){if(this.options.onClose)this.options.onClose();this.restoreElements();ExposeInstances.remove(this);ExposeInstances.wakeOthers();this.mask.remove()}.bind(this)});this.loaded=false}},exposeElements:function(){if(this.elements&&this.elements.length){this.overlayIndex=this.elements[0].getStyle("zIndex")||
"auto";for(var i=0,j=this.elements.length;i<j;i++){var element=this.elements[i];if(!/relative|absolute|fixed/i.test(element.getStyle("position")))element.setStyle({position:"relative"});element.setStyle({zIndex:Math.max(this.zIndex+1,this.overlayIndex=="auto"?0:this.overlayIndex)})}this.exposed=this.elements}},restoreElements:function(hardReset){if(this.exposed&&this.exposed.length)for(var i=0,j=this.exposed.length;i<j;i++)this.exposed[i].setStyle({zIndex:this.overlayIndex=="auto"?"":this.overlayIndex})},
sleep:function(){this.mask.fade({duration:0.5,queue:"top"});this.restoreElements();this.sleeping=true},wake:function(){this.mask.appear({duration:0.5,to:this.options.opacity,queue:"top"});this.exposeElements();this.sleeping=false},fit:function(){if(this.loaded){var size=Position.getWindowSize();this.mask.setStyle({width:size.width+"px",height:size.height+"px"})}},getMask:function(){return this.mask},isLoaded:function(){return this.loaded},getOptions:function(){return this.options},getExposed:function(){return this.exposed},
getUniqueId:function(){return this.uniqueId}});window.k=window.k||{};
(function(){var noticeOptions={header:"&nbsp;",speedin:0.3,speedout:0.5,outDirection:{y:-20},life:5,sticky:false,className:""};var growlerOptions={location:"tr",width:"250px"};var IE=Prototype.Browser.IE?parseFloat(navigator.appVersion.split("MSIE ")[1])||0:0;function removeNotice(n,o){o=o||noticeOptions;new Effect.Parallel([new Effect.Move(n,Object.extend({sync:true,mode:"relative"},o.outDirection)),new Effect.Opacity(n,{sync:true,to:0})],{duration:o.speedout,afterFinish:function(){try{var ne=n.down("div.notice-exit");
if(ne!=undefined)ne.stopObserving("click",removeNotice);if(o.created&&Object.isFunction(o.created))n.stopObserving("notice:created",o.created);if(o.destroyed&&Object.isFunction(o.destroyed)){n.fire("notice:destroyed");n.stopObserving("notice:destroyed",o.destroyed)}}catch(e){}try{n.remove()}catch(e){}}})}function createNotice(growler,msg,options){var opt=Object.clone(noticeOptions);options=options||{};Object.extend(opt,options);var notice;if(opt.className!="")notice=(new Element("div",{"class":opt.className})).setStyle({display:"block",
opacity:0});else notice=(new Element("div",{"class":"Growler-notice"})).setStyle({display:"block",opacity:0});if(opt.created&&Object.isFunction(opt.created))notice.observe("notice:created",opt.created);if(opt.destroyed&&Object.isFunction(opt.destroyed))notice.observe("notice:destroyed",opt.destroyed);if(opt.sticky){var noticeExit=(new Element("div",{"class":"Growler-notice-exit"})).update("&times;");noticeExit.observe("click",function(){removeNotice(notice,opt)});notice.insert(noticeExit)}notice.insert((new Element("div",
{"class":"Growler-notice-head"})).update(opt.header));notice.insert((new Element("div",{"class":"Growler-notice-body"})).update(msg));growler.insert(notice);new Effect.Opacity(notice,{to:0.85,duration:opt.speedin});if(!opt.sticky)removeNotice.delay(opt.life,notice,opt);notice.fire("notice:created");return notice}function specialNotice(g,m,o,t,b,c){o.header=o.header||t;var n=createNotice(g,m,o);n.setStyle({backgroundColor:b,color:c});return n}k.Growler=Class.create({initialize:function(options){var opt=
Object.clone(growlerOptions);options=options||{};Object.extend(opt,options);this.growler=new Element("div",{"class":"Growler","id":"Growler"});this.growler.setStyle({position:IE==6?"absolute":"fixed",padding:"10px","width":opt.width,"z-index":"50000"});if(IE==6){var offset={w:parseInt(this.growler.style.width)+parseInt(this.growler.style.padding)*3,h:parseInt(this.growler.style.height)+parseInt(this.growler.style.padding)*3};switch(opt.location){case "br":this.growler.style.setExpression("left","( 0 - Growler.offsetWidth + ( document.documentElement.clientWidth ? document.documentElement.clientWidth : document.body.clientWidth ) + ( ignoreMe2 = document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft ) ) + 'px'");
this.growler.style.setExpression("top","( 0 - Growler.offsetHeight + ( document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight ) + ( ignoreMe = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop ) ) + 'px'");break;case "tl":this.growler.style.setExpression("left","( 0 + ( ignoreMe2 = document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft ) ) + 'px'");this.growler.style.setExpression("top",
"( 0 + ( ignoreMe = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop ) ) + 'px'");break;case "bl":this.growler.style.setExpression("left","( 0 + ( ignoreMe2 = document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft ) ) + 'px'");this.growler.style.setExpression("top","( 0 - Growler.offsetHeight + ( document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight ) + ( ignoreMe = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop ) ) + 'px'");
break;default:this.growler.setStyle({right:"auto",bottom:"auto"});this.growler.style.setExpression("left","( 0 - Growler.offsetWidth + ( document.documentElement.clientWidth ? document.documentElement.clientWidth : document.body.clientWidth ) + ( ignoreMe2 = document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft ) ) + 'px'");this.growler.style.setExpression("top","( 0 + ( ignoreMe = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop ) ) + 'px'");
break}}else switch(opt.location){case "br":this.growler.setStyle({bottom:0,right:0});break;case "tl":this.growler.setStyle({top:0,left:0});break;case "bl":this.growler.setStyle({top:0,right:0});break;case "tc":this.growler.setStyle({top:0,left:"25%",width:"50%"});break;case "bc":this.growler.setStyle({bottom:0,left:"25%",width:"50%"});break;default:this.growler.setStyle({top:0,right:0});break}this.growler.wrap(document.body)},growl:function(msg,options){return createNotice(this.growler,msg,options)},
warn:function(msg,options){return specialNotice(this.growler,msg,options,"Warning!","#F6BD6F","#000")},error:function(msg,options){return specialNotice(this.growler,msg,options,"Critical!","#F66F82","#000")},info:function(msg,options){return specialNotice(this.growler,msg,options,"Information!","#BBF66F","#000")},ungrowl:function(n,o){removeNotice(n,o)}})})();
if(Object.isUndefined(Prototype.Browser.IE6))Prototype.Browser.IE6=navigator.appName.indexOf("Microsoft Internet Explorer")!=-1&&navigator.appVersion.indexOf("MSIE 6.0")!=-1&&!window.XMLHttpRequest;if(!window.Modalbox)var Modalbox={};
Modalbox.Methods={overrideAlert:false,focusableElements:[],currFocused:0,initialized:false,active:true,options:{title:"ModalBox Window",overlayClose:true,width:500,height:90,overlayOpacity:0.65,overlayDuration:0.25,slideDownDuration:0.5,slideUpDuration:0.5,resizeDuration:0.25,inactiveFade:true,transitions:true,loadingString:"Please wait. Loading...",closeString:"Close window",closeValue:"&times;",params:{},method:"get",autoFocusing:true,cloneDomNode:true,aspnet:false,resizeCSSID:""},_options:{},setOptions:function(options){Object.extend(this.options,
options||{})},_init:function(options){Object.extend(this._options,this.options);this.setOptions(options);this.MBoverlay=new Element("div",{id:"MB_overlay",style:"opacity: 0"});this.MBwindowwrapper=(new Element("div",{id:"MB_windowwrapper"})).update(this.MBwindow=(new Element("div",{id:"MB_window",style:"display: none"})).update(this.MBframe=(new Element("div",{id:"MB_frame"})).update(this.MBheader=(new Element("div",{id:"MB_header"})).update(this.MBcaption=new Element("div",{id:"MB_caption"})))));
this.MBclose=(new Element("a",{id:"MB_close",title:this.options.closeString,href:"#"})).update("<span>"+this.options.closeValue+"</span>");this.MBheader.insert({"bottom":this.MBclose});this.MBcontent=(new Element("div",{id:"MB_content"})).update(this.MBloading=(new Element("div",{id:"MB_loading"})).update(this.options.loadingString));this.MBframe.insert({"bottom":this.MBcontent});var injectToEl=this.options.aspnet?$(document.body).down("form"):$(document.body);injectToEl.insert({"top":this.MBwindowwrapper});
injectToEl.insert({"top":this.MBoverlay});var scrollOffsets=document.viewport.getScrollOffsets();if(scrollOffsets[1]>0)$("MB_window").setStyle({top:scrollOffsets[1]+"px"});Event.observe(window,"scroll",function(){scrollOffsets=document.viewport.getScrollOffsets();$("MB_window").setStyle({top:scrollOffsets[1]+"px"})});this.initScrollX=window.pageXOffset||document.body.scrollLeft||document.documentElement.scrollLeft;this.initScrollY=window.pageYOffset||document.body.scrollTop||document.documentElement.scrollTop;
this.hideObserver=this._hide.bindAsEventListener(this);this.clickOverlayObserver=this._clickOverlay.bindAsEventListener(this);this.kbdObserver=this._kbdHandler.bindAsEventListener(this);this.resizeObserver=this._setWidthAndPosition.bindAsEventListener(this);this._initObservers();this.initialized=true},show:function(content,options){if(!this.initialized)this._init(options);this._cleanUpContentIDs();this.content=content;this.setOptions(options);if(this.options.title)this.MBcaption.update(this.options.title);
else{this.MBheader.hide();this.MBcaption.hide()}if(this.MBwindow.style.display=="none"){this._appear();this.event("onShow")}else{this._update();this.event("onUpdate")}},hide:function(options){if(this.initialized){if(options&&!Object.isFunction(options.element))Object.extend(this.options,options);this.event("beforeHide");if(this.options.transitions)Effect.SlideUp(this.MBwindow,{duration:this.options.slideUpDuration,transition:Effect.Transitions.sinoidal,afterFinish:this._deinit.bind(this)});else{this.MBwindow.hide();
this._deinit()}Event.stopObserving(window,"scroll")}else throw"Modalbox is not initialized.";},_hide:function(event){event.stop();if(event.element().id=="MB_overlay"&&!this.options.overlayClose)return false;this.hide()},_clickOverlay:function(event){event.stop();Effect.Pulsate("MB_overlay",{from:this.options.overlayOpacity-0.1,to:this.options.overlayOpacity,pulses:2,duration:1.5,afterFinish:function(){$("MB_overlay").setOpacity(this.options.overlayOpacity)}.bind(this)})},alert:function(message,title){var html=
'<div class="MB_alert"><p>'+message+'</p><input type="button" onclick="Modalbox.hide()" value="OK" /></div>';Modalbox.show(html,{title:title,width:500,overlayClose:false})},_appear:function(){if(Prototype.Browser.IE6){window.scrollTo(0,0);this._prepareIEHtml("100%","hidden");this._prepareIESelects("hidden")}this._setWidth();if(this.options.transitions){this.MBoverlay.setOpacity(0);new Effect.Fade(this.MBoverlay,{from:0,to:this.options.overlayOpacity,duration:this.options.overlayDuration,afterFinish:function(){new Effect.SlideDown(this.MBwindow,
{duration:this.options.slideDownDuration,transition:Effect.Transitions.sinoidal,afterFinish:this.loadContent.bind(this)})}.bind(this)})}else{this.MBoverlay.setOpacity(this.options.overlayOpacity);this.MBwindow.show();this.loadContent()}Event.observe(window,"resize",this.resizeObserver)},resize:function(byWidth,byHeight,options){var oWidth=$(this.MBoverlay).getWidth();var wHeight=$(this.MBwindow).getHeight();var wWidth=$(this.MBwindow).getWidth();var hHeight=$(this.MBheader).getHeight();var cHeight=
$(this.MBcontent).getHeight();var newHeight=wHeight-hHeight+byHeight<cHeight?cHeight+hHeight:wHeight+byHeight;var el=$(this.MBwindow);var contentEl=$(this.MBcontent);var windowBottomMargin=10;newHeight+=windowBottomMargin;var windowOffset=parseInt(el.getStyle("margin-top"),0)+parseInt(el.getStyle("margin-bottom"),0)+parseInt(el.getStyle("border-top-width"),0)+parseInt(el.getStyle("border-bottom-width"),0)+windowBottomMargin;var contentPadding=parseInt(contentEl.getStyle("padding-top"))+parseInt(contentEl.getStyle("padding-bottom"));
if(newHeight+windowOffset+contentPadding>document.viewport.getHeight()){newHeight=document.viewport.getHeight()-windowOffset-windowBottomMargin;newcHeight=newHeight-hHeight-parseInt($(this.MBframe).getStyle("padding-bottom"),0)-parseInt($(this.MBcontent).getStyle("padding-bottom"),0);$(this.MBcontent).setStyle({height:newcHeight+"px"})}else if($(this.MBcontent).getStyle("height"))$(this.MBcontent).setStyle({height:""});var newWidth=wWidth+byWidth;var newStyle={width:newWidth+"px",height:newHeight+
"px"};this.options.width=newWidth;if(options)this.setOptions(options);if(this.options.transitions&&!Modalbox.animating){Modalbox.animating=true;new Effect.Morph(this.MBwindow,{style:newStyle,duration:this.options.resizeDuration,beforeStart:function(fx){fx.element.setStyle({overflow:"hidden"})},afterFinish:function(fx){fx.element.setStyle({overflow:"visible"});this.event("_afterResize");this.event("afterResize");Modalbox.animating=false}.bind(this)})}else{this.MBwindow.setStyle(newStyle);(function(){this.event("_afterResize");
this.event("afterResize")}).bind(this).defer()}},resizeToContent:function(options){if(typeof options=="undefined")options={};var mbimages=$("MB_content").select("img");var totalimages=mbimages.length;if(mbimages[0])if(typeof options.imagesloaded=="undefined"){var loadedImages=$A();var loadedImageTotal=0;mbimages.each(function(o,idx){loadedImages[idx]=new Image;loadedImages[idx].src=o.src;loadedImages[idx].onload=function(){loadedImageTotal++;if(loadedImageTotal==totalimages){var imageincomplete=false;
mbimages.each(function(i){if(i.height==0)imageincomplete=true});if(imageincomplete||Modalbox.animating)Modalbox.resizeToContent();else{options.imagesloaded=true;Modalbox.resizeToContent(options)}}}})}var byWidth=0,byHeight=this.options.height-this.MBwindow.getHeight();if(options.resizeCSSID&&$(options.resizeCSSID))byWidth=$(options.resizeCSSID).getWidth()-$(this.MBwindow).getWidth()+(parseInt($(this.MBcontent).getStyle("padding-left"),0)+parseInt($(this.MBcontent).getStyle("padding-right"),0))+15;
if(byHeight!=0)this.resize(byWidth,byHeight,options)},resizeToInclude:function(element,options){var el=$(element);var elHeight=el.getHeight()+parseInt(el.getStyle("margin-top"),0)+parseInt(el.getStyle("margin-bottom"),0)+parseInt(el.getStyle("border-top-width"),0)+parseInt(el.getStyle("border-bottom-width"),0);if(elHeight>0)this.resize(0,elHeight,options)},_update:function(){this.MBcontent.update($(this.MBloading).update(this.options.loadingString));this.loadContent()},loadContent:function(){if(this.event("beforeLoad")!=
false)if(typeof this.content=="string"){var htmlRegExp=new RegExp(/<\/?[^>]+>/gi);if(htmlRegExp.test(this.content))this._processContent(this.content);else new Ajax.Request(this.content,{method:this.options.method.toLowerCase(),parameters:this.options.params,onComplete:function(response){this._processContent(response.responseText)}.bind(this),onException:function(instance,exception){Modalbox.hide();throw"Modalbox Loading Error: "+exception;}})}else if(typeof this.content=="object")this._insertContent(this.content);
else{this.hide();throw"Modalbox Parameters Error: Please specify correct URL or HTML element (plain HTML or object)";}},_processContent:function(content){var html=content.stripScripts(),scripts=content.extractScripts();this._insertContent(html,function(){scripts.map(function(script){return eval(script.replace("<\!--","").replace("// --\>",""))},window)})},_insertContent:function(content,callback){this.MBcontent.hide().update();if(typeof content=="string")this.MBcontent.insert((new Element("div",{style:"display: none"})).update(content)).down().show();
else if(typeof content=="object"){var _htmlObj=this.options.cloneDomNode?content.cloneNode(true):content;if(content.id)content.id="MB_"+content.id;$(content).select("*[id]").each(function(el){el.id="MB_"+el.id});this.MBcontent.insert(_htmlObj).down("div").show();if(Prototype.Browser.IE6)this._prepareIESelects("","#MB_content ")}if(this.options.height==this._options.height)this.resize(this.options.width-$(this.MBwindow).getWidth(),this.MBcontent.getHeight()-$(this.MBwindow).getHeight()+this.MBheader.getHeight(),
{afterResize:function(){this._putContent.bind(this,callback).defer()}.bind(this)});else{this._setWidth();this.MBcontent.setStyle({overflow:"auto",height:this.MBwindow.getHeight()-this.MBheader.getHeight()-13+"px"});this._putContent.bind(this,callback).defer()}},_putContent:function(callback){this.MBcontent.show();this._findFocusableElements();this._setFocus();if(Object.isFunction(callback))callback();this.event("afterLoad")},activate:function(options){this.setOptions(options);this.active=true;if(this.options.overlayClose)this.MBoverlay.observe("click",
this.hideObserver);this.MBclose.observe("click",this.hideObserver).show();if(this.options.transitions&&this.options.inactiveFade)new Effect.Appear(this.MBwindow,{duration:this.options.slideUpDuration})},deactivate:function(options){this.setOptions(options);this.active=false;if(this.options.overlayClose)this.MBoverlay.stopObserving("click",this.hideObserver);else this.MBoverlay.stopObserving("click",this.clickOverlayObserver);this.MBclose.stopObserving("click",this.hideObserver).hide();if(this.options.transitions&&
this.options.inactiveFade)new Effect.Fade(this.MBwindow,{duration:this.options.slideUpDuration,to:0.75})},_initObservers:function(){this.MBclose.observe("click",this.hideObserver);if(this.options.overlayClose)this.MBoverlay.observe("click",this.hideObserver);else $(this.MBoverlay).observe("click",this.clickOverlayObserver);var kbdEvent=Prototype.Browser.Gecko||Prototype.Browser.Opera?"keypress":"keydown";Event.observe(document,kbdEvent,this.kbdObserver)},_removeObservers:function(){this.MBclose.stopObserving("click",
this.hideObserver);if(this.options.overlayClose)this.MBoverlay.stopObserving("click",this.hideObserver);var kbdEvent=Prototype.Browser.Gecko||Prototype.Browser.Opera?"keypress":"keydown";Event.stopObserving(document,kbdEvent,this.kbdObserver)},_setFocus:function(){if(this.focusableElements.length>0&&this.options.autoFocusing==true){var firstEl=this.focusableElements.find(function(el){return el.tabIndex==1})||this.focusableElements.first();this.currFocused=this.focusableElements.toArray().indexOf(firstEl);
firstEl.focus()}else if(this.MBclose.visible())this.MBclose.focus()},_findFocusableElements:function(){if(this.options.autoFocusing===true){this.MBcontent.select("input:not([type=hidden]):enabled, select, textarea, button, a[href]").invoke("addClassName","MB_focusable");this.focusableElements=this.MBcontent.select(".MB_focusable")}},_kbdHandler:function(event){var node=event.element();switch(event.keyCode){case Event.KEY_TAB:event.stop();if(node!=this.focusableElements[this.currFocused])this.currFocused=
this.focusableElements.indexOf(node);if(!event.shiftKey)if(this.currFocused>=this.focusableElements.length-1)this.currFocused=0;else this.currFocused++;else if(this.currFocused<=0)this.currFocused=this.focusableElements.length-1;else this.currFocused--;this.focusableElements[this.currFocused].focus();break;case Event.KEY_ESC:if(this.active)this._hide(event);break;case 32:this._preventScroll(event);break;case 0:if(event.which==32)this._preventScroll(event);break;case Event.KEY_UP:case Event.KEY_DOWN:case Event.KEY_PAGEDOWN:case Event.KEY_PAGEUP:case Event.KEY_HOME:case Event.KEY_END:var tagName=
node.tagName.toLowerCase();if(Prototype.Browser.WebKit&&!["textarea","select"].include(tagName))event.stop();else if(tagName=="input"&&["submit","button"].include(node.type)||tagName=="a")event.stop();break}},_preventScroll:function(event){if(!["input","textarea","select","button"].include(event.element().tagName.toLowerCase()))event.stop()},_deinit:function(){this._removeObservers();Event.stopObserving(window,"resize",this.resizeObserver);if(this.options.transitions)Effect.toggle(this.MBoverlay,
"appear",{duration:this.options.overlayDuration,afterFinish:this._removeElements.bind(this)});else{this.MBoverlay.hide();this._removeElements()}this.MBcontent.setStyle({overflow:"",height:""})},_cleanUpContentIDs:function(){if(typeof this.content=="object"){if(this.content.id&&this.content.id.match(/MB_/))this.content.id=this.content.id.replace(/MB_/,"");this.content.select("*[id]").each(function(el){el.id=el.id.replace(/MB_/,"")})}},_removeElements:function(){if(Prototype.Browser.Opera)window.scrollBy(0,
0);this.MBoverlay.remove();$(this.MBwindowwrapper).remove();if(Prototype.Browser.IE6){this._prepareIEHtml("","");this._prepareIESelects("");window.scrollTo(this.initScrollX,this.initScrollY)}this._cleanUpContentIDs();this.initialized=false;this.event("afterHide");this.setOptions(this._options)},_setWidth:function(){this.MBwindow.setStyle({width:this.options.width+"px",height:this.options.height+"px"})},_setWidthAndPosition:function(){this.MBwindow.setStyle({width:this.options.width+"px"})},_prepareIEHtml:function(height,
overflow){$$("html, body").invoke("setStyle",{width:height,height:height,overflow:overflow})},_prepareIESelects:function(visibility,prefix){$$((prefix||"")+"select").invoke("setStyle",{"visibility":visibility})},event:function(eventName){var r=true;if(this.options[eventName]){var returnValue=this.options[eventName]();this.options[eventName]=null;if(!Object.isUndefined(returnValue))r=returnValue}return r}};Object.extend(Modalbox,Modalbox.Methods);if(Modalbox.overrideAlert)window.alert=Modalbox.alert;
BrainstormJs.Controls.ModalBox.Confirm=Class.create({options:false,confirmBox:false,text:false,confirmButton:false,cancelLink:false,hideObserver:false,confirmObserver:false,onConfirm:false,onCancel:false,initialize:function(options){this.options=options;this.confirmBox=new Element("div",{className:"confirmBox",style:"display:none;"});this.text=(new Element("p",{className:"text"})).update("Are you sure?");this.detailText=(new Element("p",{className:"detailText"})).update("");this.confirmButton=new Element("input",
{type:"button",value:"Confirm",className:"confirm"});this.cancelLink=(new Element("a",{href:"#",className:"cancel"})).update("Cancel");this.confirmBox.insert(this.text);this.confirmBox.insert(this.detailText);this.confirmBox.insert(this.confirmButton);this.confirmBox.insert(this.cancelLink);this.hideObserver=this.cancel.bindAsEventListener(this);this.confirmObserver=this.confirm.bindAsEventListener(this)},show:function(options){options=options||{};this.onConfirm=options.onConfirm||false;this.onCancel=
options.onCancel||false;if(options.text)this.text.update(options.text);if(options.detailText){this.detailText.update(options.detailText);this.detailText.show()}else this.detailText.hide();if(options.confirmText)this.confirmButton.value=options.confirmText;if(options.cancelText)this.cancelLink.update(options.cancelText);Modalbox.show(this.confirmBox,{title:options.title||"Are you sure?",width:options.width||400,overlayClose:false,cloneDomNode:false,afterLoad:this.setObservers.bind(this),afterHide:this.removeObservers.bind(this)})},
setObservers:function(e){this.cancelLink.observe("click",this.hideObserver);this.confirmButton.observe("click",this.confirmObserver)},removeObservers:function(){this.cancelLink.stopObserving("click",this.hideObserver);this.confirmButton.stopObserving("click",this.confirmObserver)},confirm:function(){if(this.onConfirm)this.onConfirm();Modalbox.hide()},cancel:function(e){if(this.onCancel)this.onCancel();Modalbox.hide();e.stop()}});
BrainstormJs.Controls.ModalBox.TextPrompt=Class.create({options:false,promptBox:false,text:false,textbox:false,confirmButton:false,cancelLink:false,hideObserver:false,confirmObserver:false,keyboardConfirmObserver:false,onConfirm:false,initialize:function(options){this.options=options;this.promptBox=new Element("div",{className:"promptBox",style:"display:none;"});this.text=(new Element("p",{className:"text"})).update("Text:");this.textbox=new Element("input",{type:"text",maxlength:"20",className:"textbox"});
this.confirmButton=new Element("input",{type:"button",value:"Confirm",className:"confirm"});this.cancelLink=(new Element("a",{href:"javascript:;",className:"cancel"})).update("Cancel");this.promptBox.insert(this.text);this.promptBox.insert(this.textbox);this.promptBox.insert(this.confirmButton);this.promptBox.insert(this.cancelLink);this.hideObserver=function(e){Modalbox.hide();e.stop()};this.confirmObserver=this.confirm.bindAsEventListener(this);this.keyboardConfirmObserver=function(e){this.keyboardConfirm(e)}.bind(this)},
show:function(options){options=options||{};this.onConfirm=options.onConfirm||false;if(options.text)this.text.update(options.text);if(options.currentValue)this.textbox.value=options.currentValue;if(options.maxLength)this.textbox.maxLength=options.maxLength;if(options.confirmText)this.confirmButton.value=options.confirmText;if(options.cancelText)this.cancelLink.update(options.cancelText);Modalbox.show(this.promptBox,{title:options.title||"Are you sure?",width:options.width||400,overlayClose:false,cloneDomNode:false,
afterLoad:this.setObservers.bind(this),afterHide:this.removeObservers.bind(this)})},setObservers:function(e){this.cancelLink.observe("click",this.hideObserver);this.confirmButton.observe("click",this.confirmObserver);this.textbox.observe("keypress",this.keyboardConfirmObserver)},removeObservers:function(){this.cancelLink.stopObserving("click",this.hideObserver);this.confirmButton.stopObserving("click",this.confirmObserver);this.textbox.stopObserving("keypress",this.keyboardConfirmObserver)},confirm:function(){if(this.textbox.value.strip()==
"")return;if(this.onConfirm)this.onConfirm(this.textbox.value);Modalbox.hide()},keyboardConfirm:function(e){if(e.keyCode==Event.KEY_RETURN){e.stop();this.confirm()}}});
BrainstormJs.Controls.ModalBox.DropDownPrompt=Class.create({options:false,promptBox:false,text:false,select:false,confirmButton:false,cancelLink:false,hideObserver:false,confirmObserver:false,keyboardConfirmObserver:false,onConfirm:false,initialize:function(options){this.options=options;this.promptBox=new Element("div",{className:"promptBox",style:"display:none;"});this.text=(new Element("p",{className:"text"})).update("Text:");this.select=new Element("select",{className:"dropDown"});this.confirmButton=
new Element("input",{type:"button",value:"Confirm",className:"confirm"});this.cancelLink=(new Element("a",{href:"javascript:;",className:"cancel"})).update("Cancel");this.promptBox.insert(this.text);this.promptBox.insert(this.select);this.promptBox.insert("<hr/>");this.promptBox.insert(this.confirmButton);this.promptBox.insert(this.cancelLink);this.hideObserver=function(e){Modalbox.hide();e.stop()};this.confirmObserver=this.confirm.bindAsEventListener(this);this.keyboardConfirmObserver=function(e){this.keyboardConfirm(e)}.bind(this)},
show:function(options){options=options||{};this.onConfirm=options.onConfirm||false;if(options.text)this.text.update(options.text);if(options.confirmText)this.confirmButton.value=options.confirmText;if(options.cancelText)this.cancelLink.update(options.cancelText);if(options.choices){this.select.innerHTML="";this.select.insert(new Element("option",{"value":""}));for(var i=0,j=options.choices.length;i<j;i++){var choice=options.choices[i];if(options.ignoreChoice&&options.ignoreChoice==choice.value)continue;
var option=(new Element("option",{"value":choice.value})).update(choice.text);this.select.insert(option)}}Modalbox.show(this.promptBox,{title:options.title||"Are you sure?",width:options.width||400,overlayClose:false,cloneDomNode:false,afterLoad:this.setObservers.bind(this),afterHide:this.removeObservers.bind(this)})},setObservers:function(e){this.cancelLink.observe("click",this.hideObserver);this.confirmButton.observe("click",this.confirmObserver)},removeObservers:function(){this.cancelLink.stopObserving("click",
this.hideObserver);this.confirmButton.stopObserving("click",this.confirmObserver)},confirm:function(){if(this.select.value==""){alert("Please choose a value from the drop down list!");return}if(this.onConfirm)this.onConfirm({selectedValue:parseInt(this.select.value,10)});Modalbox.hide()}});
BrainstormJs.Controls.Pager=Class.create({list:false,currentPage:1,currentPageSize:false,changePageSizeEl:false,pages:false,breaks:false,lastPageNum:false,prevItem:false,nextItem:false,onChange:false,context:false,break1:false,break2:false,initialize:function(list,context,options){this.pages=new Array;this.breaks=[];this.context=context||"";this.list=$(list);this.onChange=options.onChange||false;this.changePageSizeEl=options.changePageSizeEl||false;this.currentPageSize=options.pageSize||false;var listItems=
this.list.select("li");this.break1=(new Element("li",{"class":"break"})).update("...");this.break2=(new Element("li",{"class":"break"})).update("...");for(var i=0,j=listItems.length;i<j;i++){var listItem=listItems[i];var linkElem=listItem.down("a");if(linkElem)this.bindLinkToPageChange(linkElem);if(listItem.hasClassName("previous")||listItem.hasClassName("previous-off"))this.prevItem=listItem;else if(listItem.hasClassName("next")||listItem.hasClassName("next-off")){this.nextItem=listItem;listItem.previous().addClassName("lastItem")}else{var pageNum=
parseInt((listItem.down("a")||listItem).innerHTML,10);if(listItem.hasClassName("active"))this.currentPage=pageNum;else linkElem.rel=pageNum;this.pages.push(listItem);this.lastPageNum=pageNum}}this.refreshPager();if(this.lastPageNum==false){if(this.list.visible())this.list.fade()}else this.list.appear()},refreshPager:function(){this.setPageLinks(this.getPageSet(this.pages.length,2,2));this.refreshNextPrev()},getPageSet:function(requiredPageLinks,requiredInitial,requiredFinal){var pageSet=new Array;
var lastPage=this.lastPageNum;if(requiredPageLinks>=lastPage){for(var i=1;i<=lastPage;i++)pageSet.push(i);return pageSet}var startPage=this.currentPage-Math.floor(requiredPageLinks/2);if(startPage<1)startPage=1;if(startPage+(requiredPageLinks-1)>lastPage)startPage=lastPage-requiredPageLinks+1;for(var i=0;i<requiredPageLinks;i++){var page=startPage+i;if(i<requiredInitial)page=i+1;if(i>=requiredPageLinks-requiredFinal)page=lastPage-(requiredPageLinks-i)+1;pageSet.push(page)}return pageSet},setPageLinks:function(pageNums){var lastPageNum=
0;var breaks=0;for(var i=0;i<pageNums.length;i++){var pageNum=pageNums[i];var pageElem=this.pages[i];this.renderPagerElem(pageElem,pageNum,pageNum);if(lastPageNum!=pageNum-1){breaks++;this.pages[i].insert({before:breaks==1?this.break1:this.break2})}lastPageNum=pageNum}if(breaks<2&&this.break2.parentNode)this.break2.remove();if(breaks<1&&this.break1.parentNode)this.break1.remove()},changePage:function(linkClicked,options){if(typeof linkClicked=="number")this.currentPage=linkClicked;else this.currentPage=
parseInt(linkClicked.rel,10);bsCommon.setState(this.context+"_page",this.currentPage);if(this.onChange){options=options||{};options.pageNum=this.currentPage;this.onChange(options)}this.refreshPager()},nextPage:function(options){if(this.currentPage<this.lastPageNum)this.changePage(this.currentPage+1,options)},renderPagerElem:function(parent,pageNum,label){var linkElem=parent.down("a")||false;var isLink=linkElem!=false;var shouldBeLink=pageNum!=false&&pageNum!=this.currentPage;var makeLink=!isLink&&
shouldBeLink;if(makeLink){linkElem=new Element("a",{href:"#",rel:pageNum});this.bindLinkToPageChange(linkElem);parent.update(linkElem)}if(shouldBeLink){linkElem.rel=pageNum;linkElem.update(label)}else parent.update(label);if(pageNum==this.currentPage)parent.addClassName("active");else parent.removeClassName("active")},bindLinkToPageChange:function(link){link.observe("click",function(e){this.changePage(e.element());e.stop()}.bind(this))},refreshNextPrev:function(){var prevLabel=(this.prevItem.down("a")||
this.prevItem).innerHTML;var nextLabel=(this.nextItem.down("a")||this.nextItem).innerHTML;if(this.currentPage>1){this.renderPagerElem(this.prevItem,parseInt(this.currentPage,10)-1,prevLabel);this.prevItem.removeClassName("previous-off");this.prevItem.addClassName("previous")}else{this.renderPagerElem(this.prevItem,false,prevLabel);this.prevItem.removeClassName("previous");this.prevItem.addClassName("previous-off")}if(this.currentPage<this.lastPageNum){this.renderPagerElem(this.nextItem,parseInt(this.currentPage,
10)+1,nextLabel);this.nextItem.removeClassName("next-off");this.nextItem.addClassName("next")}else{this.renderPagerElem(this.nextItem,false,nextLabel);this.nextItem.removeClassName("next");this.nextItem.addClassName("next-off")}}});if(typeof Control=="undefined")Control={};var $proc=function(proc){return typeof proc=="function"?proc:function(){return proc}};var $value=function(value){return typeof value=="function"?value():value};
Object.Event={extend:function(object){object._objectEventSetup=function(event_name){this._observers=this._observers||{};this._observers[event_name]=this._observers[event_name]||[]};object.observe=function(event_name,observer){if(typeof event_name=="string"&&typeof observer!="undefined"){this._objectEventSetup(event_name);if(!this._observers[event_name].include(observer))this._observers[event_name].push(observer)}else for(var e in event_name)this.observe(e,event_name[e])};object.stopObserving=function(event_name,
observer){this._objectEventSetup(event_name);if(event_name&&observer)this._observers[event_name]=this._observers[event_name].without(observer);else if(event_name)this._observers[event_name]=[];else this._observers={}};object.observeOnce=function(event_name,outer_observer){var inner_observer=function(){outer_observer.apply(this,arguments);this.stopObserving(event_name,inner_observer)}.bind(this);this._objectEventSetup(event_name);this._observers[event_name].push(inner_observer)};object.notify=function(event_name){this._objectEventSetup(event_name);
var collected_return_values=[];var args=$A(arguments).slice(1);try{for(var i=0;i<this._observers[event_name].length;++i)collected_return_values.push(this._observers[event_name][i].apply(this,args)||null)}catch(e){if(e==$break)return false;else throw e;}return collected_return_values};if(object.prototype){object.prototype._objectEventSetup=object._objectEventSetup;object.prototype.observe=object.observe;object.prototype.stopObserving=object.stopObserving;object.prototype.observeOnce=object.observeOnce;
object.prototype.notify=function(event_name){if(object.notify){var args=$A(arguments).slice(1);args.unshift(this);args.unshift(event_name);object.notify.apply(object,args)}this._objectEventSetup(event_name);var args=$A(arguments).slice(1);var collected_return_values=[];try{if(this.options&&this.options[event_name]&&typeof this.options[event_name]=="function")collected_return_values.push(this.options[event_name].apply(this,args)||null);var callbacks_copy=this._observers[event_name];for(var i=0;i<callbacks_copy.length;++i)collected_return_values.push(callbacks_copy[i].apply(this,
args)||null)}catch(e){if(e==$break)return false;else throw e;}return collected_return_values}}}};Element.addMethods({observeOnce:function(element,event_name,outer_callback){var inner_callback=function(){outer_callback.apply(this,arguments);Element.stopObserving(element,event_name,inner_callback)};Element.observe(element,event_name,inner_callback)}});
(function(){function wheel(event){var delta,element,custom_event;if(event.wheelDelta)delta=event.wheelDelta/120;else if(event.detail)delta=-event.detail/3;if(!delta)return;element=Event.extend(event).target;element=Element.extend(element.nodeType===Node.TEXT_NODE?element.parentNode:element);custom_event=element.fire("mouse:wheel",{delta:delta});if(custom_event.stopped){Event.stop(event);return false}}document.observe("mousewheel",wheel);document.observe("DOMMouseScroll",wheel)})();
var IframeShim=Class.create({initialize:function(){this.element=new Element("iframe",{style:"position:absolute;filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0);display:none",src:"javascript:void(0);",frameborder:0});$(document.body).insert(this.element)},hide:function(){this.element.hide();return this},show:function(){this.element.show();return this},positionUnder:function(element){var element=$(element);var offset=element.cumulativeOffset();var dimensions=element.getDimensions();this.element.setStyle({left:offset[0]+
"px",top:offset[1]+"px",width:dimensions.width+"px",height:dimensions.height+"px",zIndex:element.getStyle("zIndex")-1}).show();return this},setBounds:function(bounds){for(prop in bounds)bounds[prop]+="px";this.element.setStyle(bounds);return this},destroy:function(){if(this.element)this.element.remove();return this}});if(typeof Prototype=="undefined")throw"Control.Tabs requires Prototype to be loaded.";if(typeof Object.Event=="undefined")throw"Control.Tabs requires Object.Event to be loaded.";
Control.Tabs=Class.create({initialize:function(tab_list_container,options){if(!$(tab_list_container))throw"Control.Tabs could not find the element: "+tab_list_container;this.activeContainer=false;this.activeLink=false;this.containers=$H({});this.links=[];this.options={beforeChange:Prototype.emptyFunction,afterChange:Prototype.emptyFunction,hover:false,tracked:true,linkSelector:"li a",linkAttribute:"href",setClassOnContainer:false,activeClassName:"active",disabledClassName:"disabled",defaultTab:"first",
autoLinkExternal:true,targetRegExp:/#(.+)$/,showFunction:Element.show,hideFunction:Element.hide};Object.extend(this.options,options||{});if(this.options.tracked)Control.Tabs.instances.push(this);var filterLinks;switch(this.options.linkAttribute){case "href":case "src":filterLinks=function(link){return/^#/.test(link.getAttribute(this.options.linkAttribute).replace(window.location.href.split("#")[0],""))};break;default:if(typeof this.options.linkAttribute=="function")filterLinks=this.options.linkAttribute;
else filterLinks=function(link){return link.hasAttribute(this.options.linkAttribute)}}(typeof this.options.linkSelector=="string"?$(tab_list_container).select(this.options.linkSelector):this.options.linkSelector($(tab_list_container))).findAll(filterLinks.bind(this)).each(function(link){this.addTab(link)}.bind(this));this.containers.values().each(Element.hide);if(this.options.defaultTab=="first")this.setActiveTab(this.links.first());else if(this.options.defaultTab=="last")this.setActiveTab(this.links.last());
else this.setActiveTab(this.options.defaultTab);var targets=this.options.targetRegExp.exec(window.location);if(targets&&targets[1])targets[1].split(",").each(function(target){this.setActiveTab(this.links.find(function(link){return link.key==target}))}.bind(this));if(this.options.autoLinkExternal)$A(document.getElementsByTagName("a")).each(function(a){if(!this.links.include(a)){var clean_href=a.href.replace(window.location.href.split("#")[0],"");if(clean_href.substring(0,1)=="#")if(this.containers.keys().include(clean_href.substring(1)))$(a).observe("click",
function(event,clean_href){this.setActiveTab(clean_href.substring(1))}.bindAsEventListener(this,clean_href))}}.bind(this))},addTab:function(link){this.links.push(link);switch(this.options.linkAttribute){case "href":case "src":link.key=link.getAttribute(this.options.linkAttribute).replace(window.location.href.split("#")[0],"").split("#").last().replace(/#/,"");break;default:if(typeof this.options.linkAttribute=="function")link.key=this.options.linkAttribute(link);else link.key=link.getAttribute(this.options.linkAttribute)}var container=
this.options.tabs_container?this.options.tabs_container.down("#"+link.key):$(link.key);if(!container)throw"Control.Tabs: #"+link.key+" was not found on the page.";this.containers.set(link.key,container);link[this.options.hover?"onmouseover":"onclick"]=function(link){if(window.event)Event.stop(window.event);this.setActiveTab(link);return false}.bind(this,link)},getTab:function(link){if(!link&&typeof link=="undefined")return null;if(typeof link=="string")return this.getTab(this.links.find(function(_link){return _link.key==
link}));else if(typeof link=="number")return this.getTab(this.links[link]);else return this.containers.get(link.key)},setActiveTab:function(link){if(!link&&typeof link=="undefined")return;if(typeof link=="string")this.setActiveTab(this.links.find(function(_link){return _link.key==link}));else if(typeof link=="number")this.setActiveTab(this.links[link]);else if(!(this.options.setClassOnContainer?$(link.parentNode):link).hasClassName(this.options.disabledClassName)){if(link==this.activeLink)return;
if(this.notify("beforeChange",this.activeContainer,this.containers.get(link.key))===false)return;if(this.activeContainer)this.options.hideFunction(this.activeContainer);this.links.each(function(item){(this.options.setClassOnContainer?$(item.parentNode):item).removeClassName(this.options.activeClassName)}.bind(this));(this.options.setClassOnContainer?$(link.parentNode):link).addClassName(this.options.activeClassName);this.activeContainer=this.containers.get(link.key);this.activeLink=link;this.options.showFunction(this.containers.get(link.key));
this.notify("afterChange",this.containers.get(link.key))}},disableTab:function(link){if(!link&&typeof link=="undefined")return;if(typeof link=="string")this.disableTab(this.links.find(function(_link){return _link.key==link}));else if(typeof link=="number")this.disableTab(this.links[link]);else{if({"INPUT":true,"BUTTON":true,"SELECT":true,"TEXTAREA":true}[link.nodeName])link.disabled=true;(this.options.setClassOnContainer?$(link.parentNode):link).addClassName(this.options.disabledClassName)}},enableTab:function(link){if(!link&&
typeof link=="undefined")return;if(typeof link=="string")this.enableTab(this.links.find(function(_link){return _link.key==link}));else if(typeof link=="number")this.enableTab(this.links[link]);else{if({"INPUT":true,"BUTTON":true,"SELECT":true,"TEXTAREA":true}[link.nodeName])link.disabled=false;(this.options.setClassOnContainer?$(link.parentNode):link).removeClassName(this.options.disabledClassName)}},next:function(){this.links.each(function(link,i){if(this.activeLink==link&&this.links[i+1]){this.setActiveTab(this.links[i+
1]);throw $break;}}.bind(this))},previous:function(){this.links.each(function(link,i){if(this.activeLink==link&&this.links[i-1]){this.setActiveTab(this.links[i-1]);throw $break;}}.bind(this))},first:function(){this.setActiveTab(this.links.first())},last:function(){this.setActiveTab(this.links.last())}});Object.extend(Control.Tabs,{instances:[],findByTabId:function(id){return Control.Tabs.instances.find(function(tab){return tab.links.find(function(link){return link.key==id})})}});Object.Event.extend(Control.Tabs);
BrainstormJs.Controls.TabPane=Class.create({container:false,tabs:false,tabList:false,initialLoad:true,defaultTab:false,initialize:function(container,options){options=Object.extend(options||{});this.container=$(container);this.defaultTab=this.container.down("input.defaultTab").value;this.tabList=this.container.down("ul.tabs");var fxAfterSwitch=options.afterSwitch||false;var fxAfterAjaxLoad=options.fxAfterAjaxLoad||false;this.tabs=new Control.Tabs(this.container,{activeClassName:"selected",defaultTab:this.defaultTab,
setClassOnContainer:true,linkSelector:function(container){return container.down("ul").select("li a")},showFunction:function(tabContent){if(this.initialLoad){this.initialLoad=false;tabContent.show()}else{tabContent.setOpacity(0);tabContent.show();Effect.Appear(tabContent,{duration:0.5,from:0,to:1});var children=tabContent.childElements();var ajaxWrapper=children.length==1&&children[0].hasClassName("ajaxContentPane")?children[0]:null;if(ajaxWrapper)if(!tabContent.ajaxContentPane||!tabContent.ajaxContentPane.loaded){tabContent.ajaxContentPane=
new BrainstormJs.Controls.AjaxContentPane(ajaxWrapper);tabContent.ajaxContentPane.startLoading({dataMethod:function(){Brainstorm.Web.Services.Ajax.GetTabPaneContent(tabContent.identify(),function(content){tabContent.ajaxContentPane.insertContent(content);if(fxAfterAjaxLoad)fxAfterAjaxLoad(tabContent);tabContent.ajaxContentPane.showContent({fadeTransition:true})}.bind(this),bsCommon.ajaxCallError)}.bind(this),fadeTransition:true})}if(fxAfterSwitch)fxAfterSwitch(tabContent)}}.bind(this),hideFunction:Element.hide});
if(this.tabList.id&&this.tabList.id.length>0)this.tabList.tabs=this.tabs}});
BrainstormJs.Controls.ActivityFeed=Class.create({options:false,listType:false,contextId:false,earliestEventId:false,container:false,items:false,loadMoreArea:false,loadMoreLink:false,loadLessLink:false,spinner:false,numItemsToRemove:false,initialize:function(container,options){this.numItemsToRemove=10;this.options=options;this.container=$(container);this.items=this.container.down("div.activityItems");this.listType=parseInt(this.container.down("input.type").value,10);var contextIdInput=this.container.down("input.contextId");
this.contextId=contextIdInput?parseInt(contextIdInput.value,10):0;this.loadMoreArea=this.container.down("div.loadMoreArea");this.loadMoreLink=this.loadMoreArea.down("a.linkLoadMore");this.loadLessLink=null;this.spinner=this.loadMoreArea.down(".spinner");this.loadMoreLink.observe("click",function(e){this.showMore();e.stop()}.bind(this));this.refresh()},showMore:function(){this.loadMoreLink.hide();if(this.loadLessLink)this.loadLessLink.hide();this.spinner.show();Brainstorm.Web.Services.Ajax.LoadMoreActivity(this.listType,
this.earliestEventId,this.contextId,this.addNewItems.bind(this),bsCommon.ajaxCallError)},showLess:function(){this.loadMoreLink.hide();this.loadLessLink.hide();this.spinner.show();var tempContainer=new Element("div",{"class":"tempContainer"});var childElementsArr=this.items.childElements();var childElementCount=childElementsArr.length;var j=0;childElementsArr.reverse();for(var i=0;i<this.numItemsToRemove&&i<childElementCount-5;i++)childElementsArr[i].wrap(tempContainer);Effect.BlindUp(tempContainer,
{duration:0.5,afterFinish:function(){tempContainer.remove();this.refresh()}.bind(this)});this.spinner.hide();if(this.items.childElements().length>this.numItemsToRemove)this.loadLessLink.show();this.loadMoreLink.show()},addNewItems:function(newItems){if(!newItems){this.loadMoreArea.blindUp();return}var tempContainer=new Element("div",{"class":"tempContainer","style":"display:none;"});tempContainer.insert(newItems);this.items.insert(tempContainer);tempContainer.blindDown({afterFinish:function(){this.items.insert(tempContainer.innerHTML);
tempContainer.remove();bsCommon.scrollIfBelowFold(this.spinner,20,{afterFinish:function(){this.spinner.hide();if(!this.loadLessLink){this.loadLessLink=(new Element("a",{"class":"linkLoadLess","style":"display:visible;",href:"#"})).update("show less");this.loadMoreArea.insert(this.loadLessLink);this.loadLessLink.observe("click",function(e){this.showLess();e.stop()}.bind(this))}this.loadLessLink.show();this.loadMoreLink.show();if(!this.refreshFx)this.refreshFx=this.refresh.bind(this);this.refreshFx.defer()}.bind(this)})}.bind(this)})},
refresh:function(){if(typeof bsCommon!="undefined"&&bsCommon)bsCommon.wireContentPreviews();var hasEvents=this.findEarliestEventId();if(hasEvents)Effect.BlindDown(this.loadMoreArea,{duration:0.5})},findEarliestEventId:function(){if(this.items!=null){var lastListItem=this.items.immediateDescendants().last();this.earliestEventId=parseInt(lastListItem.id.split("_").last(),10);return true}return false}});
BrainstormJs.Controls.PersonSearch=Class.create({container:false,txtSearch:false,btnSearch:false,results:false,initialize:function(options){this.container=$(options.container);this.txtSearch=this.container.down("input.search");this.btnSearch=this.container.down("input.button");this.results=this.container.down("div.results");this.btnSearch.observe("click",function(e){this.startSearch();e.stop()}.bind(this));this.btnSearch.observe("keypress",this.onSearchKey.bind(this));this.txtSearch.observe("keypress",
this.onSearchKey.bind(this))},onSearchKey:function(e){if(e.keyCode==Event.KEY_RETURN){this.startSearch();e.stop()}},startSearch:function(){this.btnSearch.value="Please Wait ...";this.btnSearch.disabled=true;Brainstorm.Web.Services.Ajax.SearchForPeople(this.txtSearch.value.trim(),this.afterSearch.bind(this),bsCommon.ajaxCallError)},afterSearch:function(domElement){this.btnSearch.value="Search";this.btnSearch.disabled=false;this.results.innerHTML=domElement.HTML;this.results.appear()}});
function getUrlParam(name){name=name.replace(/[\[]/,"\\[").replace(/[\]]/,"\\]");var regexS="[\\?&]"+name+"=([^&#]*)";var regex=new RegExp(regexS);var results=regex.exec(window.location.href);if(results==null)return"";else return results[1]}function urldecode(str){return decodeURIComponent(str).replace(/\+/g,"%20")}Prototype.Browser.IE6=Prototype.Browser.IE&&parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5))==6;
Prototype.Browser.IE7=Prototype.Browser.IE&&parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5))==7;Prototype.Browser.IE8=Prototype.Browser.IE&&!Prototype.Browser.IE6&&!Prototype.Browser.IE7;Prototype.Browser.Chrome=!!navigator.userAgent.match("Chrome");Object.extend(Event,{KEY_SPACE:32,KEY_SHIFT:16,KEY_CTRL:17,KEY_ALT:18});
Element.addMethods({appear:function(element){var defaultOptions={duration:0.5,from:0,to:1};Effect.Appear(element,Object.extend(defaultOptions,arguments[1]||{}))},pulsate:function(element){var defaultOptions={pulses:2,duration:1};Effect.Pulsate(element,Object.extend(defaultOptions,arguments[1]||{}))},fade:function(element){var defaultOptions={duration:0.5,from:1,to:0};Effect.Fade(element,Object.extend(defaultOptions,arguments[1]||{}))},blindDown:function(element){var defaultOptions={duration:0.5};
Effect.BlindDown(element,Object.extend(defaultOptions,arguments[1]||{}))},blindUp:function(element){var defaultOptions={duration:0.5};Effect.BlindUp(element,Object.extend(defaultOptions,arguments[1]||{}))},lastDescendant:function(element){element=$(element).lastChild;while(element&&element.nodeType!=1)element=element.previousSibling;return $(element)}});Effect.Transitions.easeInExpo=function(pos){return pos==0?0:Math.pow(2,10*(pos-1))};
Effect.Transitions.easeOutExpo=function(pos){return pos==1?1:-Math.pow(2,-10*pos)+1};Effect.Transitions.easeInOutExpo=function(pos){if(pos==0)return 0;if(pos==1)return 1;if((pos/=0.5)<1)return 0.5*Math.pow(2,10*(pos-1));return 0.5*(-Math.pow(2,-10*--pos)+2)};Effect.Transitions.easeInCirc=function(pos){return-(Math.sqrt(1-pos*pos)-1)};Effect.Transitions.easeOutCirc=function(pos){return Math.sqrt(1-Math.pow(pos-1,2))};
Effect.Transitions.easeInOutCirc=function(pos){if((pos/=0.5)<1)return-0.5*(Math.sqrt(1-pos*pos)-1);return 0.5*(Math.sqrt(1-(pos-=2)*pos)+1)};hostName=window.location.hostname.strip(".");cookies=new CookieJar({expires:86400,path:"/",domain:hostName.indexOf(".")>0?"."+hostName:""});cookies.appendString=$F("Cookie_Prefix");
BrainstormJs.Common=Class.create({user:false,userId:false,tagSeparators:[","],isShiftPressed:false,isCtrlPressed:false,signedOutWarning:false,failedUserRequests:0,sessionCheckExecuter:false,confirmBox:false,textPromptBox:false,dropDownPromptBox:false,cookies:false,openFormCheck:true,tagToggleFx:false,growler:false,disabledLinkClass:"disabled",initialize:function(){var userId=$("BS_User_Id");this.userId=parseInt(userId.value,10);var url=this.getPageUrl();var isAdminPage=url.startsWith("/admin/");this.growler=
new k.Growler({location:"br"});if(!isAdminPage&&!url.startsWith("/signin.aspx"))this.initSessionChecker();this.confirmBox=new BrainstormJs.Controls.ModalBox.Confirm;this.textPromptBox=new BrainstormJs.Controls.ModalBox.TextPrompt;this.dropDownPromptBox=new BrainstormJs.Controls.ModalBox.DropDownPrompt;if(!isAdminPage){document.observe("keydown",this.onKeyDown.bind(this));document.observe("keyup",this.onKeyUp.bind(this))}window.onbeforeunload=this.confirmExit.bind();if(typeof MessageLogger!="undefined")if(typeof HumaneMessager!=
"undefined")HumaneMessager.setup(null,0.8);this.wireContentToggles();if(!isAdminPage){this.wireTabPanes();this.wireContentPreviews();this.wireHelpContent();this.wireRssFeedPopups();this.wireShareFollowControl();this.wireActivityFeeds();this.wireTagToggles();this.wireClassifiedHelpLinks();this.wireSlideouts();this.wirePersonSearch();var linkMyIdeas=$("linkMyIdeas");var myIdeas=$("myIdeasDropdown");if(linkMyIdeas&&myIdeas){new Tip(linkMyIdeas,myIdeas,{className:"myIdeasTip",style:"protoblue",hideOn:{element:"tip",
event:"keypress"},stem:"topMiddle",hook:{tip:"topMiddle",target:"bottomMiddle"},hideAfter:0.2,offset:{x:23,y:1}});Effect.Appear(linkMyIdeas,{duration:0.5})}if(typeof DD_belatedPNG!="undefined");var links=$$('a[href^="#"][href!="#"]');for(var i=0,j=links.length;i<j;i++){var link=links[i];if(link.hasClassName("tab")||link.hasClassName("columnName"))continue;var targetId=link.href.substring(link.href.indexOf("#")+1);if(targetId&&targetId.length>1){var target=$(targetId);if(target)link.observe("click",
function(e){var href=e.element().href;var el=$(href.substring(href.indexOf("#")+1));new Effect.ScrollTo(el.id,{duration:1.5,offset:-20,transition:Effect.Transitions.easeInOutExpo});e.stop()})}}var els=getUrlParam("nav");var scrl=getUrlParam("scrl");var target=els?$(els):false;if(target){if(scrl)new Effect.ScrollTo(target,{duration:1,offset:parseInt(scrl,10),transition:Effect.Transitions.easeInOutExpo});new Effect.Highlight(target,{delay:1.5,duration:1.5})}}},onKeyDown:function(e){if(e.keyCode==Event.KEY_CTRL)this.isCtrlPressed=
true;if(e.keyCode==Event.KEY_SHIFT)this.isShiftPressed=true},onKeyUp:function(e){if(e.keyCode==Event.KEY_CTRL)this.isCtrlPressed=false;if(e.keyCode==Event.KEY_SHIFT)this.isShiftPressed=false},confirmExit:function(e){if(bsCommon&&bsCommon.openFormCheck){var openForms=BrainstormForms.openForms;var formsWord=openForms==1?"form":"forms";var warning="You currently have "+openForms+" "+formsWord+" open. Your changes will be lost if you leave this page.";if(openForms>0)return warning}},alert:function(message,
title){Modalbox.alert(message,title?title:"Brainstorm Alert")},showError:function(errorMessage){var html=['<p class="text">',"  It looks like something went haywire under the hood.  An error report has been sent to the Brainstorm Team for investigation.","  We&#8217;re really sorry we let you down!","</p>",'<p class="text">',"  Please reload this page and attempt your request one more time.",'  If you see this error again, don&#8217;t hesitate to <a href="http://support.intuitbrainstorm.com/anonymous_requests/new" target="_blank">contact us</a>.',
"</p>"];if(errorMessage)html=html.concat(['<p class="text">',"  Error Message: <strong>"+errorMessage+"</strong>","</p>"]);Modalbox.alert(html.join("\n"),"Uh oh, that wasn't supposed to happen ...")},confirm:function(options){if(options.triggerEvent&&options.triggerEvent.ctrlKey==true){options.onConfirm();return}this.confirmBox.show(options)},prompt:function(options){this.textPromptBox.show(options)},promptDropDown:function(options){this.dropDownPromptBox.show(options)},showSuccess:function(message){this.growler.growl(message,
{header:"",life:5,speedout:1})},showMessage:function(message){this.growler.growl(message,{life:5})},processBrowserButton:function(newLocation,historyData){},ajaxCallError:function(error,callback){var stackTrace=error.get_stackTrace();var message=error.get_message();var statusCode=error.get_statusCode();var exceptionType=error.get_exceptionType();var timedout=error.get_timedOut();var errorMessage="Stack Trace: "+stackTrace+"<br/>"+"Service Error: "+message+"<br/>"+"Status Code: "+statusCode+"<br/>"+
"Exception Type: "+exceptionType+"<br/>"+"Timed out: "+timedout;if(typeof Modalbox!="undefined")bsCommon.showError(message);else alert("Unexpected error: "+errorMessage);if(callback&&typeof callback=="function")callback()},getUrlParam:function(name){name=name.replace(/[\[]/,"\\[").replace(/[\]]/,"\\]");var regexS="[\\?&]"+name+"=([^&#]*)";var regex=new RegExp(regexS);var results=regex.exec(window.location.href);if(results==null)return"";else return results[1]},getPageUrl:function(withQueryString){if(withQueryString)return window.location.href.toLowerCase();
return document.location.pathname.toLowerCase()},getAppUrl:function(){var url="";var protocol=document.location.protocol;var port=document.location.port;var hostname=document.location.hostname;url=protocol+"//"+hostname;if(port&&port.length>0)url+=":"+port;return url},addToDropDown:function(select,option,addToEnd){try{if(addToEnd)select.add(option,null);else select.add(option,select.options[0])}catch(e){if(addToEnd)select.add(option);else select.add(option,0)}},startButtonSpinner:function(linkButton,
message){linkButton.addClassName("workingLinkButton");linkButton.href="";var label=linkButton.down("span.label");label.addClassName("working");if(message)label.innerHTML=message},stopButtonSpinner:function(linkButton,message,markDone){if(!linkButton)return;linkButton.removeClassName("workingLinkButton");linkButton.href="#";var label=linkButton.down("span.label");label.removeClassName("working");if(message)label.innerHTML=message;if(markDone)label.addClassName("done")},scrollIfBelowFold:function(element,
offset,options){options=options||{};if(!element)return;var scrollOffsets=document.viewport.getScrollOffsets();var yFold=document.viewport.getHeight()+scrollOffsets.top;var yElem=element.cumulativeOffset()[1]+element.getHeight();if(offset)yElem+=offset;var doScroll=options.reverse?yElem<yFold:yElem>yFold;if(doScroll){var yScrollTo=options.scrollToTop?element.cumulativeOffset()[1]-offset:scrollOffsets.top+(yElem-yFold);new Effect.Tween(null,scrollOffsets.top,yScrollTo,{duration:0.8,afterFinish:function(){if(options&&
options.afterFinish)options.afterFinish(true)}},function(p){scrollTo(scrollOffsets.left,p.round())})}else if(options&&options.afterFinish)options.afterFinish(false)},scrollIfAboveFold:function(element,offset,options){options=options||{};options.reverse=true;this.scrollIfBelowFold(element,offset,options)},scrollTo:function(element,options){options=options||{};new Effect.ScrollTo(element,{duration:options.duration||1,offset:options.offset||0,delay:options.delay||0,transition:Effect.Transitions.easeInOutExpo})},
isAboveFold:function(element){var scrollOffsets=document.viewport.getScrollOffsets();var yFold=scrollOffsets.top;var yElem=element.cumulativeOffset()[1]+element.getHeight();return yElem<yFold},isOnScreen:function(element){var scrollOffsets=document.viewport.getScrollOffsets();var screenHeight=document.viewport.getHeight();var minVisibleY=scrollOffsets.top;var maxVisibleY=minVisibleY+screenHeight;var elementTopY=element.cumulativeOffset().top;return elementTopY>minVisibleY&&elementTopY<maxVisibleY},
incrementDomInt:function(element,highlight){if(!element)return;var previousCount=parseInt(element.innerHTML.strip(),10);element.innerHTML=previousCount+1+"";if(highlight)new Effect.Highlight(element,{delay:0.5})},wireTabPanes:function(){var tabPanes=$$("div.tabPane");for(var i=0,j=tabPanes.length;i<j;i++){var paneDiv=tabPanes[i];if(paneDiv.hasClassName("manualWire"))continue;try{var tabPane=new BrainstormJs.Controls.TabPane(paneDiv)}catch(e){console.error("Failed to initialize tab pane: %o, Error: %o",
paneDiv,e)}}},wireContentToggles:function(){var toggles=$$("a.toggleContent");var behavior=function(e){this.toggleContent(e.element());e.stop()}.bind(this);for(var i=0,j=toggles.length;i<j;i++)toggles[i].observe("click",behavior)},wireRssFeedPopups:function(){var rssInfoTipLinks=$$("div.subscriptionLinks a.rssPopupTrigger");if(rssInfoTipLinks.length>0){var rssPopupContent=$$("div.subscriptionLinks div.rssPopupContent")[0].innerHTML;var rssInfoTemplate=new Template(rssPopupContent);for(var i=0,j=rssInfoTipLinks.length;i<
j;i++){var popupTrigger=rssInfoTipLinks[i];var rssFeedUrl=popupTrigger.href;popupTrigger.href="javascript:;";var popupContent=rssInfoTemplate.evaluate({feedUrl:rssFeedUrl});new Tip(popupTrigger,popupContent,{title:"Subscribe to RSS feed",style:"darkgrey",className:"rssPopup",closeButton:true,showOn:"click",hideOn:{element:"closeButton",event:"click"},hideAfter:15,stem:"bottomLeft",hook:{target:"bottomLeft",tip:"bottomLeft"},offset:{x:-1,y:-8},width:260});popupTrigger.observe("prototip:shown",function(){Effect.Fade(this,
{duration:0.5,from:1,to:0.5})});popupTrigger.observe("prototip:hidden",function(){Effect.Appear(this,{duration:0.5,from:0.5,to:1})})}}},wireHelpContent:function(){var helpLinks=$$("a.helpLink");for(var i=0,j=helpLinks.length;i<j;i++){var helpLink=helpLinks[i];var helpContent=helpLink.next("div.helpContent");if(helpContent){new Tip(helpLink,helpContent.innerHTML,{title:helpLink.rel||"Help",style:"darkgrey",className:"helpPopup",closeButton:false,showOn:"click",hideOn:"mouseout",hideAfter:15,stem:"topRight",
hook:{target:"bottomLeft",tip:"topRight"},offset:{x:13,y:0},width:278});helpLink.observe("prototip:shown",function(){try{this.addClassName("activeHelpLink");BrainstormJs.Analytics.scTrackAction("help",helpLink.rel||"untitled")}catch(error){BrainstormJs.LogScriptError(error)}});helpLink.observe("prototip:hidden",function(){this.removeClassName("activeHelpLink")});helpLink.appear()}}},wireShareFollowControl:function(){var shareFollowDiv=$("shareFollow");if(shareFollowDiv)var shareFollowControl=new BrainstormJs.Controls.ShareFollow(shareFollowDiv)},
wireActivityFeeds:function(container){var feedContainers=container!=null?container.select("div.activityFeed"):$$("div.activityFeed");for(var i=0,j=feedContainers.length;i<j;i++)var feedControl=new BrainstormJs.Controls.ActivityFeed(feedContainers[i])},wireTagToggles:function(){var tagToggles=$$("div.tagAccordion div.tagName a.unboundToggle");if(!this.tagToggleFx)this.tagToggleFx=function(e){this.toggleTagObjects(e.element());e.stop()}.bindAsEventListener(this);for(var i=0,j=tagToggles.length;i<j;i++){var toggle=
tagToggles[i];toggle.observe("click",this.tagToggleFx);toggle.removeClassName("unboundToggle")}},toggleTagObjects:function(linkClicked){var content=linkClicked.up("div.tagName").next("div.tagObjects");if(content.visible())content.blindUp();else content.blindDown()},wireClassifiedHelpLinks:function(){var helpLinks=$$("div.classified a.unboundFillClassifiedLink");var fxOnHelp=function(e){this.onOfferHelp(e.element());e.stop()}.bind(this);for(var i=0,j=helpLinks.length;i<j;i++){var helpLink=helpLinks[i];
helpLink.observe("click",fxOnHelp);helpLink.removeClassName("unboundFillClassifiedLink")}},onOfferHelp:function(linkClicked){var classified=linkClicked.up("div.classifiedItem[id]");if(!classified){classified=linkClicked.up("div.classified[id]");if(!classified){bsCommon.alert("Oops ... Could not locate classified.");return}}var classifiedId=bsCommon.parseObjectGuid(classified.id).id;var helpArea=classified.down("div.helpArea");var formContainer=helpArea.down("div.helpFormContainer");var profile={objectType:"Idea",
id:parseInt(linkClicked.rel,10)};var joinTeamForm=new BrainstormJs.Forms.JoinTeamForm(profile,{parentContainer:formContainer,openLinks:[linkClicked],bindOpenLinks:false,createTitle:"Offer to help this team",classifiedId:classifiedId});helpArea.show();joinTeamForm.showForm({linkClicked:linkClicked})},wireSlideouts:function(){var slideoutCloseButtons=$$("div.slideout div.slideoutTitle a.close");var fxCloseSlideout=function(e){bsCommon.closeSlideout(e.element());e.stop()};for(var i=0,j=slideoutCloseButtons.length;i<
j;i++){var button=slideoutCloseButtons[i];button.observe("click",fxCloseSlideout)}},wireSubscriptionCheckboxes:function(){var fxChangeSubscription=this.changeSubscription.bind(this);var subscriptionCheckboxes=$$("input.unboundSubscriptionCheck");if(subscriptionCheckboxes&&subscriptionCheckboxes.length&&subscriptionCheckboxes.length>0)for(var i=0,j=subscriptionCheckboxes.length;i<j;i++){var checkbox=subscriptionCheckboxes[i];checkbox.observe(Prototype.Browser.IE?"click":"change",fxChangeSubscription);
checkbox.checked=checkbox.hasClassName("checked");checkbox.disabled=false;checkbox.removeClassName("unboundSubscriptionCheck")}},changeSubscription:function(e){var checkbox=e.element();var parts=checkbox.id.split("_");var objType=parts[1];var objId=parts[2];var frequency=parts[3];var enable=checkbox.checked;Brainstorm.Web.Services.Ajax.UpdateSubscription(objType,objId,frequency,enable,bsCommon.subscriptionUpdated,bsCommon.ajaxCallError,checkbox)},subscriptionUpdated:function(appendTagMessage,checkbox){var tableCell=
checkbox.up().up();var tableRow=tableCell.up();var subscribed=checkbox.checked;new Effect.Highlight(tableCell,{duration:1,startcolor:"#cdffa9"});bsCommon.subscriptionMessage(appendTagMessage,subscribed)},subscriptionMessage:function(appendTagMessage,subscribed){var messagesSub=["You're now subscribed. Way to go!","Your subscription request has been carefully hand-delivered to our servers.","Thanks for subscribing! You are now officially awesome!","Nice job! Studies show that people who follow Brainstorm activity are totally awesome.",
"Our email robots are hard at work getting your email notifications ready."];var messagesUnsub=["Aw shucks... we're sad to see you go...","You've been unsubscribed.","Sorry if we bugged you with too much email!"];var messages=subscribed?messagesSub:messagesUnsub;var message=messages[Math.floor(Math.random()*messages.length)];if(subscribed)message+=appendTagMessage;bsCommon.showSuccess(message)},openSlideout:function(linkClicked,skipBlindDown){if(linkClicked.tagName.toUpperCase()!="A")linkClicked=
linkClicked.up("a");if(!linkClicked.rel)return;if(bsCommon.shakeIfDisabled(linkClicked))return;bsCommon.setButton(linkClicked,false);if(!skipBlindDown)$(linkClicked.rel).blindDown()},closeSlideout:function(linkClicked){if(linkClicked.rel!="")bsCommon.setButton($(linkClicked.rel),true);linkClicked.up("div.slideout").blindUp()},setButton:function(button,enable){if(enable){button.removeClassName(this.disabledLinkClass);button.appear({from:0.5})}else if(!button.hasClassName(this.disabledLinkClass)){button.addClassName(this.disabledLinkClass);
button.fade({to:0.5})}},wirePersonSearch:function(){var personSearchDivs=$$("div.personSearch");for(var i=0;i<personSearchDivs.length;i++)new BrainstormJs.Controls.PersonSearch({container:personSearchDivs[i]})},serializeSortable:function(sortableElement){var objectOrder=[];var parts=Sortable.serialize(sortableElement).split("&");for(var i=0,j=parts.length;i<j;i++)objectOrder.push(parseInt(parts[i].split("=")[1],10));return objectOrder},showPageIndicator:function(message){var indicator=$("pageLoadIndicator");
indicator.innerHTML=message;Effect.Fade(indicator,{duration:0.5})},toggleContent:function(linkClicked){var contentId=linkClicked.rel;var content=contentId?$(contentId):linkClicked.previous();this.toggleElement(content,linkClicked)},toggleElement:function(element,link,showText,hideText){if(!element)return;showText=showText||"show";hideText=hideText||"hide";if(element.visible()){Effect.BlindUp(element,{duration:0.5,afterFinish:function(){element.hide()}});Effect.Appear(link,{duration:0.5,from:0,to:1});
link.innerHTML=showText}else{Effect.BlindDown(element,{duration:0.5});Effect.Appear(link,{duration:0.5,from:0,to:1});link.innerHTML=hideText}},parseObjectGuid:function(guid){var elementid=guid.id||guid;var parts=elementid.split("_");var objectType=parts[0];var objectId=parseInt(parts[1],10);return{type:objectType,id:objectId}},isInteger:function(num){return num%1==0},getRequestToken:function(){return $F("CSRF_RequestToken")||""},initSessionChecker:function(){var url=this.getPageUrl();this.failedUserRequests=
0;if(url.indexOf("signin.aspx")>=0)return;this.signedOutWarning=$("signedOutWarning");var logBackLink=$("logMeBack");var fxUpdateSessionWarning=this.updateSessionWarning.bind(this);var requestToken=this.getRequestToken();logBackLink.observe("click",function(e){Brainstorm.Web.Services.Ajax.RenewCookie(requestToken,(new Date).getTimezoneOffset(),fxUpdateSessionWarning,function(){});e.stop()});this.checkInterval=30;var fxPeriodicTask=function(pe){var minutesUTCOffset=(new Date).getTimezoneOffset();var utcCookieExpiryString=
$F("User_Cookie_Expiry_UTC");var currentDate=new Date;var cookieExpiry=false;if(utcCookieExpiryString!="")cookieExpiry=new Date(utcCookieExpiryString+" GMT");if(cookieExpiry!=null){var warningWindow=10*60*1E3;var expiryMs=cookieExpiry.getTime()-currentDate.getTime();if(expiryMs<warningWindow&&expiryMs>0){var secondsLeft=expiryMs/1E3;console.info("cookie is about to expire: "+secondsLeft+" s");var timeLeft="";if(secondsLeft<60)timeLeft=Math.round(secondsLeft)+" seconds";else{var minutes=Math.round(secondsLeft/
60);if(minutes==1)timeLeft="one minute";else timeLeft=minutes+" minutes"}if(!this.signedOutWarning.visible())Effect.BlindDown(this.signedOutWarning,{duration:1,afterFinish:function(){this.pulsateSignOutWarning()}.bind(this)});else{this.growler.warn("You will be logged out in "+timeLeft+".",{length:10});Effect.ScrollTo(this.signedOutWarning)}}else if(expiryMs<1E4){console.info("cookie expired: "+expiryMs/1E3+" s");this.displaySignedOutMsg()}}}.bind(this);window.setTimeout(function(){fxPeriodicTask()}.bind(this),
100);this.sessionCheckExecuter=new PeriodicalExecuter(fxPeriodicTask,this.checkInterval)},pulsateSignOutWarning:function(){var pulsateOptions={pulses:3,duration:3,from:0.5,to:1};Effect.ScrollTo(this.signedOutWarning);Effect.Pulsate(this.signedOutWarning,pulsateOptions)},displaySignedOutMsg:function(){this.alert("For your security we have logged you out of your account due to inactivity. Please refresh the page to sign back into Brainstorm.");this.sessionCheckExecuter.stop();this.signedOutWarning.down().down().update("You are no longer signed into Brainstorm. Refresh the page to continue using Brainstorm.");
if(!this.signedOutWarning.visible())Effect.BlindDown(this.signedOutWarning,{duration:1});Effect.ScrollTo(this.signedOutWarning);this.pulsateSignOutWarning()},updateSessionWarning:function(user){if(user){this.failedUserRequests=0;$("User_Cookie_Expiry_UTC").value=user.CookieExpiry;if(this.signedOutWarning.visible())Effect.BlindUp(this.signedOutWarning,{duration:1,afterFinish:function(){bsCommon.showMessage("You have successfully signed back in.")}})}else if(!user)this.displaySignedOutMsg()},setState:function(key,
value){cookies.put(key,value)},getState:function(key){var retVal=null;if(!retVal){var fromCookies=cookies.get(key);if(fromCookies&&fromCookies!="")retVal=fromCookies}return retVal},clearState:function(key){cookies.remove(key)},shakeIfDisabled:function(link){if(link.hasClassName(this.disabledLinkClass)){link.shake({distance:3});return true}return false},wireContentPreviews:function(){var previewToggles=$$("a.unboundPreviewToggle");var toggleFx=this.toggleContentPreview.bind(this);for(var i=0,j=previewToggles.length;i<
j;i++){var toggle=previewToggles[i];toggle.observe("click",function(e){toggleFx(e.element());e.stop()});toggle.removeClassName("unboundPreviewToggle")}},toggleContentPreview:function(linkClicked){if(linkClicked.tagName!="A")linkClicked=linkClicked.up("a");var preview=linkClicked.next("div.contentPreview");if(!preview){linkClicked.fade();return}var actionText=linkClicked.down("span.action");if(preview.visible()){preview.fade();actionText.innerHTML="show"}else{preview.appear();actionText.innerHTML=
"hide"}},getLink:function(linkClicked){if(linkClicked.tagName.toLowerCase()!="a")return linkClicked.up("a");return linkClicked},removeDropDownChoice:function(choices,removeValue){var choiceToRemove=false;for(var i=0,j=choices.length;i<j;i++){var choice=choices[i];if(choice.value==removeValue){choiceToRemove=choice;break}}if(choiceToRemove)choices=choices.without(choiceToRemove);return choices},updateTabCount:function(countSpan,offsetBy,absoluteCount,highlightCount){var countBefore=parseInt(countSpan.innerHTML,
10);var countAfter=offsetBy||offsetBy===0?countBefore+offsetBy:absoluteCount;if(countBefore==countAfter)return;if(countAfter<0)countAfter=0;countSpan.innerHTML=countAfter;if(highlightCount&&highlightCount>0)for(var i=0;i<highlightCount;i++)new Effect.Highlight(countSpan,{queue:{position:"end",scope:"tabcountscope"}})},getDateString:function(date){if(!date)return"";return date.getFullYear().toString()+"-"+(date.getMonth()+1<10?"0"+(date.getMonth()+1).toString():(date.getMonth()+1).toString())+"-"+
(date.getDate()<10?"0"+date.getDate().toString():date.getDate().toString())},onDialogStart:function(){this.clear()},onFileQueued:function(file){this.setValue(file.name)},onFileQueueError:function(file,errorCode,message){switch(errorCode){case SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED:alert("You have attempted to queue too many files.\n"+(message===0?"You have reached the upload limit.":"You may select "+(message>1?"up to "+message+" files.":"one file.")));return;case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:alert("The file you selected is too big. The maximum file upload size is "+
this.fileSizeLimit+".");return;case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:alert("The file you selected is empty.  Please select another file.");return;case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:alert("The file you choose is not an allowed file type.");return;default:alert("An error occurred in the upload. Try again later.");return}},onDialogComplete:function(numFilesSelected,numFilesQueued){},onStartUpload:function(file){},onUpdateProgress:function(file,bytesLoaded,bytesTotal){if(this.showProgress){var percent=
Math.ceil(bytesLoaded/bytesTotal*100);this.progressBar.setProgress(percent)}},onUploadSuccess:function(file,documentInfo){var parts=documentInfo.split(";");var documentId=parts[0];var mimeType=parts[1];var fileSize=parts[2];this.uploadFinishedCallback(documentId,mimeType,fileSize,file)},onUploadError:function(file,errorCode,message){this.clear();switch(errorCode){case SWFUpload.UPLOAD_ERROR.MISSING_UPLOAD_URL:alert("There was a configuration error.  You will not be able to upload a file at this time.");
return;case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:alert("You may only upload 1 file.");return;case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED:case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED:break;default:return}switch(errorCode){case SWFUpload.UPLOAD_ERROR.HTTP_ERROR:alert("Upload Error");break;case SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED:alert("Upload Failed.");break;case SWFUpload.UPLOAD_ERROR.IO_ERROR:alert("Server (IO) Error");break;case SWFUpload.UPLOAD_ERROR.SECURITY_ERROR:alert("Security Error");
break;case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED:break;case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED:alert("Upload Stopped");break}},fileUploadSettings:function(){var debugMode=$("BS_DebugSwfUpload")?$F("BS_DebugSwfUpload")=="1":false;return{flash_url:"/Scripts/Libraries/SWFUpload/swfupload.swf",flash9_url:"/Scripts/Libraries/SWFUpload/swfupload_fp9.swf",upload_url:"/Services/UploadFile.aspx",post_params:{"ASPSESSID":$F("ASP_SessionID")},button_image_url:"/Images/btn_browse.gif",button_disabled:false,
button_cursor:SWFUpload.CURSOR.HAND,button_window_mode:SWFUpload.WINDOW_MODE.TRANSPARENT,button_action:SWFUpload.BUTTON_ACTION.SELECT_FILES,prevent_swf_caching:true,debug:debugMode}},setAutoScroll:function(elem){var viewableWidth=elem.getWidth();var totalWidth=elem.scrollWidth;var targetScrollOffset=totalWidth-viewableWidth;var scrollInterval=-1;var scrollBackInterval=-1;var disableAutoscroll=false;if(targetScrollOffset>0){var fnScrollBack=function(){elem.scrollLeft--;if(elem.scrollLeft<=0){scrollInterval=
-1;clearInterval(scrollBackInterval)}};var fnScroll=function(){elem.scrollLeft++;if(elem.scrollLeft>=targetScrollOffset){clearInterval(scrollInterval);setTimeout(function(){if(!disableAutoscroll&&elem.scrollLeft>0)scrollBackInterval=setInterval(fnScrollBack,30)},3E3)}};elem.observe("mouseover",function(){if(scrollInterval==-1&&!disableAutoscroll)scrollInterval=setInterval(fnScroll,30)});elem.observe("click",function(){clearInterval(scrollInterval);clearInterval(scrollBackInterval);disableAutoscroll=
true})}},setHoverFunction:function(elem,fxHover,fxUnHover){var lazilyApplied=elem.onmouseover!=null;elem=$(elem);elem.onmouseover=fxHover;elem.onmouseout=fxUnHover;if(lazilyApplied)fxHover()},setHoverClassName:function(elem,className){this.setHoverFunction(elem,function(event){this.addClassName(className)}.bind($(elem)),function(event){this.removeClassName(className)}.bind($(elem)))}});
var BrainstormPages={constructors:new Hash,register:function(instanceClass,pageUrls){var urls=(new Array(pageUrls)).flatten();for(var i=0;i<urls.length;i++)this.constructors.set(urls[i].toLowerCase(),instanceClass)},instantiateCurrentPage:function(){url=bsCommon.getPageUrl();var pageConstructor=this.constructors.get(url);if(!pageConstructor){console.warn("Could not instantiate page: "+url);return}currentPageInstance=new pageConstructor}};
BrainstormJs.InitializeApplication=function(){if(typeof BrainstormJs=="undefined"){alert("BrainstormJs namespace not defined. Scripts will not be loaded.");return}if(typeof BrainstormJs.Common=="undefined"){alert("Oops! Brainstorm can't find its scripts ... they must be around here somewhere ...");return}bsCommon=new BrainstormJs.Common;BrainstormPages.instantiateCurrentPage();var sidePanel=new BrainstormJs.Controls.SidePanel;delete BrainstormJs.InitializeApplication};
document.observe("dom:loaded",function(){try{BrainstormJs.InitializeApplication()}catch(error){BrainstormJs.LogScriptError(error)}});BrainstormJs.LogScriptError=function(error){console.error(error);Brainstorm.Web.Services.Ajax.LogScriptError(document.location!=null?document.location.href:"unknown",error.name,error.message,null,null)};var Validator=Class.create();
Validator.prototype={initialize:function(className,error,test,options){if(typeof test=="function"){this.options=$H(options);this._test=test}else{this.options=$H(test);this._test=function(){return true}}this.error=error||"Validation failed.";this.className=className},test:function(v,elm){return this._test(v,elm)&&this.options.all(function(p){return Validator.methods[p.key]?Validator.methods[p.key](v,elm,p.value):true})}};
Validator.methods={pattern:function(v,elm,opt){return Validation.get("IsEmpty").test(v)||opt.test(v)},minLength:function(v,elm,opt){return v.length>=opt},maxLength:function(v,elm,opt){return v.length<=opt},min:function(v,elm,opt){return v>=parseFloat(opt)},max:function(v,elm,opt){return v<=parseFloat(opt)},notOneOf:function(v,elm,opt){return $A(opt).all(function(value){return v!=value})},oneOf:function(v,elm,opt){return $A(opt).any(function(value){return v==value})},is:function(v,elm,opt){return v==
opt},isNot:function(v,elm,opt){return v!=opt},equalToField:function(v,elm,opt){return v==$F(opt)},notEqualToField:function(v,elm,opt){return v!=$F(opt)},include:function(v,elm,opt){return $A(opt).all(function(value){return Validation.get(value).test(v,elm)})}};var Validation=Class.create();
Validation.prototype={initialize:function(form,options){this.options=Object.extend({onSubmit:true,stopOnFirst:false,immediate:false,focusOnError:true,useTitles:false,onFormValidate:function(result,form){},onElementValidate:function(result,elm){}},options||{});this.form=$(form);if(this.options.onSubmit)Event.observe(this.form,"submit",this.onSubmit.bind(this),false);if(this.options.immediate){var useTitles=this.options.useTitles;var callback=this.options.onElementValidate;Form.getElements(this.form).each(function(input){Event.observe(input,
"blur",function(ev){var element=ev.element();Validation.validate(element,{useTitle:useTitles,onElementValidate:callback})})})}},onSubmit:function(ev){if(!this.validate())Event.stop(ev)},validate:function(){var result=false;var useTitles=this.options.useTitles;var callback=this.options.onElementValidate;var formElements=Form.getElements(this.form);var directElements=new Array;for(var i=0,j=formElements.length;i<j;i++){var formElement=formElements[i];var disabledFieldDiv=formElement.up("div.hiddenField");
if(!disabledFieldDiv){var parentForm=formElement.up("div.baseForm");if(parentForm===this.form)directElements.push(formElement)}}formElements=directElements;if(this.options.stopOnFirst)result=directElements.all(function(elm){return Validation.validate(elm,{useTitle:useTitles,onElementValidate:callback})});else result=directElements.collect(function(elm){return Validation.validate(elm,{useTitle:useTitles,onElementValidate:callback})}).all();if(!result&&this.options.focusOnError){var firstElement=directElements.findAll(function(elm){return $(elm).hasClassName("validation-failed")}).first();
if(firstElement)try{firstElement.focus()}catch(e){}}this.options.onFormValidate(result,this.form);return result},reset:function(){Form.getElements(this.form).each(Validation.reset)}};
Object.extend(Validation,{validate:function(elm,options){options=Object.extend({useTitle:false,onElementValidate:function(result,elm){}},options||{});elm=$(elm);if(elm.hasClassName("noValidation"))return true;var cn=elm.classNames();return result=cn.all(function(value){var test=Validation.test(value,elm,options.useTitle);options.onElementValidate(test,elm);return test})},test:function(name,elm,useTitle){var v=Validation.get(name);var prop="__advice"+name.camelize();try{if(Validation.isVisible(elm)&&
!v.test($F(elm),elm)){if(!elm[prop]){var advice=Validation.getAdvice(name,elm);if(advice==null){var errorMsg=useTitle?elm&&elm.title?elm.title:v.error:v.error;advice='<span class="validation-advice" id="advice-'+name+"-"+Validation.getElmID(elm)+'" style="display:none; color: red;">'+errorMsg+"</span>";switch(elm.type.toLowerCase()){case "checkbox":var p=elm.parentNode;var advice='<span class="validation-advice" id="advice-'+name+"-"+Validation.getElmID(elm)+'" style="display:none; color: red;">* '+
errorMsg+"</span>";var newEl=(new Element("div",{"style":"padding-top: 4px"})).update(advice);new Insertion.Bottom(p,newEl);break;case "radio":var p=elm.parentNode;if(p)new Insertion.Bottom(p,advice);else new Insertion.After(elm,advice);break;default:var titleDiv=elm.previous("div.fieldTitle");if(!titleDiv&&(elm.hasClassName("maininput")||elm.hasClassName("textbox")))titleDiv=elm.up("div.multiCompleter").previous("div.fieldTitle");if(!titleDiv&&elm.hasClassName("file"))titleDiv=elm.up("div.fileWrapper").previous("div.fieldTitle");
if(!titleDiv&&elm.hasClassName("multidropdownselect"))titleDiv=elm.up("div.multiDropDownList").previous("div.fieldTitle");if(!titleDiv&&elm.hasClassName("starvalue"))titleDiv=elm.up("div.ratingstarsfield").down("div.validator");titleDiv.insert(advice)}advice=Validation.getAdvice(name,elm)}if(typeof Effect=="undefined")advice.show();else{Effect.Appear(advice,{duration:0.5});Effect.Pulsate(elm,{pulses:2,duration:1.4,from:0.4,to:1})}}elm[prop]=true;elm.removeClassName("validation-passed");elm.addClassName("validation-failed");
return false}else{if(elm.hasClassName("validation-ignore"))return true;var advice=Validation.getAdvice(name,elm);if(advice!=null)if(typeof Effect=="undefined")advice.hide();else Effect.Fade(advice,{duration:0.3});elm[prop]="";elm.removeClassName("validation-failed");elm.addClassName("validation-passed");return true}}catch(e){throw e;}},isVisible:function(elm){return true;while(elm.tagName!="BODY"){if(!$(elm).visible())return false;elm=elm.parentNode}return true},getAdvice:function(name,elm){return $("advice-"+
name+"-"+Validation.getElmID(elm))||$("advice-"+Validation.getElmID(elm))},getElmID:function(elm){return elm.id?elm.id:elm.name},reset:function(elm){elm=$(elm);var cn=elm.classNames();cn.each(function(value){var prop="__advice"+value.camelize();if(elm[prop]){var advice=Validation.getAdvice(value,elm);advice.hide();elm[prop]=""}elm.removeClassName("validation-failed");elm.removeClassName("validation-passed")})},add:function(className,error,test,options){var nv={};nv[className]=new Validator(className,
error,test,options);Object.extend(Validation.methods,nv)},addAllThese:function(validators){var nv={};$A(validators).each(function(value){nv[value[0]]=new Validator(value[0],value[1],value[2],value.length>3?value[3]:{})});Object.extend(Validation.methods,nv)},get:function(name){return Validation.methods[name]?Validation.methods[name]:Validation.methods["_LikeNoIDIEverSaw_"]},methods:{"_LikeNoIDIEverSaw_":new Validator("_LikeNoIDIEverSaw_","",{})}});
Validation.add("IsEmpty","",function(v){return v==null||v.length==0});
Validation.addAllThese([["required","This field is required",function(v){return!Validation.get("IsEmpty").test(v)}],["required-star","Please choose a star value",function(v){return!Validation.get("IsEmpty").test(v)}],["validate-number","Please enter a valid number in this field.",function(v){return Validation.get("IsEmpty").test(v)||!isNaN(v)&&!/^\s+$/.test(v)}],["validate-digits","Please use numbers only in this field. please avoid spaces or other characters such as dots or commas.",function(v){return Validation.get("IsEmpty").test(v)||
!/[^\d]/.test(v)}],["validate-alpha","Please use letters only (a-z) in this field.",function(v){return Validation.get("IsEmpty").test(v)||/^[a-zA-Z]+$/.test(v)}],["validate-alphanum","Please use only letters (a-z) or numbers (0-9) only in this field. No spaces or other characters are allowed.",function(v){return Validation.get("IsEmpty").test(v)||!/\W/.test(v)}],["validate-date","Please enter a valid date.",function(v){var test=new Date(v);return Validation.get("IsEmpty").test(v)||!isNaN(test)}],
["validate-email","Please enter a valid email address. For example fred@domain.com .",function(v){return Validation.get("IsEmpty").test(v)||/\w{1,}[@][\w\-]{1,}([.]([\w\-]{1,})){1,3}$/.test(v)}],["validate-url","Please enter a valid URL",function(v){return Validation.get("IsEmpty").test(v)||/^(([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+)(:(\d+))?\/?/i.test(v)}],["validate-date-au","Please use this date format: dd/mm/yyyy. For example 17/03/2006 for the 17th of March, 2006.",function(v){if(Validation.get("IsEmpty").test(v))return true;
var regex=/^(\d{2})\/(\d{2})\/(\d{4})$/;if(!regex.test(v))return false;var d=new Date(v.replace(regex,"$2/$1/$3"));return parseInt(RegExp.$2,10)==1+d.getMonth()&&parseInt(RegExp.$1,10)==d.getDate()&&parseInt(RegExp.$3,10)==d.getFullYear()}],["validate-currency-dollar","Please enter a valid $ amount. For example $100.00 .",function(v){return Validation.get("IsEmpty").test(v)||/^\$?\-?([1-9]{1}[0-9]{0,2}(\,[0-9]{3})*(\.[0-9]{0,2})?|[1-9]{1}\d*(\.[0-9]{0,2})?|0(\.[0-9]{0,2})?|(\.[0-9]{1,2})?)$/.test(v)}],
["validate-selection","Please choose one",function(v,elm){return elm.options?elm.selectedIndex>0:!Validation.get("IsEmpty").test(v)}],["validate-one-required","Please select one of the above options.",function(v,elm){var p=elm.parentNode;var options=p.getElementsByTagName("INPUT");return $A(options).any(function(elm){return $F(elm)})}]]);
BrainstormJs.Admin.Forms.Fields.BaseField=Class.create({options:false,form:false,container:false,id:false,initialize:function(options){this.options=options||{};this.form=options.form||false;this.container=options.container||false},hasValue:function(){},getValue:function(){},setValue:function(){},clear:function(){},focus:function(){},enable:function(){},disable:function(){},getElement:function(){}});
BrainstormJs.Admin.Forms.Fields.TextBox=Class.create(BrainstormJs.Admin.Forms.Fields.BaseField,{input:false,initialize:function($super,options){options=options||{};if(!options.container)console.error("The TextBox field needs a valid container");this.input=options.container.down("input");if(!this.input)console.error("Could not find input element for textbox: %o",options.container);this.id=this.input.id;$super(options);if(this.input.className.indexOf("validate")>=0){var validator=new LiveValidation(this.id,
{validMessage:"",wait:500,onlyOnBlur:true});if(this.input.hasClassName("validate-required"))validator.add(Validate.Presence,{failureMessage:"Required"});if(this.input.hasClassName("validate-number"))validator.add(Validate.Numericality,{notANumberMessage:"Must be a number"});if(this.input.hasClassName("validate-requiredCond")){var input=this.input;var form=this.form;validator.add(Validate.Custom,{failureMessage:"Required",against:function(value,args){var isRequired=form.getFieldValue(input.readAttribute("requiredifyes"));
var isValid=isRequired?input.value.strip()!="":true;validator.displayMessageWhenEmpty=!isValid;return isValid}})}this.form.addValidator(validator)}},hasValue:function(){return this.getValue()!=""},getValue:function(){var stringValue=this.input.value.strip();if(this.input.hasClassName("validate-number"))return parseInt(stringValue,10);return stringValue},setValue:function(value){this.input.value=value},clear:function(){this.setValue("")},focus:function(){this.input.focus()},enable:function(){this.input.disabled=
false},disable:function(){this.input.disabled=true},getElement:function(){return this.input}});
BrainstormJs.Admin.Forms.Fields.FileUpload=Class.create(BrainstormJs.Admin.Forms.Fields.BaseField,{input:false,btnUpload:false,swfUploadImage:false,showProgress:true,progressBarDiv:false,fileSizeLimit:"15 MB",fileTypes:"*.*",fileTypesDescription:"All Files",tenantId:false,fileUploadedCallback:false,fileQueuedCallback:false,tempFileName:false,autoUpload:true,uploader:false,done:false,initialize:function($super,options){options=options||{};this.fileSizeLimit=options.fileSizeLimit||this.fileSizeLimit;
this.fileTypes=options.fileTypes||this.fileTypes;this.fileTypesDescription=options.fileTypesDescription||this.fileTypesDescription;this.tenantId=options.tenantId||this.tenantId;this.swfUploadImage=options.swfUploadImage||this.swfUploadImage;if(!options.container)console.error("The FileUpload field needs a valid container");this.input=options.container.down("input");this.done=options.container.down("span.done");if(!this.input)console.error("Could not find input element for textbox: %o",options.container);
if(options.fileUploadedCallback)this.fileUploadedCallback=options.fileUploadedCallback;if(options.fileQueuedCallback)this.fileQueuedCallback=options.fileQueuedCallback;this.id=this.input.id;$super(options);this.btnUpload=this.input.next(".upload");this.initializeUploader();if(this.showProgress){this.progressBarDiv=this.input.next(".progressBar");this.progressBarDiv.hide()}this.btnUpload.observe("click",function(e){this.startUpload(this.uploadFinishedCallback);e.stop()}.bind(this));this.tempFileName=
this.btnUpload.next(".tempFileName")},initializeUploader:function(){var settings=bsCommon.fileUploadSettings();settings.file_types=this.fileTypes;settings.file_types_description=this.fileTypesDescription;settings.file_size_limit=this.fileSizeLimit;settings.file_queue_limit=100,settings.file_upload_limit=100;if(this.swfUploadImage)settings.button_image_url=this.swfUploadImage;settings.button_placeholder_id="spanButtonPlaceHolder",settings.button_width=79,settings.button_height=22,settings.button_disabled=
false,settings.button_cursor=SWFUpload.CURSOR.HAND,settings.button_window_mode=SWFUpload.WINDOW_MODE.TRANSPARENT,settings.button_action=SWFUpload.BUTTON_ACTION.SELECT_FILES,settings.file_dialog_start_handler=bsCommon.onDialogStart.bind(this);settings.file_queued_handler=this.onFileQueued.bind(this);settings.file_queue_error_handler=bsCommon.onFileQueueError.bind(this);settings.file_dialog_complete_handler=bsCommon.onDialogComplete.bind(this);settings.upload_progress_handler=bsCommon.onUpdateProgress.bind(this);
settings.upload_success_handler=bsCommon.onUploadSuccess.bind(this);settings.upload_error_handler=bsCommon.onUploadError.bind(this);if(this.tenantId)settings.post_params.tenantId=this.tenantId;this.uploader=new SWFUpload(settings)},onFileQueued:function(file){this.input.value=file.name;if(!this.autoUpload)this.btnUpload.appear();if(this.fileQueuedCallback)this.fileQueuedCallback();if(this.autoUpload)window.setTimeout(function(){this.startUpload(this.uploadFinishedCallback)}.bind(this),500)},hasValue:function(){return this.getValue()!=
""},getValue:function(){var stringValue=this.input.value.strip();return stringValue},setValue:function(value){this.input.value=value;this.enable()},clear:function(){this.setValue("");this.enable()},clearProgressBar:function(){if(this.showProgress){this.progressBarDiv.hide();if(this.progressBar)this.progressBar.reset()}},focus:function(){this.input.focus()},enable:function(){this.input.disabled=false;this.uploader.setButtonDisabled(false)},disable:function(){this.input.disabled=true;this.uploader.setButtonDisabled(true)},
getElement:function(){return this.input},uploadFinishedCallback:function(docId,mimeType,fileSize,file){var done=this.btnUpload.next(".done");if(done)Effect.Appear(done,{duration:0.5,afterFinish:function(){Effect.Fade(done,{duration:1,delay:2})}});this.clearProgressBar();this.tempFileName.value=docId;if(this.fileUploadedCallback)this.fileUploadedCallback(docId,mimeType,fileSize,file);else window.setTimeout(function(){this.enable()}.bind(this),1E3)},startUpload:function(callback){this.uploadFinishedCallback=
callback;this.disable();if(this.showProgress){if(!this.progressBar)this.progressBar=new Control.ProgressBar(this.progressBarDiv,{});Effect.BlindDown(this.progressBarDiv,{duration:0.5})}window.setTimeout(function(){this.uploader.startUpload()}.bind(this),1)}});
BrainstormJs.Controls.WysiwygTextarea=Class.create({textarea:false,options:false,_useTinyMce:true,_tinyMceWired:false,_tinyMceHidden:false,_tinyMceEditor:false,_manualPlaceholder:true,initialize:function(textarea,options){if(!textarea){console.error("Could not locate native textarea element.");return}this.options=options||{};this.textarea=textarea;this.textarea.identify();if(Prototype.Browser.MobileSafari)this._useTinyMce=false;if(BrainstormJs.Utils.hasPlaceholderSupport()){this._manualPlaceholder=
false;if(this.textarea.value==this.textarea.placeholder)this.textarea.value=""}this.textarea.observe("focus",function(e){this._onFocus(false);e.stop()}.bind(this));if(!this._useTinyMce)this.textarea.observe("blur",function(e){this._onBlur(false);e.stop()}.bind(this));if(this._useTinyMce&&!this.options.lazyWire)this._wireTinyMce()},_wireTinyMce:function(afterFocus){if(this._useTinyMce&&!this._tinyMceWired){if(afterFocus&&this.options.lazyWire&&this.options.defaultText&&this.textarea.value==this.options.defaultText)this.textarea.value=
"";window.setTimeout(function(){tinyMCE.execCommand("mceAddControl",false,this.textarea.id);this._tinyMceWired=true}.bind(this),1)}},setTabIndex:function(tabIndex){if(this._useTinyMce){var editor=this._getEditor();var setTabIndexFx=function(){if(!editor)editor=this._getEditor();if(editor){var container=$(editor.contentAreaContainer);var iframe=container.down("iframe");iframe.tabIndex=tabIndex}}.bind(this);if(editor)window.setTimeout(setTabIndexFx,1);else window.setTimeout(setTabIndexFx,1E3)}else this.textarea.tabIndex=
tabIndex},_onFocus:function(fromTinyMce){if(this._useTinyMce){if(this.options.lazyWire&&!this._tinyMceWired)this._wireTinyMce(true);if(this._tinyMceWired&&this._tinyMceHidden){if(this.options.defaultText&&this.textarea.value==this.options.defaultText)this.textarea.value="";tinyMCE.execCommand("mceToggleEditor",false,this.textarea.id);this._tinyMceHidden=false}}else if(this.options.autoExpand)this.textarea.addClassName("expanded");if(this.options.defaultText&&this._manualPlaceholder){var currentContent=
this.getContent().strip();if(currentContent&&currentContent!=""&&currentContent==this.options.defaultText)this.setContent("")}this.focus();if(this.options.onFocus)this.options.onFocus()},focus:function(){if(this._useTinyMce){var editor=this._getEditor();var focusFx=function(){if(!editor)editor=this._getEditor();if(editor)window.setTimeout(function(){editor.focus()},1)}.bind(this);if(editor)focusFx();else window.setTimeout(focusFx,1E3)}else this.textarea.focus()},_onBlur:function(){var changed=false;
if(this.options.defaultText){var currentContent=this.getContent(true);if(currentContent==""||currentContent==this.options.defaultText){this.toggleOff();changed=true}}if(this.options.onBlur)this.options.onBlur(changed)},toggleOff:function(){if(this._useTinyMce&&this._tinyMceWired){tinyMCE.execCommand("mceSetContent",false,"");tinyMCE.execCommand("mceToggleEditor",false,this.textarea.id);this._tinyMceHidden=true}if(this.options.defaultText&&this._manualPlaceholder)this.textarea.value=this.options.defaultText;
else this.textarea.value="";this.textarea.removeClassName("expanded")},remove:function(){if(this._useTinyMce&&this._tinyMceWired){var editor=this._getEditor();if(editor){editor.focus();editor.remove();this._tinyMceEditor=false;this._tinyMceWired=false}}},save:function(){if(this._useTinyMce&&this._tinyMceWired){var editor=this._getEditor();if(editor)editor.save()}},getContent:function(stripTags){if(this._useTinyMce){this.save();var editor=this._getEditor();var content=editor?editor.getContent():false;
if(stripTags&&content)content=content.stripTags();return content?content.strip():""}else return this.textarea.value.strip()},setContent:function(content){this.textarea.value=content;if(this._useTinyMce&&this._tinyMceWired){var editor=this._getEditor();if(editor)window.setTimeout(function(){editor.setContent(content)},1);else{console.warn("Could not find TinyMCE editor to set content: %o",content);window.setTimeout(function(){var editor=this._getEditor();if(editor)editor.setContent(content);else console.error("Could not find TinyMCE editor to set content: %o",
content)}.bind(this),500)}}},_getEditor:function(){if(this._useTinyMce&&this._tinyMceWired){if(!this._tinyMceEditor)this._tinyMceEditor=tinyMCE.get(this.textarea.id);return this._tinyMceEditor}return false}});
BrainstormJs.Admin.Forms.Fields.TextArea=Class.create(BrainstormJs.Admin.Forms.Fields.BaseField,{textarea:false,enableWysiwyg:false,wysiwygEditor:false,initialize:function($super,options){options=options||{};if(!options.container)console.error("The TextArea field needs a valid container");this.textarea=options.container.down("textarea");if(!this.textarea)console.error("Could not find textarea element for textarea: %o",options.container);this.id=this.textarea.id;this.enableWysiwyg=this.textarea.hasClassName("richEditor");
if(this.enableWysiwyg){this.textarea.setStyle({width:"100%"});this.wysiwygEditor=new BrainstormJs.Controls.WysiwygTextarea(this.textarea)}$super(options);if(!this.enableWysiwyg)this.setValue(this.getValue().gsub(/\n\s+/m,"\n"))},hasValue:function(){return this.getValue().strip()!=""},getValue:function(){if(this.enableWysiwyg&&this.wysiwygEditor)return this.wysiwygEditor.getContent();else return this.textarea.value.strip()},setValue:function(value){if(this.enableWysiwyg&&this.wysiwygEditor){var editor=
this.wysiwygEditor;window.setTimeout(function(){editor.setContent(value)},100)}else this.textarea.value=value},clear:function(){this.setValue("")},focus:function(){if(this.enableWysiwyg)this.wysiwygEditor.focus();else this.textarea.focus()},enable:function(){this.textarea.disabled=false},disable:function(){this.textarea.disabled=true},getElement:function(){return this.textarea}});
BrainstormJs.Admin.Forms.Fields.YesNoRadios=Class.create(BrainstormJs.Admin.Forms.Fields.BaseField,{radios:false,initialize:function($super,options){this.radios=[];options=options||{};if(!options.container)console.error("The YesNoRadios field needs a valid container");var radioChoices=options.container.select("input");for(var i=0,j=radioChoices.length;i<j;i++){var radio=radioChoices[i];this.radios.push(radio);this.id=radio.name}$super(options);var form=this.form;for(var i=0,j=radioChoices.length;i<
j;i++){var radio=radioChoices[i];var dependFieldId=radio.readAttribute("fielddepend");if(dependFieldId){radio.observe("click",function(e){this.showField(e)}.bind(this));if(radio.checked){var dependField=$(dependFieldId);if(dependField)dependField.blindDown();else console.error("Could not find field with id [%o] for radio button: %o",dependFieldId,radio)}}}},showField:function(el){var dependField=el.target.readAttribute("fielddepend");if(!$(dependField).visible())$(dependField).blindDown()},hasValue:function(){var value=
this.getValue();return value&&value!=""&&value.strip()!=""},getValue:function(){for(var i=0,j=this.radios.length;i<j;i++)if(this.radios[i].checked){var stringValue=this.radios[i].value;return stringValue=="1"}},setValue:function(value){this.clear();for(var i=0,j=this.radios.length;i<j;i++)if(this.radios[i].value==value){this.radios[i].checked=true;return}},clear:function(){for(var i=0,j=this.radios.length;i<j;i++)this.radios[i].checked=false;this.radios[0].checked=true},focus:function(){},enable:function(){for(var i=
0,j=this.radios.length;i<j;i++)this.radios[i].disabled=false},disable:function(){for(var i=0,j=this.radios.length;i<j;i++)this.radios[i].disabled=true},getElement:function(){return null}});
BrainstormJs.Admin.Forms.Fields.DropDownList=Class.create(BrainstormJs.Admin.Forms.Fields.BaseField,{select:false,initialize:function($super,options){options=options||{};if(!options.container)console.error("The DropDownList field needs a valid container");this.select=options.container.down("select");if(!this.select)console.error("Could not find select element for drop down: %o",options.container);this.id=this.select.id;$super(options)},hasValue:function(){return this.getValue()!=""},getValue:function(){var integer=
parseInt(this.select.options[this.select.selectedIndex].value);if(isNaN(integer))return this.select.options[this.select.selectedIndex].value;return integer},setIndex:function(index){if(bsCommon.isInteger(index))this.select.selectedIndex=index},setValue:function(value){for(var i=0,j=this.select.options.length;i<j;i++){var option=this.select.options[i];if(option.value==value){option.selected=true;return}}},clear:function(){this.setIndex(0)},focus:function(){this.select.focus()},enable:function(){this.select.disabled=
false},disable:function(){this.select.disabled=true},getElement:function(){return this.select}});
BrainstormJs.Admin.Forms.Fields.ActionButton=Class.create(BrainstormJs.Admin.Forms.Fields.BaseField,{button:false,onClick:false,initialLabel:false,spinner:false,outputDiv:false,errorDiv:false,container:false,textbox:false,textboxValidator:false,doneLabel:false,initialize:function($super,options){options=options||{};if(!options.container)console.error("The ActionButton field needs a valid container");this.button=options.container.down("button");if(!this.button)console.error("Could not find button element for action button: %o",
options.container);this.container=options.container;this.outputDiv=options.container.down("div.output");this.errorDiv=options.container.down("div.ajaxErrorInfo");this.spinner=options.container.down("img.spinner");this.textbox=options.container.down("input.textbox");if(this.textbox){this.textboxValidator=this.textbox.next("span.LV_validation_message");this.textbox.observe("keypress",function(e){this._onKeyPress(e)}.bind(this))}else this.doneLabel=options.container.down("span.done");this.initialLabel=
this.button.innerHTML;this.button.observe("click",function(e){this._onClick();e.stop()}.bind(this));this.id=this.button.id;$super(options)},_onClick:function(){if(this.onClick){if(this.textbox)if(!Validate.now(Validate.Presence,this.textbox.value)){this.textbox.addClassName("LV_invalid_field");this.textbox.pulsate({pulses:1});this.textboxValidator.show();return}else if(this.textbox.hasClassName("LV_invalid_field")){this.textbox.removeClassName("LV_invalid_field");this.textbox.addClassName("LV_valid_field");
this.textboxValidator.hide()}if(this.button.hasClassName("confirm")){var confirmText=this.button.next("span.confirmText");if(confirmText&&!confirm(confirmText.innerHTML))return}if(this.doneLabel)this.doneLabel.hide();this.disable(this.initialLabel+" ... Please Wait ...");this.spinner.appear({duration:0.25});this.onClick()}else alert("This button is not enabled")},_onKeyPress:function(e){if(e.keyCode==Event.KEY_RETURN&&this.textbox){this._onClick();e.stop()}},getValue:function(){if(this.textbox)return this.textbox.value.strip();
console.error("Getting a value from a no-input action button is not supported.");return false},enable:function(label){this.button.disabled=false;if(label)this.button.innerHTML=label;else this.button.innerHTML=this.initialLabel},disable:function(label){this.button.disabled=true;if(label)this.button.innerHTML=label},onSuccess:function(html){this.stopProcessing(this.errorDiv,this.doneLabel);var closeButton='<a href="javascript:;" onClick="$(this).up().blindUp();" class="close">close</a>';this.outputDiv.innerHTML=
closeButton+html;this.outputDiv.blindDown({duration:0.5})},onFailure:function(error){this.stopProcessing(this.outputDiv);this.form.processAjaxError(error,this.errorDiv);if(!this.errorDiv.visible())this.errorDiv.toggle();if(!this.container.visible())this.container.toggle()},stopProcessing:function(hideDiv,doneLabel){this.spinner.fade({duration:0.25,afterFinish:function(){if(doneLabel)doneLabel.appear()}});if(hideDiv&&hideDiv.visible())hideDiv.blindUp({duration:0.5});this.enable()}});
BrainstormJs.Admin.Forms.BaseAdminForm=Class.create({container:false,fields:false,validators:false,fileUploaders:false,submitButton:false,buttonContainer:false,cancelButton:false,validationError:false,savedMessage:false,errorDiv:false,initialize:function(container,options){this.fields=new Hash;this.validators=[];this.fileUploaders=[];this.container=$(container);var fieldDivs=this.container.select("div.adminField div.fieldInput");for(var i=0,j=fieldDivs.length;i<j;i++){var inputDiv=fieldDivs[i];var field=
false;var fieldOptions={container:inputDiv,form:this};if(inputDiv.hasClassName("textbox"))field=new BrainstormJs.Admin.Forms.Fields.TextBox(fieldOptions);if(inputDiv.hasClassName("fileupload")){Object.extend(fieldOptions,options.fileUploadOptions);fieldOptions.tenantId=options.tenantId;fieldOptions.fileUploadedCallback=options.fileUploadedCallback;fieldOptions.fileQueuedCallback=options.fileQueuedCallback;field=new BrainstormJs.Admin.Forms.Fields.FileUpload(fieldOptions);this.fileUploaders.push(field)}else if(inputDiv.hasClassName("textarea"))field=
new BrainstormJs.Admin.Forms.Fields.TextArea(fieldOptions);else if(inputDiv.hasClassName("yesno"))field=new BrainstormJs.Admin.Forms.Fields.YesNoRadios(fieldOptions);else if(inputDiv.hasClassName("dropdown"))field=new BrainstormJs.Admin.Forms.Fields.DropDownList(fieldOptions);else if(inputDiv.hasClassName("actionButton"))field=new BrainstormJs.Admin.Forms.Fields.ActionButton(fieldOptions);else if(inputDiv.hasClassName("checkbox"))field=new BrainstormJs.Admin.Forms.Fields.CheckBox(fieldOptions);if(field){if(!field.id){console.error("Field %o does not have a field id.",
field);continue}var mapField=this.fields.get(field.id);if(mapField){console.error("Field collection already contains a field with the name: %o. Make sure that field ids are unique.",field.id);continue}this.fields.set(field.id,field)}else{console.error("Could not initialize field: %o",inputDiv);continue}}this.buttonContainer=this.container.down("div.formButtons");if(this.buttonContainer){this.submitButton=this.buttonContainer.down("input.submitButton");this.cancelButton=this.buttonContainer.down("a.cancelButton");
this.validationError=this.buttonContainer.down("span.validationError");this.savedMessage=this.buttonContainer.down("span.savedMessage");this.errorDiv=this.container.down("div.ajaxErrorInfo");this.submitButton.observe("click",function(e){this.validateForm();e.stop()}.bind(this))}this.wireActionButtons();this.wireFields()},wireActionButtons:function(){},wireFields:function(){},getField:function(fieldId){var field=this.fields.get(fieldId);if(!field)return false;return field},getFieldValue:function(fieldId){return this.getField(fieldId).getValue()},
addValidator:function(validator){this.validators.push(validator)},validateForm:function(){this.validationError.hide();this.savedMessage.hide();if(!LiveValidation.massValidate(this.validators)){this.validationError.show();Effect.Pulsate(this.validationError,{pulses:3,duration:1.5});return}this.submitForm()},submitForm:function(){this.setFieldState(false);this.submitButton.value="Saving ...";this.submitButton.disabled=true;this.buttonContainer.addClassName("savingFormButtons");this.saveData()},saveData:function(){this.afterSaveData()},
afterSaveData:function(){this.errorDiv.hide();this.setFieldState(true);this.submitButton.value="Save";this.submitButton.disabled=false;this.buttonContainer.removeClassName("savingFormButtons");this.savedMessage.appear({duration:0.5})},setFieldState:function(enable){var keys=this.fields.keys();for(var i=0;i<keys.length;i++){var field=this.fields.get(keys[i]);if(enable)field.enable();else field.disable()}},getFileUpload:function(){return this.fileUploaders},resetUploads:function(){var fups=this.getFileUpload();
for(var i=0;i<fups.length;i++)fups[i].clear()},disableUploads:function(){var fups=this.getFileUpload();for(var i=0;i<fups.length;i++)fups[i].disable()},enableUploads:function(){var fups=this.getFileUpload();for(var i=0;i<fups.length;i++)fups[i].enable()},processAjaxError:function(error,overrideDiv){if(!overrideDiv){this.submitButton.value="Error ...";if(this.buttonContainer)this.buttonContainer.removeClassName("savingFormButtons")}var stackTrace=error.get_stackTrace().replace(/\n/g,"<br/>");var message=
error.get_message();var statusCode=error.get_statusCode();var exceptionType=error.get_exceptionType();var timedout=error.get_timedOut();var errorDiv=overrideDiv||this.errorDiv;errorDiv.down("p.message").innerHTML=message;errorDiv.show();Effect.Pulsate(errorDiv,{pulses:3,duration:2.5,from:0.25,to:1});bsCommon.scrollIfBelowFold(errorDiv,10)}});
BrainstormJs.Admin.Forms.Fields.CheckBox=Class.create(BrainstormJs.Admin.Forms.Fields.BaseField,{input:false,initialize:function($super,options){options=options||{};if(!options.container)console.error("The CheckBox field needs a valid container");this.input=options.container.down("input");if(!this.input)console.error("Could not find input element for textbox: %o",options.container);this.id=this.input.id;$super(options)},hasValue:function(){return this.getValue()!=""},getValue:function(){var stringValue=
this.input.checked;return stringValue},setValue:function(value){this.input.value=value},clear:function(){this.setValue("")},focus:function(){this.input.focus()},enable:function(){this.input.disabled=false},disable:function(){this.input.disabled=true},getElement:function(){return this.input}});
BrainstormJs.Admin.Forms.Instance.AdminActiveDirectoryForm=Class.create(BrainstormJs.Admin.Forms.BaseAdminForm,{btnTestConnection:false,btnTestBind:false,btnTestSearch:false,btnFindUserByEmail:false,btnFindUserByLogin:false,btnRunDirectorySync:false,wireActionButtons:function(){this.btnTestConnection=this.getField("btnTestLdapConnection");this.btnTestConnection.onClick=this.testConnection.bind(this);this.btnTestBind=this.getField("btnTestBind");this.btnTestBind.onClick=this.testBind.bind(this);this.btnTestSearch=
this.getField("btnTestSearch");this.btnTestSearch.onClick=this.testSearch.bind(this);this.btnFindUserByEmail=this.getField("btnFindUserByEmail");this.btnFindUserByEmail.onClick=this.findUserByEmail.bind(this);this.btnFindUserByLogin=this.getField("btnFindUserByLogin");this.btnFindUserByLogin.onClick=this.findUserByLogin.bind(this);this.btnRunDirectorySync=this.getField("btnRunDirectorySync");this.btnRunDirectorySync.onClick=this.executeFullSync.bind(this);this.btnInactivateUsers=this.getField("btnInactivateUsers");
this.btnInactivateUsers.onClick=this.inactivateUsers.bind(this)},testConnection:function(){Brainstorm.Web.Services.Admin.TestLdapConnection(parseInt($F("tenantId"),10),this.getFieldValue("txtLdapServer"),this.getFieldValue("txtLdapScope"),this.getFieldValue("txtLdapUsername"),this.getFieldValue("txtLdapPassword"),this.btnTestConnection.onSuccess.bind(this.btnTestConnection),this.btnTestConnection.onFailure.bind(this.btnTestConnection))},testBind:function(){Brainstorm.Web.Services.Admin.TestLdapBind(parseInt($F("tenantId"),
10),this.getFieldValue("btnTestBind"),this.btnTestBind.onSuccess.bind(this.btnTestBind),this.btnTestBind.onFailure.bind(this.btnTestBind))},testSearch:function(){Brainstorm.Web.Services.Admin.TestLdapSearch(parseInt($F("tenantId"),10),this.getFieldValue("btnTestSearch"),this.btnTestSearch.onSuccess.bind(this.btnTestSearch),this.btnTestSearch.onFailure.bind(this.btnTestSearch))},findUserByEmail:function(){Brainstorm.Web.Services.Admin.FindLdapUserByEmail(parseInt($F("tenantId"),10),this.getFieldValue("btnFindUserByEmail"),
this.btnFindUserByEmail.onSuccess.bind(this.btnFindUserByEmail),this.btnFindUserByEmail.onFailure.bind(this.btnFindUserByEmail))},findUserByLogin:function(){Brainstorm.Web.Services.Admin.FindLdapUserByLogin(parseInt($F("tenantId"),10),this.getFieldValue("btnFindUserByLogin"),this.btnFindUserByLogin.onSuccess.bind(this.btnFindUserByLogin),this.btnFindUserByLogin.onFailure.bind(this.btnFindUserByLogin))},saveData:function(){Brainstorm.Web.Services.Admin.SaveActiveDirectorySettings(parseInt($F("tenantId"),
10),this.getFieldValue("txtLdapServer"),this.getFieldValue("txtLdapScope"),this.getFieldValue("txtLdapUsername"),this.getFieldValue("txtLdapPassword"),this.getFieldValue("radLdapSyncEnabled"),this.getFieldValue("txtLdapSyncUserFilter"),this.getFieldValue("ddlLdapSyncDedupMode"),this.getFieldValue("ddlManagerLookupMode"),this.getFieldValue("ddlLdapPagingMode"),this.getFieldValue("txtLdapPageSize"),this.getFieldValue("radLdapLoggingEnabled"),this.getFieldValue("radLdapSearchLogging"),this.getFieldValue("radLdapRemoveDiacriticals"),
this.getFieldValue("txtFieldMapLdapDN"),this.getFieldValue("txtFieldMapManagerDN"),this.getFieldValue("txtFieldMapEmployeeId"),this.getFieldValue("radFieldMapEmployeeIdByteArray"),this.getFieldValue("txtFieldMapLogin"),this.getFieldValue("txtFieldMapFirstName"),this.getFieldValue("txtFieldMapLastName"),this.getFieldValue("txtFieldMapDisplayName"),this.getFieldValue("txtFieldMapLegalName"),this.getFieldValue("txtFieldMapEmailWork"),this.getFieldValue("txtFieldMapPhoneWork"),this.getFieldValue("txtFieldMapPhoneExtension"),
this.getFieldValue("txtFieldMapEmployeeBusinessTitle"),this.getFieldValue("txtFieldMapDepartmentName"),this.getFieldValue("txtFieldMapLocationWorksite"),this.getFieldValue("txtFieldMapLocationWorksiteName"),this.getFieldValue("txtFieldMapLocationRoomNumber"),this.getFieldValue("txtFieldMapLocationPostalAddress"),this.getFieldValue("txtFieldMapLocationState"),this.getFieldValue("txtFieldMapLocationCountry"),this.getFieldValue("txtFieldMapLocationTimeZone"),this.afterSaveData.bind(this),this.processAjaxError.bind(this))},
executeFullSync:function(){Brainstorm.Web.Services.Admin.ExecuteFullDirectorySync(parseInt($F("tenantId"),10),this.btnRunDirectorySync.onSuccess.bind(this.btnRunDirectorySync),this.btnRunDirectorySync.onFailure.bind(this.btnRunDirectorySync))},inactivateUsers:function(){Brainstorm.Web.Services.Admin.InactivateUsers(parseInt($F("tenantId"),10),this.btnInactivateUsers.onSuccess.bind(this.btnInactivateUsers),this.btnInactivateUsers.onFailure.bind(this.btnInactivateUsers))}});
BrainstormJs.Admin.Forms.Instance.AdminBrandingImageForm=Class.create(BrainstormJs.Admin.Forms.BaseAdminForm,{processing:false,brandingImageType:false,defaultImageUrl:false,nameElement:false,linkElement:false,resetElement:false,statusElement:false,errorElement:false,baseElementId:false,tenantId:false,initialize:function($super,container,options){var fileUploadedCallback=this.fileUploaded.bind(this);var fileQueuedCallback=this.fileQueued.bind(this);options=options||{};this.brandingImageType=options.brandingImageType;
this.tenantId=options.tenantId;this.nameElement=options.nameElement||(options.baseElementId?$(options.baseElementId+"ImageName"):false);this.linkElement=options.linkElement||(options.baseElementId?$(options.baseElementId+"ImageLink"):false);this.resetElement=options.resetElement||(options.baseElementId?$(options.baseElementId+"RemoveLink"):false);this.statusElement=options.statusElement||(options.baseElementId?$(options.baseElementId+"Status"):false);this.errorElement=options.errorElement||false;
var defaultUrlDataElem=$(container).down("input.defaultUrl");if(defaultUrlDataElem){this.defaultImageUrl=defaultUrlDataElem.value;defaultUrlDataElem.remove()}options.fileUploadedCallback=fileUploadedCallback;options.fileQueuedCallback=fileQueuedCallback;options.fileUploadOptions={fileSizeLimit:"10 MB",fileTypes:"*.jpg;*.jpeg;*.png;*.gif;*.bmp",fileTypesDescription:"Image Files",swfUploadImage:"/Images/Buttons/btn_upload_replacement.gif"};$super(container,options)},wireActionButtons:function(){if(this.resetElement){this.resetElement.observe("click",
this.resetImage.bind(this));this.resetElement.observe("mouseover",function(){this.resetElement.setStyle({backgroundPosition:"0px -22px"})}.bind(this));this.resetElement.observe("mouseout",function(){this.resetElement.setStyle({backgroundPosition:"0px 0px"})}.bind(this));this.resetElement.observe("mousedown",function(){this.resetElement.setStyle({backgroundPosition:"0px -44px"})}.bind(this));this.resetElement.observe("mouseup",function(){this.resetElement.setStyle({backgroundPosition:"0px -22px"})}.bind(this))}},
resetImage:function(){if(!confirm("Are you sure you want to reset the Brainstorm Logo to the default image?"))return;Brainstorm.Web.Services.Admin.ResetBrandingImage(this.brandingImageType,this.tenantId,this.imageReset.bind(this),function(){console.log("fail")});return false},imageReset:function(){if(this.linkElement){this.linkElement.update("Default");this.linkElement.setAttribute("href",this.defaultImageUrl?this.defaultImageUrl:"#")}this.resetElement.fade()},importImage:function(tempFileName,fileName){Brainstorm.Web.Services.Admin.ProcessBrandingImage(this.brandingImageType,
tempFileName,fileName,this.tenantId,this.fileImported.bind(this),this.processUploadError.bind(this))},processUploadError:function(error){this.hideProcessing();this.statusElement.update("Error!");this.statusElement.addClassName("error");Effect.Pulsate(this.statusElement,{pulses:3,duration:2.5,from:0.25,to:1});if(this.errorElement)this.processAjaxError(error,this.errorElement);this.resetUploads()},clearForm:function(clearFileUpload){if(clearFileUpload)this.resetUploads()},fileImported:function(response){this.hideProcessing();
this.statusElement.update("Done!");this.statusElement.addClassName("success");Effect.Fade(this.statusElement,{duration:1,delay:2});if(this.linkElement){this.linkElement.setAttribute("href",response.ImageUrl);this.linkElement.update(response.ImageFileName)}if(this.resetElement)this.resetElement.appear();this.resetUploads()},fileUploaded:function(documentId,mimeType,fileSize,file){this.disableUploads();this.importImage(documentId,file.name)},fileQueued:function(){this.showProcessing()},showProcessing:function(){if(this.statusElement){if(this.errorElement)this.errorElement.hide();
this.statusElement.removeClassName("success");this.statusElement.removeClassName("error");this.statusElement.appear();this.statusElement.update("Processing ...")}},hideProcessing:function(){if(!this.statusElement)return},saveData:function(){}});
BrainstormJs.Admin.Forms.Instance.AdminCacheSettingsForm=Class.create(BrainstormJs.Admin.Forms.BaseAdminForm,{wireActionButtons:function(){this.btnFlushHibCache=this.getField("btnFlushHibCache");this.btnFlushContentCache=this.getField("btnFlushContentCache");this.btnEjectNode=this.getField("btnEjectNode");this.btnFlushHibCache.onClick=this.flushNHibCache.bind(this);this.btnFlushContentCache.onClick=this.flushContentCache.bind(this);this.btnEjectNode.onClick=this.ejectNode.bind(this);this.nhibMsg=
this.btnFlushHibCache.button.next(".successResponse");this.contentMsg=this.btnFlushContentCache.button.next(".successResponse");this.ejectMsg=this.btnEjectNode.button.next(".successResponse")},flushContentCache:function(){Brainstorm.Web.Services.Admin.FlushCache($F("bstormCacheName"),this.btnFlushContentCache.onSuccess.bind(this.btnFlushContentCache),this.btnFlushContentCache.onFailure.bind(this.btnFlushContentCache))},flushNHibCache:function(){Brainstorm.Web.Services.Admin.FlushCache($F("nhibCacheName"),
this.btnFlushHibCache.onSuccess.bind(this.btnFlushHibCache),this.btnFlushHibCache.onFailure.bind(this.btnFlushHibCache))},ejectNode:function(){var node=this.getFieldValue("ddlNodesEject");Brainstorm.Web.Services.Admin.EjectNode(node,this.btnEjectNode.onSuccess.bind(this.btnEjectNode),this.btnEjectNode.onFailure.bind(this.btnEjectNode))}});
BrainstormJs.Admin.Forms.Instance.AdminEmailSettingsForm=Class.create(BrainstormJs.Admin.Forms.BaseAdminForm,{wireActionButtons:function(){this.btnTestEmail=this.getField("btnTestEmail");this.btnTestEmail.onClick=this.sendTestEmail.bind(this)},sendTestEmail:function(){Brainstorm.Web.Services.Admin.SendTestEmail(this.getFieldValue("btnTestEmail"),this.btnTestEmail.onSuccess.bind(this.btnTestEmail),this.btnTestEmail.onFailure.bind(this.btnTestEmail))},saveData:function(){Brainstorm.Web.Services.Admin.SaveEmailSettings(bsCommon.getRequestToken(),
this.getFieldValue("txtSmtpHost"),this.getFieldValue("txtSmtpUsername"),this.getFieldValue("txtSmtpPassword"),this.getFieldValue("txtSmtpDomain"),this.getFieldValue("txtSmtpPort"),this.getFieldValue("radSmtpEnableSsl"),this.getFieldValue("txtMailerAccount"),this.getFieldValue("txtMailerDisplayName"),this.getFieldValue("radAlwaysSendFromMailer"),this.getFieldValue("txtSupportEmail"),this.getFieldValue("txtErrorEmailRecipients"),this.getFieldValue("txtFeedbackRecipients"),this.getFieldValue("radBlockEmails"),
this.getFieldValue("txtBlockEmailWhitelist"),this.getFieldValue("txtImapServer"),this.getFieldValue("txtImapUser"),this.getFieldValue("txtImapPassword"),this.afterSaveData.bind(this),this.processAjaxError.bind(this))}});
BrainstormJs.Admin.Forms.Instance.AdminEmailTestForm=Class.create(BrainstormJs.Admin.Forms.BaseAdminForm,{btnSendMultEmails:false,wireActionButtons:function(){this.txtEmailAddress=this.getField("txtEmailAddress");this.txtNumEmails=this.getField("txtNumberOfEmails");this.btnSendMultEmails=this.getField("btnSendMultipleTestEmails");this.btnSendMultEmails.onClick=this.testEmails.bind(this)},testEmails:function(){Brainstorm.Web.Services.Admin.TestEmails(this.getFieldValue("txtEmailAddress"),this.getFieldValue("txtNumberOfEmails"),
this.btnSendMultEmails.onSuccess.bind(this.btnSendMultEmails),this.btnSendMultEmails.onFailure.bind(this.btnSendMultEmails))}});
BrainstormJs.Admin.Forms.Instance.AdminFileStorageForm=Class.create(BrainstormJs.Admin.Forms.BaseAdminForm,{wireActionButtons:function(){this.btnEncryptNonEncDocuments=this.getField("btnEncryptNonEncDocuments");this.btnEncryptNonEncDocuments.onClick=this.ecryptNonEncDocuments.bind(this)},ecryptNonEncDocuments:function(){Brainstorm.Web.Services.Admin.EncryptNonEncryptedDocuments(this.btnEncryptNonEncDocuments.onSuccess.bind(this.btnEncryptNonEncDocuments),this.btnEncryptNonEncDocuments.onFailure.bind(this.btnEncryptNonEncDocuments))},
saveData:function(){Brainstorm.Web.Services.Admin.SaveFileStorageSettings(bsCommon.getRequestToken(),this.getFieldValue("radEnableS3Documents"),this.getFieldValue("txtAccessKeyId"),this.getFieldValue("txtSecretAccessKey"),this.getFieldValue("radEnableEncryption"),this.getFieldValue("txtEncryptionKey"),this.afterSaveData.bind(this),this.processAjaxError.bind(this))}});
BrainstormJs.Admin.Forms.Instance.AdminInstanceForm=Class.create(BrainstormJs.Admin.Forms.BaseAdminForm,{saveData:function(){Brainstorm.Web.Services.Admin.UpdateInstance(bsCommon.getRequestToken(),this.getFieldValue("txtGlobalMessage"),this.getFieldValue("radUseQuartz"),this.getFieldValue("quartzDbName"),this.getFieldValue("txtStaticCDN"),this.getFieldValue("radDebugSwfUploader"),this.getFieldValue("radProxyGoogleCharts"),this.getFieldValue("radEnableRequestMetrics"),this.getFieldValue("radEnableMobileSite"),
this.getFieldValue("txtAutoDirectMobileAgents"),this.afterSaveData.bind(this),this.processAjaxError.bind(this))}});
BrainstormJs.Admin.Forms.Instance.AdminIntegrationForm=Class.create(BrainstormJs.Admin.Forms.BaseAdminForm,{tenantId:false,initialize:function($super,container,options){var fileUploadedCallback=this.fileUploaded.bind(this);var fileQueuedCallback=this.fileQueued.bind(this);options=options||{};options.fileUploadedCallback=fileUploadedCallback;options.fileQueuedCallback=fileQueuedCallback;options.tenantId=parseInt($F("tenantId"),10);options.fileUploadOptions={fileSizeLimit:"10 MB",fileTypes:"*.cer;*.crt",
fileTypesDescription:"Certificate Files"};$super(container,options)},wireActionButtons:function(){this.errorsList=$("certUploadErrors")},fileImported:function(response){},fileUploaded:function(documentId,mimeType,fileSize,file){this.disableUploads();this.uploadCert(documentId,file.name)},fileQueued:function(){this.showProcessing()},showProcessing:function(){},hideProcessing:function(){},uploadCert:function(documentId,fileName){Brainstorm.Web.Services.Admin.SaveIdpCert(parseInt($F("tenantId")),documentId,
this.getFieldValue("btnUploadCert"),this.afterSaveData.bind(this),this.processAjaxError.bind(this))},saveData:function(){Brainstorm.Web.Services.Admin.SaveIntegrationSettings(parseInt($F("tenantId")),this.getFieldValue("radSamlEnabled"),this.getFieldValue("radAllowCreate"),this.getFieldValue("txtNameId"),this.getFieldValue("txtEntityId"),this.getFieldValue("txtIdpName"),this.getFieldValue("txtIdpSsoUrl"),this.getFieldValue("txtIdpLogoutUrl"),this.getFieldValue("radSloEnabled"),this.getFieldValue("txtSamlBinding"),
this.getFieldValue("radSignAuthnRequest"),this.afterSaveData.bind(this),this.processAjaxError.bind(this))}});
BrainstormJs.Admin.Forms.Instance.AdminMetricsForm=Class.create(BrainstormJs.Admin.Forms.BaseAdminForm,{wireActionButtons:function(){this.wireTaskButton("btnRefreshCurrentTenantMetrics");this.wireTaskButton("btnReseedCurrentTenantShareMessages");this.wireTaskButton("btnReseedCurrentTenantShareRecipients")},wireTaskButton:function(buttonId){var button=this.getField(buttonId);if(button)button.onClick=function(){this.executeTask(button)}.bind(this)},executeTask:function(button){Brainstorm.Web.Services.Admin.ExecuteTask(button.id,
button.onSuccess.bind(button),button.onFailure.bind(button))},saveData:function(){}});
BrainstormJs.Admin.Forms.Instance.AdminRecordsRetentionForm=Class.create(BrainstormJs.Admin.Forms.BaseAdminForm,{tenantId:false,btnReplyRrEmails:false,wireActionButtons:function(){this.btnReplyRrEmails=this.getField("btnReplyRrEmails");this.btnReplyRrEmails.onClick=this.replayEmails.bind(this)},replayEmails:function(){Brainstorm.Web.Services.Admin.ReplayRrEmails(parseInt($F("tenantId"),10),this.getFieldValue("txtDaysToReplay"),this.btnReplyRrEmails.onSuccess.bind(this.btnReplyRrEmails),this.btnReplyRrEmails.onFailure.bind(this.btnReplyRrEmails))},
saveData:function(){Brainstorm.Web.Services.Admin.SaveRrSettings(parseInt($F("tenantId")),this.getFieldValue("radRrEnabled"),this.getFieldValue("txtRrEmail"),this.afterSaveData.bind(this),this.processAjaxError.bind(this))}});
BrainstormJs.Admin.Forms.Instance.AdminReplaceCSSForm=Class.create(BrainstormJs.Admin.Forms.BaseAdminForm,{tenantId:false,isDirty:false,editTextBoxId:false,originalContent:false,checkDirtied:null,buttons:false,initialize:function($super,container,options){options=options||{};this.tenantId=options.tenantId;this.editTextBoxId=options.editTextBoxId;$super(container,options);this.originalContent=this.getFieldValue(this.editTextBoxId);$(this.editTextBoxId).observe("keypress",this.keypress.bind(this));
this.buttons=this.buttonContainer.down(".buttons")},wireActionButtons:function(){var cancelLink=this.container.down(".cancelButton");if(cancelLink)cancelLink.observe("click",function(){this.reset();return false}.bind(this))},keypress:function(){if(!this.isDirty){clearTimeout(this.checkDirtied);this.checkDirtied=setTimeout(function(){if(this.getFieldValue(this.editTextBoxId)!=this.originalContent){this.isDirty=true;this.buttons.appear()}}.bind(this),300)}},clean:function(){this.originalContent=this.getFieldValue(this.editTextBoxId);
this.isDirty=false;this.errorDiv.hide();this.submitButton.value="Save CSS"},reset:function(){this.errorDiv.fade();this.buttons.fade();this.getField(this.editTextBoxId).setValue(this.originalContent);this.clean()},saveData:function(){this.errorDiv.hide();Brainstorm.Web.Services.Admin.UpdateBrandingCSS(this.getFieldValue(this.editTextBoxId),this.tenantId,this.afterSaveData.bind(this),this.saveDataFailed.bind(this))},saveDataFailed:function(error){this.submitButton.value="Retry";this.processAjaxError(error,
this.errorDiv)},afterSaveData:function(){this.clean();Effect.Fade(this.buttons,{duration:0.25,from:1,to:0,afterFinish:function(){this.savedMessage.show();Effect.Appear(this.savedMessage,{duration:0.5,from:0,to:1,afterFinish:function(){Effect.Fade(this.savedMessage,{duration:0.25,from:1,to:0,delay:2})}.bind(this)})}.bind(this)})},submitForm:function(){this.saveData()}});
BrainstormJs.Admin.Forms.Instance.AdminSearchForm=Class.create(BrainstormJs.Admin.Forms.BaseAdminForm,{saveData:function(){Brainstorm.Web.Services.Admin.UpdateSolr(bsCommon.getRequestToken(),this.getFieldValue("solrHost"),this.afterSaveData.bind(this),this.processAjaxError.bind(this))},wireActionButtons:function(){this.btnRefreshIndex=this.getField("btnRefreshIndex");this.btnClearSolrErrors=this.getField("btnClearSolrErrors");this.btnRefreshIndex.onClick=this.refreshIndex.bind(this);this.btnClearSolrErrors.onClick=
this.clearErrors.bind(this)},refreshIndex:function(){Brainstorm.Web.Services.Admin.RefreshIndex(bsCommon.getRequestToken(),this.getFieldValue("solrHost"),this.btnRefreshIndex.onSuccess.bind(this.btnRefreshIndex),this.btnRefreshIndex.onFailure.bind(this.btnRefreshIndex))},clearErrors:function(){Brainstorm.Web.Services.Admin.ClearErrors(this.btnClearSolrErrors.onSuccess.bind(this.btnClearSolrErrors),this.btnClearSolrErrors.onFailure.bind(this.btnClearSolrErrors))}});
BrainstormJs.Admin.Forms.Instance.AdminSendEmailsForm=Class.create(BrainstormJs.Admin.Forms.BaseAdminForm,{emailTemplates:[{heading:"Testing Emails"},{name:"Verification Email",templatePath:"Email/Welcome",subject:"Welcome to Brainstorm! Please verify your email address to Sign In.",contextualFieldIds:["dateTrialExpires"],extraData:["personFirstName","FirstName","BaseURL","https://intuit.intuitbrainstorm.com"],onBeforeRender:function(parentForm){var date=new Date(parentForm.getFieldValue("dateTrialExpires"));
if(!isNaN(date.getTime())){this.extraData=this.extraData.concat(["activeTrialMode","_TRUE_"]);if(new Date>=date)this.extraData=this.extraData.concat(["trialExpired","_TRUE_"])}}},{heading:"Trial Response Emails"},{name:"Trial Created Email",templatePath:"Email/Trial/TrialCreated",subject:"Your Brainstorm trial has been created!",contextualFieldIds:["recipientFirstName","tenantSubdomain","validEmailDomain"]},{name:"Existing Trial Email",templatePath:"Email/Trial/TrialCreated",subject:"Your Brainstorm trial is already up and running!",
contextualFieldIds:["recipientFirstName","tenantSubdomain","validEmailDomain"],extraData:["TrialExists","true"]},{name:"Trial Ended Email",templatePath:"Email/Trial/TrialEnded",subject:"Your Brainstorm trial has already ended",contextualFieldIds:["tenantSubdomain","recipientFirstName"]},{name:"Paid Customer Email",templatePath:"Email/Trial/PaidCustomer",subject:"Your organization is already using Brainstorm!",contextualFieldIds:["tenantSubdomain","recipientFirstName","adminContactName","adminContactEmail"]},
{name:"Non-Unique Email",templatePath:"Email/Trial/NonUniqueEmail",subject:"Setting up your Brainstorm trial",contextualFieldIds:["recipientFirstName","emailDomain"]}],toEmails:false,previewFrame:false,btnPreview:false,btnSend:false,ddEmails:false,txtFromDisplay:false,txtSubject:false,initialize:function($super,container,options){this.ddEmails=$("ddEmailTemplate");this.previewFrame=$("previewFrame");this.wireEmailsDropdown();$super(container,options);this.wireTaskButton("btnGetTrialEmails");this.wireTaskButton("btnGetNetworkAdminEmails");
this.wireTaskButton("btnGetApiDevelopers");$("copyButton").observe("click",function(e){this.copyTable();e.stop()}.bind(this))},copyTable:function(){var div=[];div=$$(".copyThis");if(div.length>0)if(div[0].up().visible()){console.info("0");this.selectElementContents(div[0])}else if(div[1].up().visible()){console.info("1");this.selectElementContents(div[1])}else console.error("non")},selectElementContents:function(el){var body=document.body,range,sel;if(body.createTextRange){range=body.createTextRange();
range.moveToElementText(el);range.select()}else if(document.createRange&&window.getSelection){range=document.createRange();range.selectNodeContents(el);sel=window.getSelection();sel.removeAllRanges();sel.addRange(range)}},wireTaskButton:function(buttonId){var button=this.getField(buttonId);if(button)button.onClick=function(){this.executeTask(button)}.bind(this)},executeTask:function(button){Brainstorm.Web.Services.Admin.ExecuteTask(bsCommon.getRequestToken(),button.id,button.onSuccess.bind(button),
button.onFailure.bind(button));$("copyButton").appear()},wireActionButtons:function(){this.txtFromDisplay=this.getField("txtEmailFromDisplay");this.txtSubject=this.getField("txtSubject");this.btnPreview=this.getField("btnPreviewEmail");this.btnSend=this.getField("btnSendEmail");this.wireButton(this.btnPreview,function(){this.doEmail(this.btnPreview,false)}.bind(this));this.wireButton(this.btnSend,function(){this.doEmail(this.btnSend,true)}.bind(this))},wireEmailsDropdown:function(){this.ddEmails.update("");
for(var i=0;i<this.emailTemplates.length;i++)if(this.emailTemplates[i].heading!=null)this.ddEmails.insert((new Element("option",{"value":i})).update("------- "+this.emailTemplates[i].heading+" -------"));else this.ddEmails.insert((new Element("option",{"value":i})).update(this.emailTemplates[i].name));this.ddEmails.observe("change",this.changeEmailTemplate.bind(this))},wireButton:function(button,fnAction){if(button)button.onClick=fnAction},doEmail:function(button,actuallySend){var emailTemplate=this.emailTemplates[this.getFieldValue("ddEmailTemplate")];
if(emailTemplate.onBeforeRender!=null)emailTemplate.onBeforeRender(this);Brainstorm.Web.Services.Admin.SendManualEmail(this.getFieldValue("txtEmailTo"),emailTemplate.subject,emailTemplate.templatePath,this.txtFromDisplay.getValue(),emailTemplate.extraData!=null?this.getContextualFieldValues().concat(emailTemplate.extraData):this.getContextualFieldValues(),actuallySend,function(data){this.onSuccess(data,button)}.bind(this),button.onFailure.bind(button))},onSuccess:function(email,button){button.stopProcessing(this.errorDiv,
this.doneLabel);if(button!=this.btnPreview){var closeButton='<a href="javascript:;" onClick="$(this).up().blindUp();" class="close">close</a>';button.outputDiv.innerHTML=closeButton+"Email sent";button.outputDiv.blindDown({duration:0.5})}else this.previewFrame.contentDocument.body.innerHTML=email.HTML},changeEmailTemplate:function(){var templateIndex=this.getFieldValue(this.ddEmails.identify());var emailTemplate=this.emailTemplates[templateIndex];if(emailTemplate.heading==null&&templateIndex!=0){this.setContextualFields(emailTemplate.contextualFieldIds);
this.txtSubject.setValue(emailTemplate.subject);this.txtFromDisplay.setValue(emailTemplate.fromDisplay!=null?emailTemplate.fromDisplay:"Brainstorm Support");$("SubmitButtonContainer").appear()}else{this.txtSubject.setValue("");$("SubmitButtonContainer").fade();this.setContextualFields([])}},setContextualFields:function(activeContextFieldIds){var contextualFieldsContainer=$("contextualFields");var contextualFields=contextualFieldsContainer.childElements();for(var i=0;i<contextualFields.length;i++){var field=
this.getField(contextualFields[i].select("input,select")[0].identify());if(this.requiresField(field,activeContextFieldIds)){field.enable();contextualFields[i].show()}else{field.disable();contextualFields[i].hide()}}contextualFieldsContainer.show()},getContextualFieldValues:function(){var contextualFields=$("contextualFields").childElements();var values=new Array;for(var i=0;i<contextualFields.length;i++){var inputElem=contextualFields[i].select("input,select")[0];if(!inputElem.disabled){var field=
this.getField(inputElem.identify());values.push(field.id);values.push(this.getFieldValue(field.id))}}return values},requiresField:function(field,activeFieldIds){for(var i=0;i<activeFieldIds.length;i++)if(field.id==activeFieldIds[i])return true;return false},verificationEmailLogic:function(emailTemplate){var expiresDate=this.getFieldValue("dateTrialExpires");console.log(new Date(expiresDate))},saveData:function(){}});
BrainstormJs.Admin.Forms.Instance.AdminTasksForm=Class.create(BrainstormJs.Admin.Forms.BaseAdminForm,{wireActionButtons:function(){this.wireTaskButton("btnShowWebConfig");this.wireTaskButton("btnUpdateSchema");this.wireTaskButton("btnUpdateIdeaSearchText");this.wireTaskButton("btnUpdateChallenges");this.wireTaskButton("btnUpdatePipelines");this.wireTaskButton("btnSetHasReviewsFlag");this.wireTaskButton("btnSetNeedsHelpFlag");this.wireTaskButton("btnDecayRecentActivity");this.wireTaskButton("btnUpdateActivityScores");
this.wireTaskButton("btnRebalanceBayesianScores");this.wireTaskButton("btnUpdatePhotoExists");this.wireTaskButton("btnSendInstantNotifications");this.wireTaskButton("btnSendDailyNotifications");this.wireTaskButton("btnSendWeeklyNotifications");this.wireTaskButton("btnProcessEmails");this.wireTaskButton("btnSendSeatsInfo");this.wireTaskButton("btnSendMetrics");this.wireTaskButton("btnLogMetricsCache");this.wireTaskButton("btnReseedShareMessages");this.wireTaskButton("btnReseedShareRecipients");this.wireTaskButton("btnInferUsernameFromEmail");
this.wireTaskButton("btnSyncChallengeStatus");this.wireTaskButton("btnViewPublicKey");this.wireTaskButton("btnViewApiKey");this.wireTaskButton("btnMigrateRatings")},wireTaskButton:function(buttonId){var button=this.getField(buttonId);if(button)button.onClick=function(){this.executeTask(button)}.bind(this)},executeTask:function(button){Brainstorm.Web.Services.Admin.ExecuteTask(bsCommon.getRequestToken(),button.id,button.onSuccess.bind(button),button.onFailure.bind(button))},saveData:function(){}});
BrainstormJs.Admin.Forms.Instance.AdminTenantForm=Class.create(BrainstormJs.Admin.Forms.BaseAdminForm,{saveData:function(){var tenantIdField=$("tenantId");var tenantId=false;if(tenantIdField)tenantId=parseInt(tenantIdField.value);var editMode=tenantId>0;var tenantName=this.getFieldValue("txtTenantName");var tenantSubdomain=this.getFieldValue("txtTenantSubdomain");var allowUserSignup=this.getFieldValue("radAllowUserSignup");var loginLabel=this.getFieldValue("txtTenantLoginLabel");var signInIntro=this.getFieldValue("txtTenantSignInIntro");
var signUpIntro=this.getFieldValue("txtTenantSignUpIntro");var loginFailureMsg=this.getFieldValue("txtTenantLoginFailureMsg");var storeDocsInEuZone=this.getFieldValue("radStoreDocsInEuZone");var enableMetricsReporting=this.getFieldValue("radEnableMetricsReporting");var enableAnalyticsReporting=this.getFieldValue("radEnableAnalyticsReporting");var radImapEnabled=this.getFieldValue("radImapEnabled");var allowBulkUpload=this.getFieldValue("radAllowBulkUserUpload");var txtTenantAdmins=this.getFieldValue("txtTenantAdmins");
var txtSignUpDomainWhitelist=this.getFieldValue("txtSignUpDomainWhitelist");var txtEmailWhitelist=this.getFieldValue("txtEmailWhitelist");var txtEmailHtml=this.getFieldValue("txtEmailHtml");var openInno=this.getFieldValue("radOpenInnovationMode");var trialMode=this.getFieldValue("radTrialMode");var trialLength=this.getFieldValue("txtTrialLength");var txtValidIPRanges=this.getFieldValue("txtValidIPRanges");var txtRequestorEmail=this.getFieldValue("txtRequestorEmail");var txtRequestorFirstName=this.getFieldValue("txtRequestorFirstName");
if(editMode)Brainstorm.Web.Services.Admin.UpdateTenant(bsCommon.getRequestToken(),tenantId,tenantName,tenantSubdomain,allowUserSignup,loginLabel,signInIntro,signUpIntro,loginFailureMsg,storeDocsInEuZone,enableMetricsReporting,enableAnalyticsReporting,allowBulkUpload,txtTenantAdmins,txtSignUpDomainWhitelist,txtEmailWhitelist,txtValidIPRanges,txtEmailHtml,openInno,trialMode,trialLength,txtRequestorEmail,txtRequestorFirstName,radImapEnabled,this.afterSaveData.bind(this),this.processAjaxError.bind(this));
else Brainstorm.Web.Services.Admin.CreateTenant(bsCommon.getRequestToken(),tenantName,tenantSubdomain,allowUserSignup,loginLabel,signInIntro,signUpIntro,loginFailureMsg,storeDocsInEuZone,enableMetricsReporting,enableAnalyticsReporting,allowBulkUpload,txtTenantAdmins,txtSignUpDomainWhitelist,txtEmailWhitelist,txtValidIPRanges,txtEmailHtml,openInno,trialMode,trialLength,txtRequestorEmail,txtRequestorFirstName,radImapEnabled,this.afterCreate.bind(this),this.processAjaxError.bind(this))},afterCreate:function(jsonTenant){document.location.href=
document.location.href+"?id="+jsonTenant.Id}});
BrainstormJs.Admin.Forms.Tenant.BulkDeactivateForm=Class.create(BrainstormJs.Admin.Forms.BaseAdminForm,{btnDeactivateUsers:false,btnCancel:false,key:false,deactivatePreview:false,bulkDeacErrors:false,initialize:function($super,container,options){var fileUploadedCallback=this.fileUploaded.bind(this);var fileQueuedCallback=this.fileQueued.bind(this);options=options||{};options.fileUploadedCallback=fileUploadedCallback;options.fileQueuedCallback=fileQueuedCallback;options.fileUploadOptions={fileTypes:"*.csv",
fileTypesDescription:"CSV Files"};$super(container,options)},clearForm:function(clearFileUpload){if(this.deactivatePreview.hasClassName("visible")){this.deactivatePreview.up().fade();this.deactivatePreview.removeClassName("visible");this.deactivatePreview.update("")}if(this.bulkDeacErrors.hasClassName("visible")){this.bulkDeacErrors.up().fade();this.bulkDeacErrors.removeClassName("visible");this.bulkDeacErrors.update("")}if(clearFileUpload){var fups=this.getFileUpload();for(var i=0;i<fups.length;i++)fups[i].clear()}},
fileUploaded:function(){this.deactivateUsers()},fileQueued:function(){this.clearForm(false)},wireActionButtons:function(){this.btnDeacUsers=this.getField("btnDeacUsers");this.btnDeacUsers.onClick=this.deactivateUsers.bind(this);this.btnDeactivateUsers=this.getField("btnDeactivateUsers");this.btnDeactivateUsers.onClick=this.commit.bind(this);this.btnCancel=this.btnDeactivateUsers.container.down("a.cancelButton");this.btnCancel.observe("click",function(e){this.cancelCommit();e.stop()}.bind(this));this.deactivatePreview=
$("deactivatePreview");this.bulkDeacErrors=$("bulkDeacErrors")},showProcessing:function(){this.processing=(new Element("span",{"class":"processing"})).update("Processing ...");this.deactivatePreview.insert(this.processing);this.processing.pulsate();this.deactivatePreview.up().appear();this.btnDeactivateUsers.container.hide()},hideProcessing:function(){if(!this.processing)return;this.processing.fade()},cancelCommit:function(){this.clearForm(true)},deactivateUsers:function(){this.disableUploads();this.showProcessing();
Brainstorm.Web.Services.TenantAdmin.PreviewDeactiveUsers($("csvDeacFileName").value,this.wireUserPreview.bind(this),this.btnDeacUsers.onFailure.bind(this.btnDeacUsers))},commit:function(){this.disableUploads();Brainstorm.Web.Services.TenantAdmin.ConfirmDeactivateUsers(this.key,this.wireUsersCommitted.bind(this),this.btnDeactivateUsers.onFailure.bind(this.btnDeactivateUsers))},wireUserPreview:function(listHtml){this.key=listHtml.Id;this.hideProcessing();if(this.key!="error"){this.deactivatePreview.update(listHtml.HTML);
this.deactivatePreview.addClassName("visible");this.deactivatePreview.up().appear();this.btnDeactivateUsers.button.appear();this.btnCancel.appear();this.btnDeactivateUsers.container.appear()}else{this.deactivatePreview.up().hide();this.bulkDeacErrors.update(listHtml.HTML);this.bulkDeacErrors.addClassName("visible");this.bulkDeacErrors.up().appear()}this.enableUploads()},wireUsersCommitted:function(message){this.enableUploads();this.btnDeactivateUsers.stopProcessing(this.btnDeactivateUsers.container);
this.deactivatePreview.update(message)},saveData:function(){}});
BrainstormJs.Admin.Forms.Tenant.BulkUserImportForm=Class.create(BrainstormJs.Admin.Forms.BaseAdminForm,{btnLoadUsers:false,btnCommitUsers:false,btnCancel:false,key:false,userPreviewList:false,errorsList:false,asyncUpdaterExec:false,importProgressBar:false,imptProgDiv:false,processing:false,initialize:function($super,container,options){var fileUploadedCallback=this.fileUploaded.bind(this);var fileQueuedCallback=this.fileQueued.bind(this);options=options||{};options.fileUploadedCallback=fileUploadedCallback;
options.fileQueuedCallback=fileQueuedCallback;options.fileUploadOptions={fileTypes:"*.csv",fileTypesDescription:"CSV Files"};$super(container,options)},clearForm:function(clearFileUpload){if(this.userPreviewList.hasClassName("visible")){this.userPreviewList.up().fade();this.userPreviewList.removeClassName("visible");this.userPreviewList.update("")}if(this.errorsList.hasClassName("visible")){this.errorsList.up().fade();this.errorsList.removeClassName("visible");this.errorsList.update("")}if(clearFileUpload)this.resetUploads()},
fileUploaded:function(){this.importByCsv()},fileQueued:function(){this.clearForm(false)},wireActionButtons:function(){this.btnLoadUsers=this.getField("btnLoadUsers");this.btnLoadUsers.onClick=this.importByCsv.bind(this);this.btnCommitUsers=this.getField("btnCommitUsers");this.btnCommitUsers.onClick=this.commitUsers.bind(this);this.btnCancel=this.btnCommitUsers.container.down("a.cancelButton");this.btnCancel.observe("click",function(e){this.cancelCommit();e.stop()}.bind(this));this.userPreviewList=
$("userPreview");this.errorsList=$("bulkUploadErrors")},cancelCommit:function(){this.clearForm(true)},showProcessing:function(){this.processing=(new Element("span",{"class":"processing"})).update("Processing ...");this.userPreviewList.insert(this.processing);this.processing.pulsate();this.userPreviewList.up().appear();this.btnCommitUsers.container.hide()},hideProcessing:function(){if(!this.processing)return;this.processing.fade();this.userPreviewList.up().toggle()},importByCsv:function(){this.disableUploads();
this.showProcessing();Brainstorm.Web.Services.TenantAdmin.ImportByCsv($("csvFileName").value,this.wireUserPreview.bind(this),this.importFailed.bind(this))},importFailed:function(error){this.btnLoadUsers.onFailure(error);this.hideProcessing();window.setTimeout(function(){this.clearForm(true)}.bind(this),3E3)},commitUsers:function(){this.disableUploads();Brainstorm.Web.Services.TenantAdmin.CommitPendingUsers(this.key,this.wireUsersCommitted.bind(this),this.btnCommitUsers.onFailure.bind(this.btnCommitUsers))},
wireUserPreview:function(listHtml){this.btnLoadUsers.stopProcessing(this.btnLoadUsers.container);this.key=listHtml.Id;this.hideProcessing();if(this.key!="error"){this.userPreviewList.update(listHtml.HTML);this.userPreviewList.addClassName("visible");this.userPreviewList.up().appear();$("btnCommitUsers").appear();this.btnCancel.appear();if(!this.btnCommitUsers.container.visible())this.btnCommitUsers.container.toggle()}else{this.userPreviewList.up().fade();this.errorsList.update(listHtml.HTML);this.errorsList.addClassName("visible");
this.errorsList.up().appear()}this.enableUploads()},wireUsersCommitted:function(async){this.disableUploads();this.btnCommitUsers.stopProcessing(this.btnCommitUsers.container);var splits=async.Id.split("_");var status=splits[0];var id=splits[1];if(status=="Running"){if(!this.asyncUpdaterExec)this.initPeriodicUpdater(id);this.userPreviewList.update(async.HTML);this.initProgressBar()}else if(status=="Completed"){this.userPreviewList.update(async.HTML);this.enableUploads()}else;},initProgressBar:function(){if(!this.importProgressBar){this.imptProgDiv=
this.userPreviewList.down(".progressBar");this.imptProgDiv.appear();this.importProgressBar=new Control.ProgressBar(this.imptProgDiv.identify(),{})}},initPeriodicUpdater:function(id){var checkInterval=5;var fxUpdateAsync=this.updateAsyncProgress.bind(this);var fxUpdateAsyncError=this.updateAsyncError.bind(this);var fxPeriodicTask=function(pe){Brainstorm.Web.Services.TenantAdmin.PollAsyncTask(id,fxUpdateAsync,fxUpdateAsyncError)}.bind(this);this.asyncUpdaterExec=new PeriodicalExecuter(fxPeriodicTask,
checkInterval)},updateAsyncProgress:function(json){var statusMsg=this.userPreviewList.down(".statusMsg");if(statusMsg=="undefined")return;if(json.Status=="Running"){var progress=json.Progress;this.importProgressBar.setProgress(progress);var message=json.Message;new Effect.Highlight(statusMsg,{endcolor:"#F7FBFD"})}else if(json.Status=="Completed"){var successMsg=this.userPreviewList.down(".successMessage").innerHTML;this.userPreviewList.down("h5").innerHTML=successMsg;$("asyncStatus").removeClassName("Running");
$("asyncStatus").addClassName("Completed");this.userPreviewList.pulsate();this.asyncUpdaterExec.stop();this.importProgressBar.step(100);this.imptProgDiv.fade();this.asyncUpdaterExec=false;this.enableUploads()}else if(json.Status=="Error"){$("asyncStatus").removeClassName("Running");$("asyncStatus").addClassName("Error");this.enableUploads()}statusMsg.update(json.Message)},updateAsyncError:function(json){var div=this.userPreviewList.down(".Running");div.removeClassName("Running");div.addClassName("Error");
if(div.down("h5"))div.down("h5").update("Uh oh! An error occurred while attempting to commit users:");var statusMsg=this.userPreviewList.down(".statusMsg");statusMsg.update("Message: "+json._message+'. Please try again or contact <a href="mailto:support@intuitbrainstorm.com">Intuit Brainstorm Support</a>');if(this.asyncUpdaterExec){this.asyncUpdaterExec.stop();this.asyncUpdaterExec=false}this.importProgressBar.stop();this.imptProgDiv.fade();this.enableUploads()},saveData:function(){}});
BrainstormJs.Admin.Forms.Tenant.ChallengeSettingsForm=Class.create(BrainstormJs.Admin.Forms.BaseAdminForm,{saveData:function(){Brainstorm.Web.Services.TenantAdmin.UpdateChallengeSettings(bsCommon.getRequestToken(),this.getFieldValue("radEnableChallenges"),this.getFieldValue("radOpenChallengeCreation"),this.getFieldValue("txtChallengeTemplate"),this.afterSaveData.bind(this),this.processAjaxError.bind(this))},wireFields:function(){var template=$("challengeCreateTemplate");var templateField=this.getField("txtChallengeTemplate");
if(template&&templateField)window.setTimeout(function(){templateField.setValue(template.innerHTML)}.bind(this),100)}});
BrainstormJs.Admin.Forms.Tenant.DirectoryImportForm=Class.create(BrainstormJs.Admin.Forms.BaseAdminForm,{btnImportUserByEmail:false,btnImportUserByLogin:false,wireActionButtons:function(){this.btnImportUserByEmail=this.getField("btnImportUserByEmail");this.btnImportUserByEmail.onClick=this.importByEmail.bind(this);this.btnImportUserByLogin=this.getField("btnImportUserByLogin");this.btnImportUserByLogin.onClick=this.importByLogin.bind(this);this.btnRenameLogin=this.getField("btnRenameLogin");this.btnRenameLogin.onClick=
this.renameLogin.bind(this)},importByEmail:function(){Brainstorm.Web.Services.TenantAdmin.ImportDirectoryPersonByEmail(this.getFieldValue("btnImportUserByEmail"),this.btnImportUserByEmail.onSuccess.bind(this.btnImportUserByEmail),this.btnImportUserByEmail.onFailure.bind(this.btnImportUserByEmail))},importByLogin:function(){Brainstorm.Web.Services.TenantAdmin.ImportDirectoryPersonByLogin(this.getFieldValue("btnImportUserByLogin"),this.btnImportUserByLogin.onSuccess.bind(this.btnImportUserByLogin),
this.btnImportUserByLogin.onFailure.bind(this.btnImportUserByLogin))},renameLogin:function(){Brainstorm.Web.Services.TenantAdmin.RenameLogin(this.getFieldValue("btnRenameLogin"),this.btnRenameLogin.onSuccess.bind(this.btnRenameLogin),this.btnRenameLogin.onFailure.bind(this.btnRenameLogin))},saveData:function(){}});
BrainstormJs.Admin.Forms.Tenant.EmailSettingsForm=Class.create(BrainstormJs.Admin.Forms.BaseAdminForm,{txtRrEmail:false,btnReplayRrEmails:false,wireActionButtons:function(){this.txtRrEmail=$("txtRrEmail");if(this.txtRrEmail!=null){this.btnReplayRrEmails=this.getField("btnReplayRrEmails");this.btnReplayRrEmails.onClick=this.replayEmails.bind(this)}},replayEmails:function(){Brainstorm.Web.Services.TenantAdmin.ReplayRrEmails(this.getFieldValue("txtDaysToReplay"),this.getFieldValue("txtRrEmail"),this.btnReplayRrEmails.onSuccess.bind(this.btnReplayRrEmails),
this.btnReplayRrEmails.onFailure.bind(this.btnReplayRrEmails))},saveData:function(){var rrEmail="";if(this.txtRrEmail!=null)rrEmail=this.getFieldValue("txtRrEmail");Brainstorm.Web.Services.TenantAdmin.UpdateEmailSettings(bsCommon.getRequestToken(),this.getFieldValue("txtSupportEmail"),this.getFieldValue("txtStuckRecipients"),this.getFieldValue("txtMailerDisplayName"),this.getFieldValue("txtSubjectPrepender"),this.getFieldValue("radEnableBrainstormFeedback"),rrEmail,this.afterSaveData.bind(this),this.processAjaxError.bind(this))}});
BrainstormJs.Admin.Forms.Tenant.GeneralSettingsForm=Class.create(BrainstormJs.Admin.Forms.BaseAdminForm,{saveData:function(){Brainstorm.Web.Services.TenantAdmin.UpdateGeneralSettings(bsCommon.getRequestToken(),this.getFieldValue("txtTenantName"),this.getFieldValue("txtAreaName"),this.getFieldValue("radShowNews"),this.getFieldValue("radShowStoreLink"),this.getFieldValue("txtFooterText"),this.afterGeneralUpdate.bind(this),this.processAjaxError.bind(this))},afterGeneralUpdate:function(jsonTenant){this.afterSaveData();
var areasTabLink=$("tabIdeaAreas_link").down("span");areasTabLink.update(jsonTenant.AreaNamePlural);areasTabLink.appear({from:0.25,to:1})}});BrainstormJs.Admin.Forms.Tenant.MiscSettingsForm=Class.create(BrainstormJs.Admin.Forms.BaseAdminForm,{saveData:function(){Brainstorm.Web.Services.TenantAdmin.UpdateGeekySettings(bsCommon.getRequestToken(),this.getFieldValue("radShowExceptionDetails"),this.getFieldValue("txtGoogleAnalyticsId"),"",this.afterSaveData.bind(this),this.processAjaxError.bind(this))}});
BrainstormJs.Admin.Forms.Tenant.PipelineSettingsForm=Class.create(BrainstormJs.Admin.Forms.BaseAdminForm,{saveData:function(){Brainstorm.Web.Services.TenantAdmin.UpdatePipelineSettings(bsCommon.getRequestToken(),this.getFieldValue("radEnablePipelines"),this.getFieldValue("radOpenPipelineCreation"),this.afterSaveData.bind(this),this.processAjaxError.bind(this))}});
BrainstormJs.Admin.Forms.Tenant.ProfileInfoSettingsForm=Class.create(BrainstormJs.Admin.Forms.BaseAdminForm,{saveData:function(){Brainstorm.Web.Services.TenantAdmin.UpdateProfileInfoSettings(this.getFieldValue("radEditProfilePhoto"),this.getFieldValue("radEditProfileInfo"),this.afterSaveData.bind(this),this.processAjaxError.bind(this))}});
BrainstormJs.Admin.Forms.Tenant.UserRegistrationForm=Class.create(BrainstormJs.Admin.Forms.BaseAdminForm,{saveData:function(){Brainstorm.Web.Services.TenantAdmin.UpdateRegistrationSettings(bsCommon.getRequestToken(),this.getFieldValue("radAllowUserSignup"),this.getFieldValue("radCheckRememberMe"),this.getFieldValue("txtDomainWhitelist"),this.getFieldValue("txtEmailWhitelist"),this.getFieldValue("radRequireTerms"),this.getFieldValue("txtTermsOfService"),this.getFieldValue("txtPasswordLength"),this.getFieldValue("chkPassReqNum"),
this.getFieldValue("chkPassReqLowLet"),this.getFieldValue("chkPassReqUpLet"),this.getFieldValue("chkPassSpecChar"),this.getFieldValue("radReverify"),this.getFieldValue("txtReverifyDays"),this.afterSaveData.bind(this),this.processAjaxError.bind(this))}});
BrainstormJs.Admin.Forms.Tenant.UserSearchForm=Class.create(BrainstormJs.Admin.Forms.BaseAdminForm,{btnFindUserByEmail:false,btnFindUserByLogin:false,btnFindUsersByKeyword:false,wireActionButtons:function(){this.btnFindUserByEmail=this.getField("btnFindUserByEmail");this.btnFindUserByEmail.onClick=this.findByEmail.bind(this);this.btnFindUserByLogin=this.getField("btnFindUserByLogin");this.btnFindUserByLogin.onClick=this.findByLogin.bind(this);this.btnFindUsersByKeyword=this.getField("btnFindUsersByKeyword");
this.btnFindUsersByKeyword.onClick=this.findByKeyword.bind(this)},findByEmail:function(){Brainstorm.Web.Services.TenantAdmin.FindPersonByEmail(this.getFieldValue("btnFindUserByEmail"),this.btnFindUserByEmail.onSuccess.bind(this.btnFindUserByEmail),this.btnFindUserByEmail.onFailure.bind(this.btnFindUserByEmail))},findByLogin:function(){Brainstorm.Web.Services.TenantAdmin.FindPersonByLogin(this.getFieldValue("btnFindUserByLogin"),this.btnFindUserByLogin.onSuccess.bind(this.btnFindUserByLogin),this.btnFindUserByLogin.onFailure.bind(this.btnFindUserByLogin))},
findByKeyword:function(){Brainstorm.Web.Services.TenantAdmin.FindPeopleByKeyword(this.getFieldValue("btnFindUsersByKeyword"),this.btnFindUsersByKeyword.onSuccess.bind(this.btnFindUsersByKeyword),this.btnFindUsersByKeyword.onFailure.bind(this.btnFindUsersByKeyword))},saveData:function(){}});BrainstormJs.Admin.Pages.AdminActiveDirectoryPage=Class.create({initialize:function(){var tenantLdapForm=new BrainstormJs.Admin.Forms.Instance.AdminActiveDirectoryForm("activeDirectoryForm")}});
BrainstormPages.register(BrainstormJs.Admin.Pages.AdminActiveDirectoryPage,"/Admin/ActiveDirectory.aspx");
BrainstormJs.Admin.Pages.AdminBrandingPage=Class.create({imageUploadForm:false,outerHeaderBgUploadForm:false,innerHeaderBgUploadForm:false,quickSearchButtonUploadForm:false,replacementCSSForm:false,initialize:function(){var tId=$("tenantId").value;var errorDescriptionElement=$("imageUploadError").down(".ajaxErrorInfo");this.imageUploadForm=new BrainstormJs.Admin.Forms.Instance.AdminBrandingImageForm("logoImageUpload",{tenantId:tId,brandingImageType:"Logo",baseElementId:"logo",errorElement:errorDescriptionElement});
this.outerHeaderBgUploadForm=new BrainstormJs.Admin.Forms.Instance.AdminBrandingImageForm("outerHeaderBgImageUpload",{tenantId:tId,brandingImageType:"OuterHeaderBg",baseElementId:"outerHeaderBg",errorElement:errorDescriptionElement});this.innerHeaderBgUploadForm=new BrainstormJs.Admin.Forms.Instance.AdminBrandingImageForm("innerHeaderBgImageUpload",{tenantId:tId,brandingImageType:"InnerHeaderBg",baseElementId:"innerHeaderBg",errorElement:errorDescriptionElement});this.menuSelectBgUploadForm=new BrainstormJs.Admin.Forms.Instance.AdminBrandingImageForm("menuSelectBgImageUpload",
{tenantId:tId,brandingImageType:"MenuSelectBg",baseElementId:"menuSelectBg",errorElement:errorDescriptionElement});this.userMenuBgUploadForm=new BrainstormJs.Admin.Forms.Instance.AdminBrandingImageForm("userMenuBgImageUpload",{tenantId:tId,brandingImageType:"UserMenuBg",baseElementId:"userMenuBg",errorElement:errorDescriptionElement});this.userMenuDropdownUploadForm=new BrainstormJs.Admin.Forms.Instance.AdminBrandingImageForm("userMenuDropdownIconImageUpload",{tenantId:tId,brandingImageType:"UserMenuDropdownIcon",
baseElementId:"userMenuDropdownIcon",errorElement:errorDescriptionElement});this.quickSearchButtonUploadForm=new BrainstormJs.Admin.Forms.Instance.AdminBrandingImageForm("quickSearchButtonImageUpload",{tenantId:tId,brandingImageType:"QuickSearchButton",baseElementId:"quickSearchButton",errorElement:errorDescriptionElement});this.signInHeaderUploadForm=new BrainstormJs.Admin.Forms.Instance.AdminBrandingImageForm("signInHeaderImageUpload",{tenantId:tId,brandingImageType:"SignInHeader",baseElementId:"signInHeader",
errorElement:errorDescriptionElement});this.emailHeaderUploadForm=new BrainstormJs.Admin.Forms.Instance.AdminBrandingImageForm("emailHeaderImageUpload",{tenantId:tId,brandingImageType:"EmailHeader",baseElementId:"emailHeader",errorElement:errorDescriptionElement});this.replacementCSSForm=new BrainstormJs.Admin.Forms.Instance.AdminReplaceCSSForm("replacementCSSForm",{tenantId:tId,editTextBoxId:"txtReplacementCSS"})}});BrainstormPages.register(BrainstormJs.Admin.Pages.AdminBrandingPage,"/Admin/Branding.aspx");
BrainstormJs.Admin.Pages.AdminCacheSettingsPage=Class.create({initialize:function(){var form=new BrainstormJs.Admin.Forms.Instance.AdminCacheSettingsForm("cacheSettingsForm")}});BrainstormPages.register(BrainstormJs.Admin.Pages.AdminCacheSettingsPage,"/Admin/ContentCache.aspx");BrainstormJs.Admin.Pages.AdminEmailSettingsPage=Class.create({initialize:function(){var form=new BrainstormJs.Admin.Forms.Instance.AdminEmailSettingsForm("emailSettingsForm")}});
BrainstormPages.register(BrainstormJs.Admin.Pages.AdminEmailSettingsPage,"/Admin/EmailSettings.aspx");BrainstormJs.Admin.Pages.AdminEmailsPage=Class.create({initialize:function(){var form=new BrainstormJs.Admin.Forms.Instance.AdminSendEmailsForm("sendEmailsForm")}});BrainstormPages.register(BrainstormJs.Admin.Pages.AdminEmailsPage,"/Admin/Emails.aspx");BrainstormJs.Admin.Pages.AdminFileStoragePage=Class.create({initialize:function(){var form=new BrainstormJs.Admin.Forms.Instance.AdminFileStorageForm("fileStorageForm")}});
BrainstormPages.register(BrainstormJs.Admin.Pages.AdminFileStoragePage,"/Admin/FileStorage.aspx");BrainstormJs.Admin.Pages.AdminInstancePage=Class.create({initialize:function(){var form=new BrainstormJs.Admin.Forms.Instance.AdminInstanceForm("instanceForm")}});BrainstormPages.register(BrainstormJs.Admin.Pages.AdminInstancePage,"/Admin/Instance.aspx");BrainstormJs.Admin.Pages.AdminIntegrationPage=Class.create({initialize:function(){var integrationForm=new BrainstormJs.Admin.Forms.Instance.AdminIntegrationForm("integrationForm")}});
BrainstormPages.register(BrainstormJs.Admin.Pages.AdminIntegrationPage,"/Admin/Integration.aspx");BrainstormJs.Admin.Pages.AdminMetricsPage=Class.create({initialize:function(){var form=new BrainstormJs.Admin.Forms.Instance.AdminMetricsForm("tasksForm")}});BrainstormPages.register(BrainstormJs.Admin.Pages.AdminMetricsPage,"/Admin/Metrics.aspx");BrainstormJs.Admin.Pages.AdminIntegrationPage=Class.create({initialize:function(){var integrationForm=new BrainstormJs.Admin.Forms.Instance.AdminRecordsRetentionForm("rrForm")}});
BrainstormPages.register(BrainstormJs.Admin.Pages.AdminIntegrationPage,"/Admin/RecordsRetention.aspx");BrainstormJs.Admin.Pages.AdminSearchPage=Class.create({initialize:function(){var form=new BrainstormJs.Admin.Forms.Instance.AdminSearchForm("searchTasksForm")}});BrainstormPages.register(BrainstormJs.Admin.Pages.AdminSearchPage,"/Admin/Search.aspx");
BrainstormJs.Admin.Pages.AdminTasksPage=Class.create({initialize:function(){var form=new BrainstormJs.Admin.Forms.Instance.AdminTasksForm("tasksForm");var emailTestForm=new BrainstormJs.Admin.Forms.Instance.AdminEmailTestForm("adminTestEmailForm")}});BrainstormPages.register(BrainstormJs.Admin.Pages.AdminTasksPage,"/Admin/Tasks.aspx");BrainstormJs.Admin.Pages.AdminTenantPage=Class.create({initialize:function(){var tenantForm=new BrainstormJs.Admin.Forms.Instance.AdminTenantForm("tenantForm")}});
BrainstormPages.register(BrainstormJs.Admin.Pages.AdminTenantPage,"/Admin/Tenant.aspx");
BrainstormJs.Admin.Pages.AllTenantsPage=Class.create({tenantGrid:false,tenantRows:false,radShowAll:false,radTrialsOnly:false,radNonTrialsOnly:false,filterBox:false,initialize:function(){try{this.tenantGrid=$("adminAllTenantsGrid");var trialRemainingElems=this.tenantGrid.select(".trialRemaining");for(var i=0,j=trialRemainingElems.length;i<j;i++){var trialRemainingElem=trialRemainingElems[i];this.convertTrialElem(trialRemainingElem)}this.filterBox=$("quickFilter");if(this.filterBox)this.filterBox.observe("keydown",
function(e){if(e.keyCode==Event.KEY_RETURN){this.filterTable();e.stop();return false}return true}.bind(this));this.radShowAll=$("radShowAll");if(this.radShowAll)this.radShowAll.observe("change",this.filterTable.bind(this));this.radTrialsOnly=$("radShowTrials");if(this.radTrialsOnly)this.radTrialsOnly.observe("change",this.filterTable.bind(this));this.radNonTrialsOnly=$("radShowNonTrials");if(this.radNonTrialsOnly)this.radNonTrialsOnly.observe("change",this.filterTable.bind(this))}catch(exception){console.warn(exception)}},
getTenantRows:function(){this.tenantRows=this.tenantGrid.select("tr.tenantRow")},convertTrialElem:function(statusEl){var trialMinutesLeft=parseInt(statusEl.innerHTML)+1;statusEl.update("");var countdown=this.convertMinutesToCountdown(trialMinutesLeft);var percent=Math.floor(trialMinutesLeft/(30*24*60)*100);if(percent>100)percent=100;else if(percent<=0)percent=0;if(percent>0){var countdownBar=new Element("div",{"class":"trialCountdownBar"});var rgb=[Math.round(Math.min(200-percent*2,100)/100*240),
Math.round(Math.min(percent*2,100)/100*190),65];var color="rgb("+rgb.join(",")+");";var countdownBarFill=new Element("div",{"style":"width:"+percent+"%; background-color: "+color});var detailText=new Element("span",{"class":"detailText","style":"display:none"});detailText.update("In Trial: "+countdown+" left");statusEl.update("&nbsp;");statusEl.insert(countdownBar.insert(countdownBarFill));statusEl.insert(detailText);bsCommon.setHoverFunction(countdownBar,function(){detailText.show()},function(){detailText.hide()})}else{var lengthExpired=
this.convertMinutesToCountdown(trialMinutesLeft*-1);var expiredEl=(new Element("span",{"class":"detailText"})).update("Trial Expired "+lengthExpired+" ago");statusEl.insert(expiredEl)}statusEl.show()},filterTable:function(){if(!this.tenantRows)this.getTenantRows();var searchTerm=this.filterBox?this.filterBox.getValue():"";var re=new RegExp(searchTerm,"i");var trialsOnly=this.radTrialsOnly?this.radTrialsOnly.getValue()!=null:false;var nonTrialsOnly=this.radNonTrialsOnly?this.radNonTrialsOnly.getValue()!=
null:false;for(var i=0,j=this.tenantRows.length;i<j;i++){var row=this.tenantRows[i];var showRow=false;var isTrialRow=row.hasClassName("trialRow");if((nonTrialsOnly&&isTrialRow||trialsOnly&&!isTrialRow)==false){var searchContent=this.getSearchContent(row);if(searchContent!=""&&re.test(searchContent))showRow=true}showRow?row.show():row.hide()}},getSearchContent:function(row){var searchContentEl=row.down(".tenantInfo");var searchContent="";while(searchContentEl){searchContent+=searchContentEl.innerHTML;
searchContentEl=searchContentEl.next(".tenantInfo")}return searchContent},convertMinutesToCountdown:function(minutesLeft){var remainingVal;var remainingUnit="day";if(minutesLeft<=0){remainingVal=0;remainingUnit="minute"}else if(minutesLeft<60){remainingVal=minutesLeft;remainingUnit="minute"}else if(minutesLeft<60*24){remainingVal=Math.floor(minutesLeft/60);remainingUnit="hour"}else remainingVal=Math.floor(minutesLeft/60/24);if(remainingVal!=1)remainingUnit+="s";return remainingVal+" "+remainingUnit}});
BrainstormPages.register(BrainstormJs.Admin.Pages.AllTenantsPage,"/Admin/Tenants.aspx");
BrainstormJs.Controls.ActionBox=Class.create({container:false,options:false,closeLink:false,initialize:function(container,options){this.container=container;this.options=options||{};if(!this.container){console.error("Could not find container for action box.");return}if(options&&options.triggers){var fxOpen=function(e){this.open();e.stop()}.bind(this);for(var i=0,j=options.triggers.length;i<j;i++){var trigger=options.triggers[i];if(trigger){trigger.observe("click",fxOpen);if(!trigger.visible())trigger.appear({duration:0.5})}}}this.closeLink=
this.container.down("div.actionBoxTitle a.close");this.closeLink.observe("click",function(e){this.manualClose(e.element());e.stop()}.bind(this))},open:function(linkClicked){var container=this.container;container.blindDown({duration:0.75,afterFinish:function(){bsCommon.scrollIfBelowFold(container,100,{scrollToTop:true,afterFinish:function(scrolled){if(scrolled)Effect.Pulsate(container,{pulses:2,duration:3,from:0.5,to:1})}})}});this.toggleTriggers(false);if(this.options.afterOpen)this.options.afterOpen()},
manualClose:function(linkClicked){this.container.fade({duration:0.5});this.toggleTriggers(true);if(this.options.afterClose)this.options.afterClose()},hideCloseLink:function(){this.closeLink.fade()},showCloseLink:function(){this.closeLink.appear()},toggleTriggers:function(show){if(this.options&&this.options.triggers)for(var i=0,j=this.options.triggers.length;i<j;i++){var trigger=this.options.triggers[i];if(trigger)trigger[show?"appear":"fade"]({duration:0.25})}},hide:function(){this.container.fade({duration:0.25})},
show:function(){this.container.blindDown({duration:0.5})},restore:function(){this.toggleTriggers(true);this.hide()},getCloseLink:function(){return this.closeLink},hideCloseLink:function(){this.closeLink.fade({duration:0.5})},showCloseLink:function(){this.closeLink.appear({duration:0.5})}});
BrainstormJs.Controls.AjaxContentPane=Class.create({container:false,options:false,loadingDiv:false,spinner:false,contentDiv:false,loaded:false,afterContentVisible:false,hiddenElements:false,openClass:"openAjaxPane",initialize:function(container,options){this.container=container;this.options=options;if(!this.container){console.error("Could not find container for AJAX preview pane.");return}this.loadingDiv=this.container.down("div.loading");this.contentDiv=this.container.down("div.content")},startLoading:function(options){if(this.loaded)return;
this.container.show();this.contentDiv.hide();if(options&&options.fadeTransition)this.loadingDiv.appear({duration:0.5,afterFinish:function(){if(options&&options.dataMethod)options.dataMethod()}});else this.loadingDiv.blindDown({duration:0.5,afterFinish:function(){if(options&&options.dataMethod)options.dataMethod()}});if(options&&options.hideElements&&options.hideElements.length){this.hiddenElements=options.hideElements;for(var i=0,j=this.hiddenElements.length;i<j;i++)this.hiddenElements[i].fade({duration:0.25})}this.afterContentVisible=
options&&options.afterContentVisible},insertContent:function(contentHTML,insertOptions,showOptions){this.contentDiv.innerHTML=contentHTML;window.setTimeout(function(){this.afterDomReady(insertOptions,showOptions)}.bind(this),0)},afterDomReady:function(insertOptions,showOptions){this.loaded=true;if(insertOptions){if(insertOptions.onContentReady)insertOptions.onContentReady();if(insertOptions.autoShow)this.showContent(showOptions)}},showContent:function(options){var contentDiv=this.contentDiv;var afterContentVisible=
this.afterContentVisible;var transitionSettings={duration:1,afterFinish:function(){if(options&&options.scroll)bsCommon.scrollTo(contentDiv,{offset:options.scrollOffset});if(afterContentVisible)afterContentVisible()}};if(options&&options.fadeTransition){this.contentDiv.setOpacity(0.05);this.contentDiv.show();this.contentDiv.appear(transitionSettings);this.loadingDiv.hide()}else{this.contentDiv.blindDown(transitionSettings);this.loadingDiv.blindUp({duration:0.25,queue:"top"})}},close:function(options){this.container.blindUp({duration:0.5,
afterFinish:function(){this.loaded=false;this.contentDiv.hide();this.loadingDiv.show();if(options.destroyContent)this.contentDiv.innerHTML=""}.bind(this)});if(this.hiddenElements&&this.hiddenElements.length&&this.hiddenElements.length>0)for(var i=0,j=this.hiddenElements.length;i<j;i++)this.hiddenElements[i].appear({duration:0.5})},getContentDiv:function(){return this.contentDiv},visible:function(){return this.contentDiv.visible()},isLoaded:function(){return this.loaded}});
BrainstormJs.Controls.CustomButton=Class.create({value:false,element:false,altText:false,fxClick:false,initialize:function(options){options=options||{};this.value=options.value||false;this.fxClick=options.fxClick||false;this.altText=options.altText||false},render:function(renderOptions){this.element=(new Element("a",{"class":"customButton","href":"#","title":"Add as an interest"})).update(this.value);this.element.identify();this.element.observe("click",function(e){this.onClick();return false}.bind(this));
return this.element},onClick:function(){if(this.fxClick)this.fxClick(this)}});
BrainstormJs.Controls.HomeModeSelect=Class.create({menu:false,menuItems:false,modeContainer:false,activeItem:false,initialize:function(){},onChange:function(linkClicked){if(bsCommon.shakeIfDisabled(linkClicked))return;var previousActive=this.activeItem;var newActive=this.menuItems.get(linkClicked.id);this.activeItem=newActive;Effect.Fade(previousActive.activeDiv,{duration:0.5});Effect.Appear(newActive.activeDiv,{duration:0.5});Effect.Fade(previousActive.modeDiv,{duration:0.2,afterFinish:function(){Effect.Appear(newActive.modeDiv,
{duration:0.7})}})}});var BrainstormForms={instances:[],counter:1,tabIndex:200,openForms:0,add:function(formToAdd){formToAdd.id="baseForm-"+this.counter;this.counter++;this.instances.push(formToAdd)},remove:function(formToRemove){this.instances=this.instances.reject(function(form){return form.id==formToRemove.id})},getTabIndex:function(){return this.tabIndex++}};
BrainstormJs.Forms.BaseForm=Class.create({id:false,fields:[],validator:false,container:false,origFormsContainer:false,parentContainer:false,profile:false,fieldContainer:false,alwaysEditable:false,editingExisting:false,editObjectType:false,editObjectId:false,editObjectElement:false,createTitle:false,editTitle:false,action:"add",friendlyObjectName:"object",emptyMessage:false,introText:false,title:false,submitButton:false,submitButtonTitle:false,cancelButton:false,progressSpinner:false,openLinks:[],
scrollToBottom:true,options:false,closeSkipBlind:false,closeManually:false,replaceElement:false,initialize:function(profile,options){BrainstormForms.add(this);this.openLinks=options.openLinks||[];this.createTitle=options.createTitle||"Create New Object";this.editTitle=options.editTitle||"Edit";this.emptyMessage=options.emptyMessage||false;this.parentContainer=$(options.parentContainer);this.origFormsContainer=this.parentContainer;this.submitButtonTitle=options.submitButtonTitle||"Submit";this.replaceElement=
options.replaceElement||false;this.destroyOnClose=options.destroyOnClose||false;this.introText=options.introText||false;this.closeSkipBlind=options.closeSkipBlind||false;this.closeManually=options.closeManually||false;this.customFields=options.customFields||[];for(var i=0,j=this.openLinks.length;i<j;i++){var openLink=this.openLinks[i];if(typeof openLink=="string"){openLink=$(openLink);this.openLinks[i]=openLink}if(!(options.bindOpenLinks===false)&&openLink!=null){openLink.observe("click",function(e){this.showForm({linkClicked:e.element()});
e.stop()}.bind(this));if(options.appearOpenLink)openLink.appear()}}if(this.options.scrollToBottom!="undefined")this.scrollToBottom=options.scrollToBottom||this.scrollToBottom;this.profile=profile;this.options=options;this.fields=[];this.createFields();this.createCustomFields();this.container=this.render();this.validator=new Validation(this.id,{immediate:true})},addOpenLink:function(link){if(this.hasOpenLink(link))return;this.openLinks.push(link)},hasOpenLink:function(link){for(var i=0,j=this.openLinks.length;i<
j;i++)if(this.openLinks[i]===link)return true;return false},getPrimaryOpenLink:function(){return this.openLinks.length>0?this.openLinks[0]:false},createFields:function(){},createCustomFields:function(){for(var i=0,j=this.customFields.length;i<j;i++){var field=this.customFields[i];if(field.getCustomFieldId())this.registerField(field);else console.error("Can't register custom field '%o' because it does not have customFieldId set.",field.title)}},render:function(){var formAttributes={"id":this.id,"class":"baseForm actionBox clearfix",
"style":"display:none;"};var form=new Element("div",formAttributes);this.title=(new Element("div",{"class":"formTitle actionBoxTitle"})).update(this.createTitle);this.fieldContainer=new Element("div",{"class":"fields clearfix"});for(var i=0,j=this.fields.length;i<j;i++)this.fieldContainer.insert(this.fields[i].render());var buttons=new Element("div",{"class":"buttons clearfix"});this.submitButton=new Element("input",{"type":"button","class":"submitButton button","value":this.submitButtonTitle,"tabindex":BrainstormForms.getTabIndex()});
this.cancelButton=(new Element("a",{"href":"#","class":"cancelButton","tabindex":BrainstormForms.getTabIndex()})).update("Cancel");this.submitButton.observe("click",function(e){BrainstormJs.Utils.disableTinyMceSpellChecking();e.stop();this.submitForm()}.bind(this));this.cancelButton.observe("click",function(e){e.stop();this.cancelForm()}.bind(this));buttons.insert(this.submitButton);buttons.insert(this.cancelButton);this.progressSpinner=new Element("img",{"class":"progressSpinner","alt":"","src":"/images/editForm_progress.gif"});
this.progressSpinner.hide();buttons.insert(this.progressSpinner);form.insert(this.title);if(this.introText)form.insert((new Element("div",{"class":"formIntro"})).update(this.introText));form.insert(this.fieldContainer);form.insert(buttons);$("hiddenElements").insert(form);for(var i=0,j=this.fields.length;i<j;i++)this.fields[i].afterRender();return form},registerField:function(field){field.setForm(this);this.fields.push(field)},destroyFields:function(){this.fields.each(function(e){if(e.container)e.container.remove()});
this.fields=[]},destroyCustomFields:function(){for(var i=this.fields.length-1;i>=0;i--){var field=this.fields[i];if(field.getCustomFieldId()){if(field.container)field.container.remove();this.fields.splice(i,1)}}},showForm:function(options){options=options||{};for(var i=0,j=this.openLinks.length;i<j;i++){var openLink=this.openLinks[i];if(openLink.hasClassName("inactiveOpenLink")){if(options.linkClicked&&options.linkClicked===openLink)Effect.Shake(options.linkClicked,{distance:3});return}else{Effect.Fade(openLink,
{duration:0.5,from:1,to:0.5});openLink.addClassName("inactiveOpenLink")}}if(options.editMode===true){this.editingExisting=true;try{this.title.update(this.editTitle)}catch(e){}if(options.insertAfter)options.insertAfter.insert({after:this.container});else if(options.insertInto){options.insertInto.insert(this.container);this.parentContainer=options.insertInto}else if(this.parentContainer)this.parentContainer.insert(this.container)}else{this.parentContainer=this.origFormsContainer;try{this.title.update(this.createTitle)}catch(e){}if(this.container.up()!=
this.parentContainer)this.parentContainer.insert(this.container)}if(this.options&&this.options.beforeShow)this.options.beforeShow();this.clearFields();this.beforeShowFields();this.beforeShow();var afterFinishFx=function(appearContainer){BrainstormForms.openForms++;this.focusFirstField();this.afterShow();if(this.scrollToBottom){var container=this.container;bsCommon.scrollIfBelowFold(container,20,{afterFinish:function(){if(appearContainer===true)container.appear({duration:0.75,from:0.25,to:1,delay:0.1})}})}if(options.afterFinish)options.afterFinish();
BrainstormJs.Analytics.scTrackOpenForm(this.getFormIdentifier())}.bind(this);var beforeStartFx=function(){};if(this.replaceElement){var element=this.replaceElement;beforeStartFx=function(){element.blindUp({duration:0.5})}}if(this.parentContainer&&bsCommon.isOnScreen(this.parentContainer))this.container.blindDown({duration:options.blindDuration||0.5,afterFinish:afterFinishFx,beforeStart:beforeStartFx});else{if(this.replaceElement)this.replaceElement.hide();this.container.show();BrainstormJs.Analytics.scTrackOpenForm(this.getFormIdentifier());
afterFinishFx(true)}},isValid:function(){this.container.select(".submit-error").each(function(adv){adv.remove()});for(var i=0,j=this.fields.length;i<j;i++){var field=this.fields[i];if(field.enabled)this.fields[i].beforeValidation()}var validfields=this.validator.validate();var validform=this.validateForm();return validfields&&validform},submitForm:function(){if(!this.isValid())return;this.setSubmissionInProgress();BrainstormJs.Analytics.scTrackSubmitForm(this.getFormIdentifier());if(this.editingExisting)this.saveEditedObject();
else this.createNewObject()},setSubmissionInProgress:function(){this.toggleSubmitButton(false);this.cancelButton.hide();this.progressSpinner.show();this.disableFields()},clearSubmissionInProgress:function(){this.toggleSubmitButton(true);this.cancelButton.show();this.progressSpinner.hide();this.enableFields()},handleAjaxError:function(error,callback){this.clearSubmissionInProgress();bsCommon.ajaxCallError(error,callback)},cancelForm:function(){this.closeForm({cancelPressed:true})},hideCancelPanel:function(){this.container.select(".cancelPanel").each(function(cancel){cancel.hide()})},
toggleSubmitButton:function(enable){if(enable){this.submitButton.value=this.submitButtonTitle;this.submitButton.disabled=false;this.submitButton.removeClassName("disabled")}else{this.submitButton.value="Please Wait...";this.submitButton.disabled=true;this.submitButton.addClassName("disabled")}},enableFields:function(){for(var i=0,j=this.fields.length;i<j;i++){var field=this.fields[i];field.enabled=true;field.enable()}this.fieldContainer.removeClassName("disabledFields")},disableFields:function(){for(var i=
0,j=this.fields.length;i<j;i++){var field=this.fields[i];field.enabled=false;field.disable()}this.fieldContainer.addClassName("disabledFields")},beforeShowFields:function(){for(var i=0,j=this.fields.length;i<j;i++){var field=this.fields[i];field.beforeShowForm()}},clearFields:function(){this.container.select(".submit-error").each(function(adv){adv.remove()});this.validator.reset();this.clearSubmissionInProgress();for(var i=0,j=this.fields.length;i<j;i++){var field=this.fields[i];field.clear();if(this.editingExisting&&
field.hideOnEdit){field.container.addClassName("hiddenField");field.enabled=false;field.disable();field.container.hide()}else if(!this.editingExisting&&field.hideOnAdd)field.container.hide();else if(field.container)field.container.show()}this.container.select(".cancelPanel").each(function(cancel){cancel.show()})},focusFirstField:function(){if(this.container&&!this.container.visible())return;if(this.parentContainer&&!this.parentContainer.visible())return;if(this.fields&&this.fields.length>0){var firstField=
false;for(var i=0,j=this.fields.length;i<j;i++){var field=this.fields[i];if(field.enabled&&field.visible){firstField=field;break}}if(!firstField)return;try{(function(){typeof firstField.select=="function"?firstField.select():firstField.focus()}).defer()}catch(e){}window.setTimeout(function(){try{typeof firstField.select=="function"?firstField.select():firstField.focus()}catch(e){}},250)}},closeForm:function(options){this.clearFields();BrainstormForms.openForms--;var doAfterClose=function(){if(options&&
options.successMessage&&!options.highlight)bsCommon.showSuccess(options.successMessage);if(options&&options.highlight){var elementsToHighlight=[];if(options.highlight.length&&options.highlight.length>0)options.highlight.each(function(el){elementsToHighlight.push(el)});else if(typeof options.highlight.length=="undefined")elementsToHighlight.push(options.highlight);for(var i=0;i<elementsToHighlight.length;i++)new Effect.Highlight(elementsToHighlight[i],{delay:0.2,afterFinish:function(){if(i==0&&options.successMessage)bsCommon.showSuccess(options.successMessage)}})}for(var i=
0,j=this.openLinks.length;i<j;i++){var openLink=this.openLinks[i];openLink.removeClassName("inactiveOpenLink");if(!(options&&options.dontFadeOpenLink))openLink.appear({duration:0.5})}if(options&&options.afterFinish)options.afterFinish();if(this.options&&this.options.afterClose)this.options.afterClose();if(this.afterCancel&&options&&options.cancelPressed)this.afterCancel();if(this.afterClose)this.afterClose();this.stopEditingObject()}.bind(this);if(this.replaceElement&&!this.replaceElement.visible())this.replaceElement.blindDown({duration:0.5,
delay:0.25});if(this.closeSkipBlind||this.closeManually){if(!this.closeManually)this.container.hide();doAfterClose()}else this.container.blindUp({duration:0.5,delay:0.1,afterFinish:doAfterClose})},loadObjectValues:function(container){for(var i=0,j=this.fields.length;i<j;i++){var field=this.fields[i];if(field.dataSelector){var found=container.select(field.dataSelector);if(found.length>0){var data=found[0].value||found[0].innerHTML.strip();field.setValue(data)}}}},getCustomFieldValues:function(){var fieldValues=
[];for(var i=0,j=this.fields.length;i<j;i++){var field=this.fields[i];if(field.getCustomFieldId())fieldValues.push({Id:field.getCustomFieldId(),Value:field.getValue()})}return fieldValues},stopEditingObject:function(){if(this.editObjectElement)this.editObjectElement.removeClassName("editing");this.editObjectId=false;this.editObjectElement=false;this.editingExisting=false},showCancelButton:function(){if(this.cancelButton)this.cancelButton.show()},hideCancelButton:function(){if(this.cancelButton)this.cancelButton.hide()},
getFormIdentifier:function(){if(this.createTitle!="Create New Object")return"create - "+this.createTitle;if(this.editTitle!="Edit")return"edit - "+this.editTitle;if(this.id)return"id - "+this.id;return"Unspecified Form"},beforeShow:function(){},afterShow:function(){},afterClose:function(){},afterCancel:function(){},createNewObject:function(){},saveEditedObject:function(){},validateForm:function(){return true}});
BrainstormJs.Forms.Fields.BaseField=Class.create({form:false,options:false,cssClass:false,dataSelector:false,tabIndex:false,container:false,warningDiv:false,title:false,subtitle:false,help:false,helpDiv:false,helpIcon:false,helpTip:false,warning:false,required:false,hideOnAdd:false,hideOnEdit:false,triggerCheckbox:false,enabled:true,visible:true,customFieldId:false,initialize:function(options){this.options=options||{};this.title=this.options.title||false;this.subtitle=this.options.subtitle||false;
this.help=this.options.help||false;this.warning=this.options.warning||false;this.required=this.options.required||false;this.cssClass=this.options.cssClass||"";this.dataSelector=this.options.dataSelector||null;this.hideOnAdd=this.options.hideOnAdd||false;this.hideOnEdit=this.options.hideOnEdit||false;this.triggerCheckbox=this.options.triggerCheckbox||false;this.tabIndex=BrainstormForms.getTabIndex();this.protectedLinkFn=this.options.protectedLinkFn||false;this.customFieldId=options.customFieldId||
false;if(this.triggerCheckbox)this.triggerCheckbox.addObserver(this.onCheckboxChange.bind(this))},render:function(innerElements){if(innerElements&&innerElements.length>0){this.container=new Element("div",{"class":"field "+this.cssClass});var titleDiv=this.renderTitle();if(titleDiv)this.container.insert(titleDiv);if(this.help){this.helpIcon=(new Element("span",{"class":"helpIcon"})).update("&nbsp;");titleDiv.insert(this.helpIcon);this.helpTip=new Tip(this.helpIcon,this.help,{title:"Help",style:"darkgrey",
className:"helpPopup",closeButton:false,showOn:"click",hideOn:"mouseout",hideAfter:15,stem:"bottomLeft",hook:{target:"topRight",tip:"bottomLeft"},offset:{x:-9,y:0}})}if(titleDiv&&this.required){var requiredSpan=(new Element("span",{"class":"required"})).update("*");titleDiv.insert(requiredSpan)}if(titleDiv&&this.subtitle){var subtitle=(new Element("span",{"class":"subtitle"})).update(this.subtitle);titleDiv.insert(subtitle)}if(titleDiv&&this.protectedLinkFn){this.editLink=(new Element("a",{"class":"editLink",
"href":"#"})).update("change");titleDiv.insert({top:this.editLink});this.editLink.observe("click",function(e){e.stop();this.protectedLinkFn()}.bind(this))}for(var i=0,j=innerElements.length;i<j;i++){var elem=innerElements[i];if(elem)this.container.insert(elem)}if(this.warning&&this.warning.strip().length>0){this.warningDiv=(new Element("div",{"class":"warning"})).update(this.warning);this.container.insert(this.warningDiv)}if(this.hideOnAdd)this.container.hide();return this.container}else return(new Element("div")).update("Error: Field UI not implemented.")},
renderTitle:function(){if(!this.title)return false;var title=new Element("div",{"class":"fieldTitle"});var label=(new Element("label")).update(this.title);title.insert(label);return title},onCheckboxChange:function(checkbox){if(checkbox===this.triggerCheckbox){var checked=checkbox.getValue();if(checked){Effect.BlindDown(this.container,{duration:0.5});this.enableValidation()}else{Effect.BlindUp(this.container,{duration:0.5});this.disableValidation()}}},getForm:function(){return this.form},setForm:function(form){this.form=
form},isValid:function(){return true},beforeValidation:function(){},enableValidation:function(){var element=this.getElement();if(element)element.removeClassName("noValidation")},disableValidation:function(){var element=this.getElement();if(element)element.addClassName("noValidation")},getCustomFieldId:function(){return this.customFieldId},afterRender:function(){},beforeShowForm:function(){},hasValue:function(){return false},getValue:function(){return null},setValue:function(){},clear:function(){},
focus:function(){},enable:function(){},disable:function(){},getElement:function(){}});var lestest;
BrainstormJs.Forms.Fields.TextArea=Class.create(BrainstormJs.Forms.Fields.BaseField,{textarea:false,rows:5,columns:40,enableWysiwyg:false,wysiwygEditor:false,width:false,autoGrowTextArea:false,spellcheckOff:false,initialize:function($super,options){if(Prototype.Browser.MobileSafari)options.enableWysiwyg=false;options=options||{};options.cssClass="textarea tinyMceParent";this.rows=options.rows||this.rows;this.columns=options.columns||this.columns;this.enableWysiwyg=options.enableWysiwyg||this.enableWysiwyg;
this.autoGrowTextArea=options.autoGrow||this.autoGrow;this.spellcheckOff=options.spellcheckOff||this.spellcheckOff;$super(options)},render:function($super){this.textarea=new Element("textarea",{"class":this.cssClass,"rows":this.rows,"cols":this.columns});this.textarea.identify();if(!this.enableWysiwyg)this.textarea.tabIndex=this.tabIndex;if(this.enableWysiwyg)this.textarea.setStyle({width:"100%"});if(this.required)this.textarea.addClassName("required");if(this.spellcheckOff)this.textarea.writeAttribute({spellcheck:"false"});
if(this.autoGrowTextArea){this.textarea.setStyle({overflow:"hidden"});this.textarea.observe("keyup",this.autoSize.bind(this))}return $super([this.textarea])},autoSize:function(){if(this.textarea.scrollHeight>this.textarea.getHeight())this.textarea.setStyle({height:this.textarea.scrollHeight+"px"})},createWysiwyg:function(){if(this.enableWysiwyg){this.wysiwygEditor=new BrainstormJs.Controls.WysiwygTextarea(this.textarea);this.wysiwygEditor.setTabIndex(this.tabIndex)}},destroyWysiwyg:function(){if(this.enableWysiwyg&&
this.wysiwygEditor){this.wysiwygEditor.remove();this.wysiwygEditor=null}},hasValue:function(){return this.getValue()!=""},getValue:function(){if(this.enableWysiwyg&&this.wysiwygEditor)return this.wysiwygEditor.getContent();else return this.textarea.value.strip()},setValue:function(value){if(this.enableWysiwyg&&this.wysiwygEditor){var editor=this.wysiwygEditor;window.setTimeout(function(){editor.setContent(value)},100)}else this.textarea.value=value},clear:function(){this.setValue("")},beforeValidation:function(){if(this.enableWysiwyg&&
this.wysiwygEditor)this.wysiwygEditor.save()},focus:function(){if(this.enableWysiwyg)this.wysiwygEditor.focus();else this.textarea.focus()},getElement:function(){return this.textarea},isWysiwyg:function(){return this.enableWysiwyg}});
BrainstormJs.Forms.Fields.TextBox=Class.create(BrainstormJs.Forms.Fields.BaseField,{input:false,maxLength:20,validateUrl:false,submitOnEnter:false,initialize:function($super,options){options=options||{};options.cssClass="textbox";this.maxLength=options.maxLength||this.maxLength;this.validateUrl=options.validateUrl||this.validateUrl;this.submitOnEnter=options.submitOnEnter||this.submitOnEnter;$super(options)},render:function($super){this.input=new Element("input",{"type":"text","class":"textbox","tabindex":this.tabIndex,
"maxlength":this.maxLength});this.input.identify();if(this.required)this.input.addClassName("required");if(this.validateUrl)this.input.addClassName("validate-url");if(this.submitOnEnter)this.input.observe("keypress",function(e){this.catchKeyPress(e)}.bind(this));return $super([this.input])},catchKeyPress:function(e){if(this.submitOnEnter&&e.keyCode==Event.KEY_RETURN){this.form.submitForm();e.stop()}},hasValue:function(){return this.getValue()!=""},getValue:function(){return this.input.value.strip()},
setValue:function(value){this.input.value=value},clear:function(){this.setValue("")},focus:function(){this.input.focus()},select:function(){this.input.focus();this.input.select()},enable:function(){this.input.disabled=false;this.input.removeClassName("disabled")},disable:function(){this.input.disabled=true;this.input.addClassName("disabled")}});
BrainstormJs.Forms.ContentForm=Class.create(BrainstormJs.Forms.BaseForm,{fieldContent:false,enableWysiwyg:false,editingContent:false,onSave:false,initialize:function($super,options){options=options||{};options.required=options.required||false;this.enableWysiwyg=options.enableWysiwyg||false;this.onSave=options.onSave||false;options.submitButtonTitle="Save";options.editTitle=options.editTitle||"Edit content";$super(null,options)},createFields:function($super){if(this.enableWysiwyg)this.fieldContent=
new BrainstormJs.Forms.Fields.TextArea({title:"Body",required:this.options.required,enableWysiwyg:true,dataSelector:".data-Content"});else this.fieldContent=new BrainstormJs.Forms.Fields.TextBox({title:"Body",required:this.options.required,dataSelector:".data-Content"});this.registerField(this.fieldContent)},startEditing:function(contentEditor){this.contentEditor=contentEditor;this.showForm({afterFinish:function(){this.loadObjectValues(contentEditor.editableDiv)}.bind(this),editMode:true})},saveEditedObject:function(){if(this.editingExisting&&
this.contentEditor)this.onSave(this.fieldContent.getValue(),this.contentSaved.bind(this))},contentSaved:function(newContent){this.contentEditor.setNewContent(newContent);this.closeForm({highlight:this.contentEditor.editableDiv})},beforeShow:function($super){$super();if(this.enableWysiwyg)this.fieldContent.createWysiwyg()},afterClose:function($super){$super();if(this.enableWysiwyg)this.fieldContent.destroyWysiwyg();this.contentEditor.stopEditing();this.contentEditor=false}});
BrainstormJs.Controls.InLineContentEditor=Class.create({options:false,container:false,editableDiv:false,formContainer:false,trigger:false,editing:false,inlineMode:false,editTooltip:false,contentForm:false,formEditTitle:false,fadeInEffect:false,fadeOutEffect:false,onSave:false,initialize:function(options){this.options=options||{};this.container=options.container;this.onSave=options.onSave||false;this.formEditTitle=options.formEditTitle||"Edit content";this.editableDiv=this.container.down("div.editableContent");
this.formContainer=this.container.down("div.contentForm-container");this.inlineMode=!this.formContainer.hasClassName("hoverOverContainer");if(this.editableDiv.hasClassName("editOnClick")){this.editableDiv.observe("mouseenter",this.fadeIn.bind(this));this.editableDiv.observe("mouseleave",this.fadeOut.bind(this));this.editableDiv.observe("click",function(e){this.startEditing(e.element());e.stop()}.bind(this))}else{this.trigger=options.trigger||false;if(this.trigger){this.trigger.observe("click",function(e){this.startEditing(e.element());
e.stop()}.bind(this));if(!this.trigger.visible())this.trigger.appear()}}},fadeIn:function(){if(this.editing)return;if(this.fadeOutEffect)this.fadeOutEffect.cancel();this.fadeInEffect=new Effect.Highlight(this.editableDiv,{duration:0.75,startcolor:"#ffffff",endcolor:"#ffff99",restorecolor:"#ffff99"})},fadeOut:function(force){if(this.editing)return;if(this.fadeInEffect)this.fadeInEffect.cancel();this.fadeOutEffect=new Effect.Highlight(this.editableDiv,{duration:0.5,startcolor:"#ffff99",endcolor:"#ffffff",
restorecolor:"#ffffff"})},startEditing:function(elementClicked){if(this.editing)return;if(this.trigger)this.trigger.fade({duration:0.5});if(this.inlineMode)this.editableDiv.morph("background:#ffffff;",{duration:0.5});this.editableDiv.addClassName("editingContent");this.editing=true;if(!this.contentForm)this.contentForm=new BrainstormJs.Forms.ContentForm({parentContainer:this.formContainer,enableWysiwyg:true,onSave:this.onSave,editTitle:this.formEditTitle});this.contentForm.startEditing(this);if(this.inlineMode)this.editableDiv.blindUp({duration:0.5})},
setNewContent:function(newContent){var content=this.editableDiv.down("div.content");var blankContent=this.editableDiv.down("div.blankContent");if(newContent&&newContent.strip().length>0){content.innerHTML=newContent;content.show();blankContent.hide()}else{content.hide();blankContent.show()}},stopEditing:function(){this.editing=false;this.editableDiv.removeClassName("editingContent");if(this.inlineMode)this.editableDiv.blindDown({duration:0.5});if(this.trigger)this.trigger.appear({duration:0.5})},
onCancelEdit:function(){this.editing=false},onSave:function(){},visible:function(){return this.editing}});
BrainstormJs.Controls.InLineEditor=Class.create({options:false,contentEl:false,editLink:false,container:false,input:false,saveLink:false,cancelLink:false,validator:false,editing:false,serviceMethod:false,serviceParams:false,initialize:function(options){this.options=options;this.contentEl=options.contentEl||false;this.editLink=options.editLink||false;this.container=options.container||false;this.hideElements=options.hideElements||[];this.serviceMethod=options.serviceMethod||false;this.serviceParams=
options.serviceParams||[];this.editLink.observe("click",function(e){this.onEdit();e.stop()}.bind(this))},onEdit:function(){if(!this.input){this.input=this.container.down("input");this.saveLink=this.container.down("a.saveLink");this.cancelLink=this.container.down("a.cancelLink");this.validator=this.container.down("span.validator");this.saveLink.observe("click",function(e){this.onSave();e.stop()}.bind(this));this.cancelLink.observe("click",function(e){this.onCancelEdit();e.stop()}.bind(this));this.input.observe("keypress",
function(e){if(e.keyCode==Event.KEY_RETURN){e.stop();this.onSave()}else if(e.keyCode==Event.KEY_ESC){e.stop();this.onCancelEdit()}}.bind(this))}this.editing=true;this.editLink.hide();this.hideElements.each(function(el){el.fade()});if(this.contentEl){this.contentEl.hide();this.input.value=this.contentEl.innerHTML.unescapeHTML()}else this.input.value="";this.container.appear();this.validator.hide();var textbox=this.input;window.setTimeout(function(){textbox.focus()},100)},onCancelEdit:function(){this.container.hide();
if(this.contentEl)this.contentEl.show();this.editLink.appear();this.validator.hide();this.hideElements.each(function(el){el.appear()});this.editing=false},onSave:function(){var newContent=this.input.value.strip();if(!newContent||newContent==""||newContent.length==0){Effect.Appear(this.validator,{duration:0.5});Effect.Pulsate(this.validator,{pulses:2,duration:1.4,from:0.4,to:1});return}var params=[this.serviceParams,newContent,this.afterSave.bind(this),bsCommon.ajaxCallError].flatten();this.serviceMethod.apply(null,
params)},afterSave:function(returnValue){if(this.contentEl)this.contentEl.innerHTML=returnValue;this.onCancelEdit();if(this.contentEl)new Effect.Highlight(this.contentEl,{duration:1,delay:0.25,startcolor:"#ffff99",endcolor:this.options.restoreColor||"#ffffff",restoreColor:this.options.restoreColor||"#ffffff"});if(this.options.afterSave)this.options.afterSave(returnValue)},visible:function(){return this.editing}});
BrainstormJs.Controls.ResizableTextbox=Class.create({initialize:function(element,options){var that=this;this.options=$H({min:15,max:500,step:7});this.options.update(options);this.el=$(element);this.width=Math.max(this.el.offsetWidth,this.options.get("min"));this.el.observe("keyup",function(){var newsize=that.options.get("step")*$F(this).length+that.options.get("step");if(newsize<=that.options.get("min"))newsize=that.width;if(!(newsize<=that.options.min||newsize>=that.options.max))this.setStyle({"width":newsize+
"px"})})}});
BrainstormJs.Controls.TextboxList=Class.create({initialize:function(element,options){this.options=$H({resizable:{},className:"bit",separator:",",extrainputs:true,startinput:true,hideempty:true,newValues:false,spaceReplace:"",fetchFile:undefined,fetchMethod:"get",results:10,wordMatch:false,fxItemAdded:options.fxItemAdded||false});this.options.update(options);this.element=$(element).hide();this.bits=new Hash;this.events=new Hash;this.count=0;this.numItems=0;this.current=false;this.maininput=this.createInput({"class":"maininput",
"maxlength":30,"tabindex":options.tabIndex});this.holder=(new Element("ul",{"class":"holder"})).insert(this.maininput);this.element.insert({"before":this.holder});this.holder.observe("click",function(event){event.stop();if(this.maininput!=this.current)this.focus(this.maininput)}.bind(this));this.makeResizable(this.maininput);this.setEvents()},setEvents:function(){document.observe(Prototype.Browser.IE?"keydown":"keypress",function(e){if(!this.current)return;if(this.current.retrieveData("type")=="box"&&
e.keyCode==Event.KEY_BACKSPACE)e.stop()}.bind(this));document.observe("keyup",function(e){e.stop();if(!this.current)return;switch(e.keyCode){case Event.KEY_LEFT:return this.move("left");case Event.KEY_RIGHT:return this.move("right");case Event.KEY_SPACE:return this.move("right");case Event.KEY_DELETE:case Event.KEY_BACKSPACE:return this.moveDispose()}}.bind(this));document.observe("click",function(){document.fire("blur")}.bindAsEventListener(this))},update:function(){var values=this.bits.values();
for(var i=0,numVals=this.bits.values().length;i<numVals;i++)values[i]=values[i].value;this.element.value=values.join(this.options.get("separator"));return this},add:function(text,html){var id=this.id_base+"-"+this.count++;var el=this.createBox($pick(html,text),{"id":id,"class":this.options.get("className"),"newValue":text.newValue?"true":"false"});(this.current||this.maininput).insert({"before":el});el.observe("click",function(e){e.stop();this.focus(el)}.bind(this));this.numItems++;this.bits.set(id,
text);this.update();if(this.options.get("extrainputs")&&(this.options.get("startinput")||el.previous()))this.addSmallInput(el,"before");var fxItemAdded=this.options.get("fxItemAdded");if(fxItemAdded)fxItemAdded(el,text);return el},addSmallInput:function(el,where){var input=this.createInput({"class":"smallinput"});el.insert({}[where]=input);input.cacheData("small",true);this.makeResizable(input);if(this.options.get("hideempty"))input.hide();return input},dispose:function(el){this.bits.unset(el.id);
this.update();if(el.previous()&&el.previous().retrieveData("small"))el.previous().remove();if(this.current==el)this.focus(el.next());if(el.retrieveData("type")=="box")el.onBoxDispose(this);el.remove();this.numItems--;if(this.maxItems&&this.numItems<this.maxItems&&this.current)this.current.show();return this},focus:function(el,nofocus){if(!this.current&&el.visible())el.fire("focus");else if(this.current==el)return this;this.blur();el.addClassName(this.options.get("className")+"-"+el.retrieveData("type")+
"-focus");if(el.retrieveData("small"))el.setStyle({"display":"block"});if(el.retrieveData("type")=="input"){el.onInputFocus(this);if(!nofocus)this.callEvent(el.retrieveData("input"),"focus")}else el.fire("onBoxFocus");this.current=el;return this},blur:function(noblur){if(!this.current)return this;if(this.current.retrieveData("type")=="input"){var input=this.current.retrieveData("input");if(!noblur)this.callEvent(input,"blur");input.onInputBlur(this)}else this.current.fire("onBoxBlur");if(this.current.retrieveData("small")&&
!input.get("value")&&this.options.get("hideempty"))this.current.hide();this.current.removeClassName(this.options.get("className")+"-"+this.current.retrieveData("type")+"-focus");this.current=false;return this},createBox:function(text,options){var boxElem=(new Element("li",options)).addClassName(this.options.get("className")+"-box").update(text.caption);boxElem.insert((new Element("span")).addClassName("detail").hide());return boxElem.cacheData("type","box")},createInput:function(options){var li=new Element("li",
{"class":this.options.get("className")+"-input"});var el=new Element("input",Object.extend(options,{"type":"text"}));el.observe("click",function(e){e.stop()}).observe("focus",function(e){if(!this.isSelfEvent("focus"))this.focus(li,true)}.bind(this)).observe("blur",function(){if(!this.isSelfEvent("blur"))this.blur(true)}.bind(this)).observe("keydown",function(e){this.cacheData("lastvalue",this.value).cacheData("lastcaret",this.getCaretPosition())});var tmp=li.cacheData("type","input").cacheData("input",
el).insert(el);return tmp},callEvent:function(el,type){if(type=="focus")if(!el.visible()||!el.up().visible())return;this.events.set(type,el);el[type]()},isSelfEvent:function(type){return this.events.get(type)?!!this.events.unset(type):false},makeResizable:function(li){var el=li.retrieveData("input");var resizableTextbox=new BrainstormJs.Controls.ResizableTextbox(el,Object.extend(this.options.get("resizable"),{max:this.element.getWidth()?this.element.getWidth():10}));el.cacheData("resizable",resizableTextbox);
return this},checkInput:function(){var input=this.current.retrieveData("input");return!input.retrieveData("lastvalue")||input.getCaretPosition()===0&&input.retrieveData("lastcaret")===0},move:function(direction){var el=this.current[direction=="left"?"previous":"next"]();if(el&&(!this.current.retrieveData("input")||this.checkInput()||direction=="right"))this.focus(el);return this},moveDispose:function(){if(this.current.retrieveData("type")=="box")return this.dispose(this.current);if(this.checkInput()&&
this.bits.keys().length&&this.current.previous())return this.focus(this.current.previous())}});
Element.addMethods({getCaretPosition:function(){if(this.createTextRange){var r=document.selection.createRange().duplicate();r.moveEnd("character",this.value.length);if(r.text==="")return this.value.length;return this.value.lastIndexOf(r.text)}else return this.selectionStart},cacheData:function(element,key,value){if(Object.isUndefined(this[$(element).identify()])||!Object.isHash(this[$(element).identify()]))this[$(element).identify()]=$H();this[$(element).identify()].set(key,value);return element},
retrieveData:function(element,key){return this[$(element).identify()].get(key)}});function $pick(){for(var i=0,j=arguments.length;i<j;i++)if(!Object.isUndefined(arguments[i]))return arguments[i];return null}Object.extend(Event,{KEY_COMMA:188});
BrainstormJs.Controls.MultiCompleter=Class.create(BrainstormJs.Controls.TextboxList,{maxItems:false,newValues:false,ajaxEnableDelay:true,ajaxCallLastQuery:false,ajaxCallFrequency:0.1,ajaxCallObserver:false,height:29,initialize:function($super,element,autoholder,options,func){$super(element,options);this.loptions=$H({autocomplete:{"opacity":1,"maxresults":10,"minchars":3}});this.maxItems=options.maxItems||false;this.newValues=this.options.get("newValues");this.id_base=$(element).identify()+"_"+this.options.get("className");
this.data=[];this.autoholder=$(autoholder).setOpacity(this.loptions.get("autocomplete").opacity);this.autoholder.observe("mouseover",function(){this.curOn=true}.bind(this)).observe("mouseout",function(){this.curOn=false}.bind(this));this.autoresults=this.autoholder.select("ul").first();var children=this.autoresults.select("li");children.each(function(el){this.add({value:el.readAttribute("value"),caption:el.innerHTML})},this)},autoShow:function(search){this.autoholder.setStyle({"display":"block"});
this.autoholder.descendants().each(function(e){e.hide()});if(!search||!search.strip()||!search.length||search.length<this.loptions.get("autocomplete").minchars)this.resultsshown=false;else{var specialChars=new RegExp("[.*+?|()\\[\\]{}\\\\]","g");search=search.replace(specialChars,"\\$&");this.resultsshown=true;this.autoresults.setStyle({"display":"block"}).update("");if(this.options.get("wordMatch"))var regexp=new RegExp("(^|\\s)"+search,"i");else var regexp=new RegExp(search,"i");var count=0;var items=
this.data;var bestMatchIndex=-1;items.each(function(result,ti){count++;if(ti>=this.loptions.get("autocomplete").maxresults)return;var that=this;var el=new Element("li");el.observe("click",function(e){e.stop();if(that.checkValid(this))that.autoAdd(this,true)});el.observe("mouseover",function(){that.autoFocus(this)});var result=result.evalJSON(true);var highlightedCaption=this.autoHighlight(result.caption,search);if(bestMatchIndex<0&&highlightedCaption!=result.caption)bestMatchIndex=ti;var subcaption=
result.subcaption;if(subcaption!=null){if(result.type=="Tag"){if(subcaption=="0")el.addClassName("invalid");subcaption+=subcaption==1?"&nbsp;Person":"&nbsp;People"}subcaption='<span class="detail">('+subcaption+")</span>"}else subcaption="";var icon="";if(result.icon&&result.icon.length>0)icon='<img class="icon" src="'+result.icon+'"/>';el.addClassName(result.type);el.update(icon+highlightedCaption+subcaption);this.autoresults.insert(el);el.cacheData("result",result);if((ti==bestMatchIndex||ti==0)&&
!this.newValues)this.autoFocus(el)},this)}if(count==0)this.autoHide();return this},autoHighlight:function(html,highlight){return html.gsub(new RegExp(highlight,"i"),function(match){return"<em>"+match[0]+"</em>"})},autoHide:function(){this.resultsshown=false;this.autoholder.hide();return this},autoFocus:function(el){if(!el)return;if(this.selectedSuggestItem)this.selectedSuggestItem.removeClassName("auto-focus");this.selectedSuggestItem=el;this.selectedSuggestItem.addClassName("auto-focus");return this},
autoMove:function(direction){if(!this.resultsshown)return;var moveToItem=null;if(this.selectedSuggestItem){if(direction=="up")moveToItem=this.selectedSuggestItem.previous();else if(direction=="down")moveToItem=this.selectedSuggestItem.next();if(moveToItem==null&&this.newValues){this.selectedSuggestItem.removeClassName("auto-focus");this.selectedSuggestItem=false}}else if(direction=="down")moveToItem=this.autoresults.firstDescendant();else if(direction=="up")moveToItem=this.autoresults.select("li:last-child")[0];
this.autoFocus(moveToItem);if(this.selectedSuggestItem)this.autoresults.scrollTop=this.selectedSuggestItem.positionedOffset()[1]-this.selectedSuggestItem.getHeight();return this},autoFeed:function(text){if(this.data.indexOf(Object.toJSON(text))==-1)this.data.push(Object.toJSON(text));return this},autoAdd:function(el,focus,id,label){if(this.newvalue){this.add({caption:label?label:el.value,value:id?id:el.value,newValue:true});var input=el}else if(!el||!el.retrieveData("result"))return;else{this.add(el.retrieveData("result"));
delete this.data[this.data.indexOf(Object.toJSON(el.retrieveData("result")))];var input=this.lastinput||this.current.retrieveData("input")}if(this.isMaxReached()&&input){var li=input.up();if(li){li.hide();focus=false}}this.autoHide();input.clear();if(focus)input.focus();return this},isMaxReached:function(){return this.maxItems&&this.numItems>=this.maxItems},addNewValue:function(keyEvent){var new_value_el=this.current.retrieveData("input");new_value_el.value=new_value_el.value.strip().gsub(",","").gsub("'",
"").stripScripts().stripTags();if(!this.options.get("spaceReplace").blank())new_value_el.gsub(" ",this.options.get("spaceReplace"));if(!new_value_el.value.blank()){keyEvent.stop();this.newvalue=true;this.autoAdd(new_value_el,true)}},checkValid:function(elem){if(elem.hasClassName("invalid")){Effect.Shake(elem,{distance:3});return false}return true},createInput:function($super,options){var li=$super(options);var input=li.retrieveData("input");input.observe("keydown",function(e){this.dosearch=false;
this.newvalue=false;switch(e.keyCode){case Event.KEY_UP:e.stop();return this.autoMove("up");case Event.KEY_DOWN:e.stop();return this.autoMove("down");case Event.KEY_COMMA:case Event.KEY_TAB:if(!this.newValues&&input.value.strip()=="")return;case Event.KEY_RETURN:if(this.newValues&&(!this.resultsshown||!this.selectedSuggestItem)){this.addNewValue(e);break}e.stop();if(this.selectedSuggestItem&&this.checkValid(this.selectedSuggestItem)){this.autoAdd(this.selectedSuggestItem,true);this.selectedSuggestItem=
false;this.autoenter=true}break;case Event.KEY_ESC:this.autoHide();if(this.current&&this.current.retrieveData("input"))this.current.retrieveData("input").clear();break;default:this.dosearch=true}}.bind(this));input.observe("keyup",function(e){switch(e.keyCode){case Event.KEY_UP:case Event.KEY_DOWN:case Event.KEY_RETURN:case Event.KEY_ESC:break;default:if(input.value.length>=this.loptions.get("autocomplete").minchars&&!Object.isUndefined(this.options.get("fetchFile")))if(this.ajaxEnableDelay){if(this.ajaxCallObserver)clearTimeout(this.ajaxCallObserver);
if(input.value.strip()!=this.ajaxCallLastQuery){var delayedFunction=function(){this.getAjaxData(input)}.bind(this);this.ajaxCallObserver=setTimeout(delayedFunction,this.ajaxCallFrequency*1E3)}else if(this.dosearch)this.autoShow(input.value)}else this.getAjaxData(input);else if(this.dosearch)this.autoShow(input.value)}}.bind(this));input.observe(Prototype.Browser.IE?"keydown":"keypress",function(e){if((e.keyCode==Event.KEY_RETURN||e.keyCode==Event.KEY_TAB||e.keyCode==Event.KEY_COMMA)&&this.autoenter)e.stop();
this.autoenter=false}.bind(this));return li},getAjaxData:function(input){this.ajaxCallLastQuery=input.value.strip();new Ajax.Request(this.options.get("fetchFile"),{method:"post",postBody:Object.toJSON({requestToken:bsCommon.getRequestToken(),keyword:this.ajaxCallLastQuery}),contentType:"application/json; charset=utf-8",onSuccess:function(transport){var resultJSON=transport.responseText.evalJSON(true);var array=resultJSON.d;this.data=[];array.each(function(t){this.autoFeed(t)}.bind(this));this.autoShow(input.value)}.bind(this)})},
createBox:function($super,text,options){var li=$super(text,options);li.observe("mouseover",function(){this.addClassName("bit-hover")});li.observe("mouseout",function(){this.removeClassName("bit-hover")});var a=new Element("a",{"href":"#","class":"closebutton"});a.observe("click",function(e){e.stop();if(!this.current)this.focus(this.maininput);this.dispose(li)}.bind(this));li.insert(a).cacheData("text",Object.toJSON(text));return li}});
Element.addMethods({onBoxDispose:function(item,obj){item=item.retrieveData("text").evalJSON(true);if(!item.newValue)obj.autoFeed(item)},onInputFocus:function(el,obj){obj.autoShow()},onInputBlur:function(el,obj){obj.lastinput=el;if(!obj.curOn)obj.blurhide=obj.autoHide.bind(obj).delay(0.1)},filter:function(D,E){var items=[];for(var i=0,j=this.length;i<j;i++)if(D.call(E,this[i],i,this))items.push(this[i]);return items}});
BrainstormJs.Controls.PopupMenu=Class.create({container:false,options:false,menuContext:false,choices:false,closeLink:false,preloadChoices:false,choicesDiv:false,noChoicesDiv:false,fxOnSelectChoice:false,fxOnDeleteChoice:false,initialize:function(container,options){if(!container)return;this.container=container;this.options=options;this.choices=new Hash;this.choicesDiv=this.container.down("div.popupChoices");this.preloadChoices=this.container.down("select.preloadChoices");this.noChoicesDiv=this.container.down("div.noChoices");
if(this.preloadChoices&&this.preloadChoices.options&&this.preloadChoices.options.length>0)for(var i=0,j=this.preloadChoices.options.length;i<j;i++){var option=this.preloadChoices.options[i];var editable=option.className.indexOf("editable")>=0;this.addChoice(option.value,option.text,false,editable)}this.closeLink=this.container.down("div.menuTitle a.close");this.closeLink.observe("click",function(e){this.hide();e.stop()}.bind(this))},addChoice:function(choiceId,choiceText,context,editable){if(!this.container)return;
if(!this.fxOnSelectChoice)this.fxOnSelectChoice=function(e){this.onSelectChoice(e.element());e.stop()}.bindAsEventListener(this);if(!this.fxOnDeleteChoice)this.fxOnDeleteChoice=function(e){this.onDeleteChoice(e);e.stop()}.bindAsEventListener(this);var choiceDiv=new Element("div",{"class":"choice"});var choiceLink=(new Element("a",{href:"#","class":"choice",rel:choiceId})).update(choiceText);choiceLink.observe("click",this.fxOnSelectChoice);choiceDiv.insert(choiceLink);if(editable){var deleteLink=
new Element("a",{href:"#","class":"delete",rel:choiceId});deleteLink.observe("click",this.fxOnDeleteChoice);choiceDiv.insert({top:deleteLink})}this.choicesDiv.insert(choiceDiv);this.noChoicesDiv.hide();this.choices.set(choiceId,{id:choiceId,text:choiceText,link:choiceLink,div:choiceDiv,context:context})},removeChoice:function(choiceId){var choice=this.choices.get(choiceId);if(choice){choice.div.remove();this.choices.unset(choiceId)}if(this.choices.keys().length<=0)this.noChoicesDiv.show()},show:function(linkClicked,
context,options){if(linkClicked.tagName.toLowerCase()!="a")linkClicked=linkClicked.up("a",0);this.menuContext=context;var menuWrapper=linkClicked.previous("div.popupMenuWrapper");if(!menuWrapper){menuWrapper=new Element("div",{"class":"popupMenuWrapper"});linkClicked.insert({before:menuWrapper})}this.container.setStyle({width:(options.width||this.container.getWidth())+"px",top:(options.offset?options.offset.y:0)+"px",left:(options.offset?options.offset.x:0)+"px"});menuWrapper.insert(this.container);
var visibleChoices=0;if(options&&options.hideChoiceWithId)this.choices.each(function(pair){var choice=pair.value;if(choice.id==options.hideChoiceWithId)choice.div.hide();else{choice.div.show();visibleChoices++}});else visibleChoices=this.choices.keys().length;if(visibleChoices==0)this.noChoicesDiv.show();this.container.appear({duration:0.5})},hide:function(){this.container.fade({duration:0.5});this.menuContext=false},onSelectChoice:function(linkClicked){var choice=this.choices.get(linkClicked.rel);
var choiceContext=choice?choice.context:false;if(this.options.onSelectChoice)this.options.onSelectChoice(linkClicked,this.menuContext,choiceContext)},onDeleteChoice:function(triggerEvent){var linkClicked=triggerEvent.element();var choice=this.choices.get(linkClicked.rel);var choiceContext=choice?choice.context:false;if(this.options.onDeleteChoice)this.options.onDeleteChoice(linkClicked,this.menuContext,choiceContext,choice,triggerEvent)}});
var Starboxes={options:{buttons:5,className:"default",color:false,duration:0.6,effect:{mouseover:false,mouseout:window.Effect&&Effect.Morph},hoverColor:false,hoverClass:"hover",ghostColor:false,ghosting:false,identity:false,indicator:false,inverse:false,locked:false,max:5,onRate:Prototype.emptyFunction,rated:false,ratedClass:"rated",rerate:false,overlay:"default.png",overlayImages:"/Images/Controls/RatingStars/",stars:5,total:0}};
eval(function(p,a,c,k,e,r){e=function(c){return(c<a?"":e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!"".replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return"\\w+"};c=1}while(c--)if(k[c])p=p.replace(new RegExp("\\b"+e(c)+"\\b","g"),k[c]);return p}('(9(){P.1c(o,{2q:"1.7",2r:"1.8.3",1Q:9(){5.1p("12");5.Q.1R=1;13(/^(2s?:\\/\\/|\\/)/.2t(5.6.1q)){5.1r=5.6.1q}1S{l b=/14(?:-[\\w\\d.]+)?\\.2u(.*)/;5.1r=(($$("2v[B]").1T(9(c){x c.B.2w(b)})||{}).B||"").1U(b,"")+5.6.1q}},1p:9(b){13(2x 15[b]=="2y"||5.1s(15[b].2z)<5.1s(5["1V"+b])){2A"1W 2B "+b+" >= "+5["1V"+b]}},1s:9(d){l c=d.1U(/1t.*|\\./g,""),c=1u(c+"0".1v(4-c.2C));x d.2D("1t")>-1?c-1:c},1X:9(b){x(b=/2E ([\\d.]+)/.2F(b))?2G(b[1])<7:!1}(2H.2I),Q:9(e){l e=$(e),d=e.2J("1Y"),f=2K.2L;13(d){x d}2M{d="2N"+f.1R++}2O($(d));e.2P("1Y",d);x d},1w:[],2Q:9(b){5.1x(b.B)||5.1w.1d(b);x b},1x:9(b){x 5.1w.1T(9(c){x c.B==b})},G:[],1Z:9(b){5.G.1d(b)},1e:9(){5.G[0]?5.20(5.G[0]):5.2R=!1},20:9(f){l e=[],h=f.6.21,f=5.1x(h);5.G.H(9(b){b.6.21==h&&(e.1d(b),5.G=5.G.2S(b))}.C(5));13(f){5.1y(e,f)}1S{l g=m 2T;g.2U=9(){5.1y(e,{B:h,I:g.I,J:g.J,22:g.B})}.C(5);g.B=o.1r+h}},1y:9(d,c){d.H(9(b){b.1f=c;b.23()});5.1e()},1z:{1g:"1g",R:"R",K:12.1h.1i?"2V":"K"},24:9(b){12.1h.1i||(b=b.2W(9(f,i){l h=P.2X(5)?5:5.q,g=i.2Y;g!=h&&!$A(h.2Z("*")).30(g)&&f(i)}));x b}});o.1Q();(9(b){1A.25?b.31(1A):1A.26("32:25",b)})(9(){o.1e()});l a=33.34({35:9(e,d,f){5.q=$(e);5.n=d;5.6=P.1c(P.36(o.6),f||{});$w("L k D s").H(9(b){5[b]=5.6[b]}.C(5));5.S=5.6.S||5.k&&!5.6.1B;5.L||(5.L=o.Q(5.q));5.6.t&&(5.6.t.R||5.6.t.K)&&o.1p("37");o.1Z(5);o.1e()},27:9(){$w("K R 1g").H(9(e){l d=e.28(),f=5["1j"+d].38(5);5["1j"+d+"1C"]=e=="K"&&!12.1h.1i?o.24(f):f;5.16.26(o.1z[e],5["1j"+d+"1C"])}.C(5));5.M.29("j",{2a:"39"})},2b:9(){$w("R K 1g").H(9(b){5.16.3a(o.1z[b],5["1j"+b.28()+"1C"])}.C(5));5.M.29("j",{2a:"3b"})},23:9(){5.17=5.1f.J;5.18=5.1f.I;5.1D=5.1f.22;5.T=5.17*5.6.1E;5.19=5.T/5.6.M;5.1k=5.6.D/5.6.M;5.6.t&&(5.2c=5.1a(0),5.2d=5.1a(5.6.D));l b={N:{U:"N",1l:0,y:0,J:5.T+"p",I:5.18+"p"},1F:{U:"2e",J:5.T+"p",I:5.18+"p"},2f:{U:"N",1l:0,y:0,J:5.17+"p",I:5.18+"p"}};5.q.V("14");5.2g=(m r("u",{W:5.6.W||""})).j({U:"2e"}).v(5.1b=(m r("u")).v(5.1m=(m r("u")).v(5.1G=(m r("u",{W:"1E"})).j(P.1c({3c:"2h"},b.1F)))));5.k&&5.1b.V("k");5.S&&5.1b.V("S");5.6.2i&&(5.1G.v(5.O=(m r("u",{W:"O"})).j(b.N)),5.6.2j&&5.O.j({X:5.6.2j}),5.6.t&&(5.O.E=5.O.Q()),5.Y(5.O,5.n,15.Z&&Z.1H));5.1G.v(5.z=(m r("u",{W:"z"})).j(b.N)).v((m r("u")).j(b.N).v(5.16=(m r("u")).j(b.1F)));5.6.1I&&5.z.j({X:5.6.1I});5.6.t&&(5.z.E=5.z.Q());5.6.1E.1v(9(d){l e;5.16.v(e=(m r("u")).j(P.1c({X:"3d("+5.1D+") 1l y 3e-3f",y:5.17*d+"p"},b.2f)));e.j({y:5.17*d+"p"});o.1X&&e.j({X:"3g",3h:"3i:3j.3k.3l(B=\'"+5.1D+"\'\', 3m=\'3n\')"})}.C(5));5.M=[];5.6.M.1v(9(d){l e;e=5.6.2k?5.T-5.19*(d+1):5.19*d;5.16.v(e=(m r("u")).j({U:"N",1l:0,y:e+"p",J:5.19+(12.1h.1i?1:0)+"p",I:5.18+"p"}));e.F=5.1k*d+5.1k;5.M.1d(e)}.C(5));5.Y(5.z,5.n);5.q.2l(5.2g);5.1J={};$w("n D k 1n s").H(9(c){5.q.v(5.1J[c]=m r("3o",{3p:"2h",3q:5.L+"1t"+c,2m:""+(c=="1n"?!!5[c]:5[c])}))}.C(5));5.6.11&&(5.1m.v(5.11=m r("u",{W:"11"})),5.1K());5.S||5.27()},2n:9(d){5.k&&5.6.1B&&(5.n=(5.s*5.n-5.k)/(5.s-1||1));l c=5.k?5.s:5.s++;5.n=5.n==0?d:(5.n*(5.k?c-1:c)+d)/(5.k?c:c+1)},1K:9(){5.11.2l((m 3r(5.6.11)).3s({D:5.6.D,s:5.s,n:(5.n*10).3t()/10}))},1a:9(b){b=5.T-b/5.1k*5.19;x 1u(5.6.2k?b.3u():-1*b.3v())},Y:9(f,e,h){5.6.t&&5["1L"+f.E]&&Z.3w.3x(f.E).3y(5["1L"+f.E]);l g=5.1a(e);h?(h=1u(f.3z("y")),e=5.1a(e),h!=e&&(e=((5.2d-(h-e).1M()).1M()/5.2c.1M()).3A(2),5["1L"+f.E]=m Z.1H(f,{3B:{y:g+"p"},3C:{U:"3D",3E:1,E:f.E},2o:5.6.2o*e}))):f.j({y:g+"p"})},3F:9(e){l d=e.q();13(d.F){5.2n(d.F);5.6.11&&5.1K();5.6.2i&&5.Y(5.O,5.n,15.Z&&Z.1H);5.k||5.1b.V("k");5.1n=!!5.k;5.k=d.F;5.6.1B||(5.2b(),5.1b.V("S"),5.2p(e));l f={};$w("n L D k 1n s").H(9(b){b!="L"&&(5.1J[b].2m=5[b]);f[b]=5[b]}.C(5));5.6.3G(5.q,f);5.q.1N("14:k",f)}},2p:9(){5.Y(5.z,5.n,5.6.t&&5.6.t.K);5.1O=!1;5.6.1o&&5.1m.3H(5.6.1o);5.6.1P&&5.z.j({X:5.6.1I});5.q.1N("14:y")},3I:9(b){b=b.q();!b.F||(5.Y(5.z,b.F,5.6.t&&5.6.t.R),!5.1O&&5.6.1o&&5.1m.V(5.6.1o),5.1O=!0,5.6.1P&&5.z.j({X:5.6.1P}),5.q.1N("14:3J",{Q:5.6.L,D:5.6.D,F:b.F,s:5.s}))}});15.1W=a})();',
62,232,"|||||this|options|||function||||||||||setStyle|rated|var|new|average|Starboxes|px|element|Element|total|effect|div|insert||return|left|colorbar||src|bind|max|scope|rating|buildQueue|each|height|width|mouseout|identity|buttons|absolute|ghost|Object|identify|mouseover|locked|boxWidth|position|addClassName|className|background|setBarPosition|Effect||indicator|Prototype|if|starbox|window|starbar|starWidth|starHeight|buttonWidth|getBarPosition|status|extend|push|processBuildQueue|imageInfo|click|Browser|IE|on|buttonRating|top|hover|rerated|hoverClass|require|overlayImages|imageSource|convertVersionString|_|parseInt|times|imagecache|getCachedImage|buildBatch|useEvent|document|rerate|_cached|starSrc|stars|base|wrapper|Morph|color|inputs|updateIndicator|activeEffect_|abs|fire|hovered|hoverColor|load|counter|else|find|replace|REQUIRED_|Starbox|fixIE|id|queueBuild|cacheBuildBatch|overlay|fullsrc|build|capture|loaded|observe|enable|capitalize|invoke|cursor|disable|zeroPosition|maxPosition|relative|star|container|hidden|ghosting|ghostColor|inverse|update|value|updateAverage|duration|onMouseout|REQUIRED_Prototype|REQUIRED_Scriptaculous|https|test|js|script|match|typeof|undefined|Version|throw|requires|length|indexOf|MSIE|exec|parseFloat|navigator|userAgent|readAttribute|arguments|callee|do|starbox_|while|writeAttribute|cacheImage|batchLoading|without|Image|onload|mouseleave|wrap|isElement|relatedTarget|select|member|call|dom|Class|create|initialize|clone|Scriptaculous|bindAsEventListener|pointer|stopObserving|auto|overflow|url|no|repeat|none|filter|progid|DXImageTransform|Microsoft|AlphaImageLoader|sizingMethod|scale|input|type|name|Template|evaluate|round|ceil|floor|Queues|get|remove|getStyle|toFixed|style|queue|end|limit|onClick|onRate|removeClassName|onMouseover|changed".split("|"),
0,{}));
BrainstormJs.Controls.RatingStars=Class.create({options:false,element:false,average:0,color:false,starbox:false,summaryControl:false,fadeFx:false,hoverDelay:0,hovering:false,hoveredOut:false,initialize:function(options){this.options=options;this.average=options.average||0;this.summaryControl=options.summaryControl||false;this.element=$(options.element);this.color=options.color||false;this.hoverDelay=options.hoverDelay||0;if(!this.element||typeof this.element=="undefined")console.error("Could not find a valid element to make into a RatingStars control.");this.element.identify();
this.starbox=new Starbox(this.element,this.average,{ghosting:options.ghosting||true,color:this.color,locked:false,rated:options.userRating||false,rerate:options.rerate||true,overlay:options.overlay||"star_overlay.png",total:options.total||0,onRate:this.onRate.bind(this)});if(this.options.onHoverChange){this.element.observe("starbox:changed",this.onHoverChange.bind(this));this.element.observe("starbox:left",this.onMouseLeave.bind(this))}},onRate:function(element,details){this.hovering=false;this.hoveredOut=
true;if(this.options.onRate)this.options.onRate(element,details);var colorbar=element.down("div.colorbar");var highlightDiv=colorbar.down("div.highlight");if(!highlightDiv){highlightDiv=new Element("div",{"class":"highlight","style":"height: "+colorbar.getHeight()+"px;"});colorbar.insert(highlightDiv)}if(this.fadeFx)this.fadeFx.cancel();highlightDiv.show();this.fadeFx=new Effect.Fade(highlightDiv,{duration:1,from:1,to:0});if(this.summaryControl&&this.summaryControl.ideaProfile&&this.summaryControl.ideaProfile.reviewsContainer){var reviewsContainer=
this.summaryControl.ideaProfile.reviewsContainer;var isRated=$F("user_rating")!="0";var reviewForm=reviewsContainer.reviewForm;if(isRated){var myReview=reviewsContainer.myReviewContainer.down("div.myReview");reviewForm.setInitialStarValue(details.rated);reviewForm.startEditing(myReview)}else{reviewForm.setInitialStarValue(details.rated);reviewForm.showForm()}}},onHoverChange:function(e){var rating=e.memo.rating;if(!this.options.onHoverChange)return;if(this.hoverDelay===0||this.hovering){this.options.onHoverChange(rating);
return}this.hoveredOut=false;if(this.hoverDelay>0)window.setTimeout(function(){if(!this.hoveredOut){this.hovering=true;this.options.onHoverChange(rating)}}.bind(this),this.hoverDelay)},onMouseLeave:function(){this.hovering=false;this.hoveredOut=true;if(this.options.onMouseLeave)this.options.onMouseLeave()},setState:function(state){var current=this.starbox.options;var newAverage=typeof state.average=="undefined"?this.starbox.average:state.average;var newRated=typeof state.rated=="undefined"?current.rated:
state.rated;var newTotal=typeof state.total=="undefined"?current.total:state.total;var recrateFx=function(){delete this.starbox;this.starbox=new Starbox(this.element,newAverage,{rated:newRated,total:newTotal,locked:current.locked||false,ghosting:current.ghosting,rerate:current.rerate,overlay:current.overlay,onRate:current.onRate})}.bind(this);recrateFx.defer()},lock:function(){this.starbox.locked=true;this.starbox.options.locked=true},unlock:function(){this.starbox.locked=false;this.starbox.options.locked=
true}});
BrainstormJs.Controls.RefreshDataMessage=Class.create({container:false,options:false,refreshLink:false,loaded:false,initialize:function(container,options){this.container=container;if(!this.container)return;this.options=options;this.refreshLink=this.container.down("a.refreshData");this.refreshLink.observe("click",function(e){this.onRefresh();e.stop()}.bind(this));this.loaded=true},onRefresh:function(){if(this.options&&this.options.onRefresh)this.options.onRefresh()},show:function(pulsate){if(!this.loaded)return;if(this.isVisible())this.pulsate();
else{this.container.blindDown({duration:0.5});if(pulsate)this.container.pulsate({duration:1.5,queue:"top"})}},hide:function(){if(!this.loaded)return;if(this.container.visible()){this.container.fade({duration:0.75});this.container.blindUp({duration:0.75})}},isVisible:function(){if(!this.loaded)return false;return this.container.visible()},pulsate:function(){if(!this.loaded)return;this.container.pulsate({pulses:2,duration:1.5})},pulsateIf:function(condition){if(!this.loaded)return;if(condition&&this.isVisible())this.pulsate()}});
BrainstormJs.Forms.Fields.RatingStarsField=Class.create(BrainstormJs.Forms.Fields.BaseField,{wrapper:false,starControl:false,starValue:false,label:false,requiredSpan:false,validator:false,initialize:function($super,options){options=options||{};options.cssClass="ratingstarsfield clearfix";$super(options)},render:function($super){this.wrapper=new Element("div",{"class":"wrapper"});this.wrapper.identify();this.starControl=new BrainstormJs.Controls.RatingStars({element:this.wrapper,average:0,mouseoutEffect:false,
overlay:"star_overlay_form.png",rerate:true,onRate:this.onRate.bind(this)});this.label=(new Element("div",{"class":"starLabel"})).update(this.title+":");this.requiredSpan=(new Element("span",{"class":"required"})).update("*");this.validator=new Element("div",{"class":"validator"});this.starValue=new Element("input",{"class":"starvalue","type":"hidden","value":""});if(this.required)this.starValue.addClassName("required-star");return $super([this.label,this.requiredSpan,this.wrapper,this.starValue,
this.validator])},afterRender:function(){},renderTitle:function($super){},hasValue:function(){var value=this.getValue();return value&&value>0},getValue:function(){var stringValue=this.starValue.value.strip();return stringValue==""?false:parseInt(stringValue,10)},setValue:function(value){this.starValue.value=value;this.starControl.setState({average:value,rated:value,total:1,locked:false})},clear:function(){},focus:function(){},getElement:function(){return this.starValue},disable:function(){},enable:function(){},
onRate:function(element,details){this.starValue.value=details.rated;if(this.required&&this.validator){var advice=this.validator.down("span.validation-advice");if(advice)advice.fade({duration:0.5,afterFinish:function(){advice.remove()}})}}});
BrainstormJs.Forms.Fields.RadioButtonChoice=Class.create(BrainstormJs.Forms.Fields.BaseField,{wrapper:false,groupId:false,radios:false,initialize:function($super,options){options=options||{};options.cssClass="radiobuttonchoice";this.radios=[];$super(options)},render:function($super){this.wrapper=new Element("div",{"class":"radiobuttons"});this.wrapper.identify();this.groupId=this.wrapper.id;if(this.options.choices)for(var i=0,j=this.options.choices.length;i<j;i++){var choice=this.options.choices[i];
var radio=new Element("input",{"type":"radio","class":"radio","name":this.groupId,"value":choice.value,"tabindex":this.tabIndex});var text=(new Element("span",{"class":"label"})).update(choice.text);this.radios.push(radio);if(choice.subtitle){var subtitle=(new Element("span",{"class":"small"})).update(choice.subtitle);text.insert(subtitle)}if(choice.checked)radio.writeAttribute("checked","checked");var choiceWrapper=new Element("div",{"class":"radioChoice clearfix"});choiceWrapper.insert(radio);choiceWrapper.insert(text);
this.wrapper.insert(choiceWrapper)}return $super([this.wrapper])},renderTitle:function($super){if(this.options.title){var e=new Element("div",{"class":"fieldTitle"});var lbl=new Element("label");lbl.innerHTML=this.options.title;e.insert(lbl);return e}},afterRender:function(){},hasValue:function(){var value=this.getValue();return value&&value!=""&&value.strip()!=""},getValue:function(){for(var i=0,j=this.radios.length;i<j;i++)if(this.radios[i].checked)return this.radios[i].value},getIntValue:function(){var value=
this.getValue();if(value&&value.length>0)return parseInt(value,10);return false},setValue:function(value){this.clear();for(var i=0,j=this.radios.length;i<j;i++)if(this.radios[i].value==value){this.radios[i].checked=true;return}},clear:function(){for(var i=0,j=this.radios.length;i<j;i++)this.radios[i].checked=false;this.radios[0].checked=true},focus:function(){}});
BrainstormJs.Forms.IdeaReviewForm=Class.create(BrainstormJs.Forms.BaseForm,{fieldStars:false,fieldReview:false,fieldVisibility:false,onCreate:false,reviewsContainer:false,initialStarValue:false,editingReview:false,initialize:function($super,profile,options){options=options||{};options.createTitle="Submit your rating";options.editTitle="Edit your rating";this.reviewsContainer=options.reviewsContainer||false;this.editObjectType="IdeaReview";this.friendlyObjectName="review";this.onCreate=options.onCreate;
$super(profile,options)},createFields:function($super){this.fieldStars=new BrainstormJs.Forms.Fields.RatingStarsField({title:"Your rating",required:true,dataSelector:"input.data-Rating"});this.fieldReview=new BrainstormJs.Forms.Fields.TextArea({title:'Provide a review to help this team move forward: <span class="small">(optional)</span>',enableWysiwyg:true,dataSelector:"div.data-Review"});this.fieldVisibility=new BrainstormJs.Forms.Fields.RadioButtonChoice({required:true,choices:[{text:"Public review",
subtitle:"(anybody can see your review)",value:Brainstorm.Model.Enums.IdeaReviewVisibility.Public,checked:true},{text:"Private review",subtitle:"(only team members of this idea can see your review)",value:Brainstorm.Model.Enums.IdeaReviewVisibility.TeamOnly}],dataSelector:"input.data-Visibility"});this.registerField(this.fieldStars);this.registerField(this.fieldReview);this.registerField(this.fieldVisibility)},createNewObject:function($super){$super();Brainstorm.Web.Services.IdeaTasks.CreateOrUpdateReview(this.profile.id,
this.fieldStars.getValue(),this.fieldReview.getValue(),this.fieldVisibility.getValue(),this.onCreate,bsCommon.ajaxCallError)},startCreateOrEdit:function(linkClicked){if(linkClicked.hasClassName("inactiveOpenLink")){Effect.Shake(linkClicked,{distance:3});return}var myReviewDiv=this.reviewsContainer.getMyReview();this.reviewsContainer.updateSummaries({locked:true});if(myReviewDiv)this.startEditing(myReviewDiv,linkClicked);else this.showForm({linkClicked:linkClicked})},startCreate:function(){},startEditing:function(reviewDiv,
linkClicked){this.editingExisting=true;this.editingReview=reviewDiv;this.showForm({afterFinish:function(){if(this.initialStarValue)this.editingReview.down(this.fieldStars.dataSelector).value=this.initialStarValue;this.loadObjectValues(this.editingReview)}.bind(this),editMode:true,insertInto:this.parentContainer,linkClicked:linkClicked})},saveEditedObject:function(){if(this.editingExisting&&this.editingReview)Brainstorm.Web.Services.IdeaTasks.CreateOrUpdateReview(this.profile.id,this.fieldStars.getValue(),
this.fieldReview.getValue(),this.fieldVisibility.getValue(),this.reviewUpdated.bind(this),bsCommon.ajaxCallError)},reviewUpdated:function(jsonObjectView){var jsonReview=jsonObjectView.Object;this.closeForm({afterFinish:function(){this.reviewsContainer.updateSummaries({average:jsonReview.Idea.BayesianRating,rated:jsonReview.Rating,total:jsonReview.Idea.TotalRatings,locked:false});$("bayesian_avg").value=jsonReview.Idea.BayesianRating;$("total_ratings").value=jsonReview.Idea.TotalRatings;var header=
this.editingReview.down("div.header");var starValue=this.editingReview.down(this.fieldStars.dataSelector);starValue.value=jsonReview.Rating;$("user_rating").value=jsonReview.Rating;var starsDisplay=header.down("span.stars_fg");[1,2,3,4,5].each(function(num){starsDisplay.removeClassName("stars_"+num)});starsDisplay.addClassName("stars_"+jsonReview.Rating);var visibilityValue=this.editingReview.down(this.fieldVisibility.dataSelector);visibilityValue.value=jsonReview.VisibilityInt;var visibilityDisplay=
header.down("span.visibility");visibilityDisplay.innerHTML="public";var privateNotice=this.editingReview.down("div.privateNotice");if(jsonReview.Visibility==Brainstorm.Model.Enums.IdeaReviewVisibility.TeamOnly&&!privateNotice.visible())privateNotice.blindDown();else if(jsonReview.Visibility==Brainstorm.Model.Enums.IdeaReviewVisibility.Public&&privateNotice.visible())privateNotice.blindUp();var blankReview=this.editingReview.down("div.blankReview");if(jsonReview.HasReview&&blankReview.visible())blankReview.blindUp();
else if(!jsonReview.HasReview&&!blankReview.visible())blankReview.blindDown();var reviewText=this.editingReview.down(this.fieldReview.dataSelector);reviewText.innerHTML=jsonReview.ReviewText;reviewText.blindDown();new Effect.Highlight(reviewText)}.bind(this)});this.stopEditingObject()},setInitialStarValue:function(value){this.initialStarValue=value},beforeShow:function($super){$super();this.fieldReview.createWysiwyg();if(!this.editingExisting&&this.initialStarValue&&this.initialStarValue>0)this.fieldStars.setValue(this.initialStarValue)},
afterClose:function($super){$super();this.fieldReview.destroyWysiwyg();if(this.destroyOnClose)this.container.remove()},afterCancel:function(){if(this.reviewsContainer){this.reviewsContainer.updateSummaries({average:parseFloat($F("bayesian_avg"),10),total:parseInt($F("total_ratings"),10),rated:this.editingExisting?$F("user_rating"):false,locked:false});if(this.editingExisting&&this.editingReview&&this.initialStarValue){this.editingReview.down(this.fieldStars.dataSelector).value=$F("user_rating");this.initialStarValue=
false}}}});
BrainstormJs.Controls.ReviewsSummary=Class.create({options:false,container:false,starsContainer:false,ideaProfile:false,inModule:false,starControl:false,otherReviewsDiv:false,reviewsLink:false,myReviewBlurb:false,initialize:function(ideaProfile,container,options){this.ideaProfile=ideaProfile;this.container=$(container);this.options=options;this.starsContainer=this.container.down("div.starsContainer");this.reviewsLink=this.container.down("a.totalReviews");this.myReviewBlurb=this.container.down("div.myReviewBlurb");if(this.container.up("div#moduleIdeaSnapshot"))this.inModule=
true;var reviewsContainer=$("reviewsContainer");this.otherReviewsDiv=reviewsContainer.down("div.otherReviews");this.starControl=new BrainstormJs.Controls.RatingStars({element:this.starsContainer,average:options.bayesianAverage,total:options.totalRatings,userRating:options.userRating,onRate:this.onRate.bind(this),summaryControl:this});if(this.reviewsLink)this.reviewsLink.observe("click",function(e){this.onReviewLinkClick();e.stop()}.bind(this))},onRate:function(element,state){if(this.ideaProfile)for(var i=
0,j=this.ideaProfile.reviewSummaries.length;i<j;i++){var summaryControl=this.ideaProfile.reviewSummaries[i];var starControl=summaryControl.starControl;summaryControl.lock();starControl.setState(Object.extend(state,{locked:true}))}},onReviewLinkClick:function(){var reviewsDiv=this.otherReviewsDiv;var noOtherReviews=reviewsDiv.down("div.noData");var reviewsLinkAction=reviewsDiv.up("div.reviewsContainer").down("span.action");var reviewsOpen=false;var highlightReviewsFx=function(){new Effect.Highlight(noOtherReviews||
reviewsDiv,{duration:1,delay:0.5})};var scrollFx=function(){bsCommon.scrollIfBelowFold(reviewsDiv,10,{afterFinish:highlightReviewsFx})};if(this.inModule){reviewsDiv.show();reviewsOpen=true;bsCommon.scrollIfBelowFold(reviewsDiv,10,{afterFinish:highlightReviewsFx})}else if(!reviewsDiv.visible()){reviewsDiv.blindDown({duration:0.5,afterFinish:scrollFx});reviewsOpen=true}else{reviewsDiv.blindUp();reviewsOpen=false}if(reviewsLinkAction)reviewsLinkAction.innerHTML=reviewsOpen?"hide":"show"},lock:function(){this.container.addClassName("locked");
this.container.fade({duration:1,from:1,to:0.5})},unlock:function(){this.container.removeClassName("locked");this.container.appear({duration:1,from:0.5,to:1})},isLocked:function(){this.container.hasClassName("locked")}});
BrainstormJs.Controls.ReviewsContainer=Class.create({ideaProfile:false,container:false,formContainer:false,profile:false,noReviewDiv:false,myReviewContainer:false,otherReviewsContainer:false,addLink:false,editLink:false,ratingCountSpans:false,reviewCountSpans:false,initialize:function(ideaProfile,profile,options){this.ideaProfile=ideaProfile;this.container=$("reviewsContainer");this.myReviewContainer=$("myReview");this.noReviewDiv=this.myReviewContainer.down("div.noReview");this.otherReviewsContainer=
this.container.down("div.otherReviews");this.formContainer=this.container.down("div.reviewFormContainer");this.profile=profile;this.reviewForm=new BrainstormJs.Forms.IdeaReviewForm(this.profile,{reviewsContainer:this,parentContainer:this.formContainer,replaceElement:this.myReviewContainer.down("div.myReview"),onCreate:this.reviewCreated.bind(this)});this.wireUnboundAddEditLinks();this.ratingCountSpans=$$("div.reviewsSummary .ratingCount");this.reviewCountSpans=$$("div.reviewsSummary .reviewCount")},
wireUnboundAddEditLinks:function(){var unboundOpenLinks=$$("a.unboundEditReviewLink");var addOrEditFx=function(e){this.reviewForm.startCreateOrEdit(e.element());e.stop()}.bind(this);for(var i=0,j=unboundOpenLinks.length;i<j;i++){var openLink=unboundOpenLinks[i];openLink.observe("click",addOrEditFx);openLink.removeClassName("unboundEditReviewLink");this.reviewForm.addOpenLink(openLink)}},getMyReview:function(){return this.myReviewContainer.down("div.myReview")||false},reviewCreated:function(jsonObjectView){var jsonReview=
jsonObjectView.Object;var domElement=jsonObjectView.View;if(domElement&&domElement.HTML)this.myReviewContainer.insert(domElement.HTML);this.switchToEditMode();if(this.noReviewDiv&&this.noReviewDiv.visible())this.noReviewDiv.blindUp({duration:0.2});var ratingCountSpans=this.ratingCountSpans;var reviewCountSpans=this.reviewCountSpans;var otherReviewsDiv=this.otherReviewsContainer;this.reviewForm.closeForm({afterFinish:function(){this.updateSummaries({average:jsonReview.Idea.BayesianRating,rated:jsonReview.Rating,
total:jsonReview.Idea.TotalRatings,locked:false});$("bayesian_avg").value=jsonReview.Idea.BayesianRating;$("total_ratings").value=jsonReview.Idea.TotalRatings;this.wireUnboundAddEditLinks();if(domElement&&domElement.Id){var newReview=$(domElement.Id);newReview.blindDown({duration:0.5,afterFinish:function(){bsCommon.scrollIfBelowFold(newReview,10);for(var i=0,j=ratingCountSpans.length;i<j;i++)bsCommon.incrementDomInt(ratingCountSpans[i],true);if(jsonReview.HasReview&&jsonReview.JustCreated){for(var i=
0,j=reviewCountSpans.length;i<j;i++)bsCommon.incrementDomInt(reviewCountSpans[i],true);var noReviewsDiv=otherReviewsDiv.down("div.noReviews");var onlyMyReviewDiv=otherReviewsDiv.down("div.onlyMyReview");if(noReviewsDiv)noReviewsDiv.hide();if(onlyMyReviewDiv)onlyMyReviewDiv.show()}}})}}.bind(this)})},switchToEditMode:function(){var addEditLink=$("linkAddEditReview");addEditLink.innerHTML="Edit my rating";addEditLink.removeClassName("linkAddReview");addEditLink.addClassName("linkEditReview")},updateSummaries:function(state){for(var i=
0,j=this.ideaProfile.reviewSummaries.length;i<j;i++){var reviewSummary=this.ideaProfile.reviewSummaries[i];reviewSummary.starControl.setState(state);if(state.rated&&typeof state.rated!="undefined"&&reviewSummary.myReviewBlurb){reviewSummary.myReviewBlurb.innerHTML='You rated this idea <span class="numStars">'+state.rated+" stars</span>";new Effect.Highlight(reviewSummary.myReviewBlurb,{duration:1})}if(state.locked)reviewSummary.lock();else reviewSummary.unlock()}}});
BrainstormJs.Forms.Fields.MultiSelect.BaseMultiSelectField=Class.create(BrainstormJs.Forms.Fields.BaseField,{container:false,input:false,dropdown:false,guidance:false,completer:false,completerTabIndex:false,serviceUrl:false,allowMultiple:false,allowNewValues:false,maxItems:false,height:0,valueType:"string",fxItemAdded:false,initialize:function($super,options){options=options||{};if(options.warning!="")options.warning=options.warning||"Multiple values are comma-separated";this.completerTabIndex=BrainstormForms.getTabIndex();
this.maxItems=options.maxItems||false;this.allowMultiple=options.allowMultiple||false;this.fxItemAdded=options.fxItemAdded||false;$super(options)},render:function($super,renderOptions){this.container=new Element("div",{"class":"multiCompleter"});this.input=new Element("input",{"class":"textbox","type":"text","tabindex":this.tabIndex,"value":""});this.dropdown=new Element("div",{"class":"suggest"});this.suggestlist=new Element("ul",{"class":"feed"});this.container.identify();this.input.identify();
this.dropdown.identify();this.dropdown.insert(this.suggestlist);this.container.insert(this.input);this.container.insert(this.dropdown);if(this.required)this.input.addClassName("required");if(renderOptions&&renderOptions.controlOnly)return this.container;else return $super([this.container])},afterRender:function(){this.completer=new BrainstormJs.Controls.MultiCompleter(this.input,this.dropdown,{fetchFile:this.serviceUrl,allowMultiple:this.allowMultiple,newValues:this.allowNewValues,maxItems:this.maxItems,
tabIndex:this.completerTabIndex,height:this.height,fxItemAdded:this.fxItemAdded||false})},beforeValidation:function(){var tempInput=this.container.down("ul.holder li.bit-input input");if(this.allowNewValues&&tempInput&&tempInput.value&&tempInput.value.strip().length>0){this.completer.newvalue=true;this.completer.autoAdd(tempInput,false)}else if(tempInput)tempInput.value=""},isValid:function(){return this.hasValue()},hasValue:function(){return this.getValue()!=""},getValue:function(){var value=this.input.value.strip();
if(this.valueType=="int"){var tempValues=[];for(var parts=value.split(","),i=0,j=parts.length;i<j;i++){var part=parts[i];if(part&&part.strip()!=""){var numValue=parseInt(part,10);if(numValue!="NaN")tempValues.push(numValue)}}value=tempValues}else if(this.valueType=="object")return this.completer.bits.values();return value},setValue:function(values){this.clear();if(!values)return;if(!(values instanceof Array)&&values.length>0){var stringValues=values.split(",");values=[];for(var i=0,j=stringValues.length;i<
j;i++){var label=stringValues[i];values.push({id:label,label:label})}}var tempInput=this.container.down("ul.holder li.bit-input input");for(var i=0,j=values.length;i<j;i++){var value=values[i];if(!value)continue;this.completer.newvalue=true;this.completer.autoAdd(tempInput,false,value.id,value.label)}},clear:function(){this.input.value="";var boxes=this.container.select("ul.holder li.bit-box");for(var i=0,j=boxes.length;i<j;i++)this.completer.dispose(boxes[i]);var mainInput=this.container.down("ul.holder li.bit-input");
if(mainInput&&!mainInput.visible())mainInput.show()},focus:function(){if(!this.completer.isMaxReached()){var tempInput=this.container.down("ul.holder li.bit-input input.maininput");if(tempInput&&tempInput.visible())try{tempInput.focus()}catch(e){}}},disable:function(){},getElement:function(){return this.container}});
BrainstormJs.Forms.Fields.MultiSelect.HybridSelect=Class.create(BrainstormJs.Forms.Fields.MultiSelect.BaseMultiSelectField,{initialize:function($super,options){options=options||{};options.cssClass="hybridSelect";options.warning=false;options.fxItemAdded=this.itemAdded.bind(this);$super(options);this.serviceUrl="/Services/PersonSearch.asmx/FindPeopleAndTags";this.allowNewValues=false;this.valueType="object"},itemAdded:function(elem,item){if(item.type=="Tag"){var numSubscribed=item.subcaption;numSubscribed+=
numSubscribed==1?" Person":" People";$(elem.identify()).down(".detail").update("("+numSubscribed+")").show()}}});
BrainstormJs.Forms.ShareObjectForm=Class.create(BrainstormJs.Forms.BaseForm,{fieldMessage:false,fieldPeople:false,fieldAddComment:false,showCommentField:false,initialize:function($super,profile,options){options=options||{};options.createTitle="Share with others via email";options.submitButtonTitle="Send";var url=document.location.pathname.toLowerCase();var isProfile=(url.indexOf("idea.aspx")>=0||url.indexOf("pipeline.aspx")>=0||url.indexOf("challenge.aspx")>=0)&&!options.hideCommentField;this.showCommentField=
isProfile;$super(profile,options)},createFields:function($super){this.fieldPeople=new BrainstormJs.Forms.Fields.MultiSelect.HybridSelect({title:"Choose people",required:true,help:'<p>Start typing a name to find people you can share with. Select that person from the list to add them. Repeat that process until you have all the people you need and hit "Send."</p>'});this.fieldMessage=new BrainstormJs.Forms.Fields.TextArea({title:"Message",required:false,enableWysiwyg:false});if(this.showCommentField)this.fieldAddComment=
new BrainstormJs.Forms.Fields.CheckBox({title:"Post to comments section",required:false,startChecked:false});this.registerField(this.fieldPeople);this.registerField(this.fieldMessage);if(this.showCommentField)this.registerField(this.fieldAddComment)},createNewObject:function($super){$super();var pageUrl=bsCommon.getPageUrl(true);Brainstorm.Web.Services.Ajax.ShareObject(this.profile.objectType||"page",this.profile.id||"page",this.fieldPeople.getValue(),this.fieldMessage.getValue(),pageUrl,this.fieldAddComment?
this.fieldAddComment.getValue():false,this.onSuccess.bind(this),bsCommon.ajaxCallError)},onSuccess:function(domElement){var successMessage="Message sent.";if(domElement){var commentContainer=$("container").down("div.commentsSection div.commentContainer");if(commentContainer){BrainstormJs.Controls.Comments.CommentUtils.addNewComment({jsonCommentElement:domElement,commentContainer:commentContainer,scrollToComment:false});successMessage="Message sent and comment added."}}this.closeForm({afterFinish:function(){bsCommon.showSuccess(successMessage)}})},
afterClose:function($super){if(this.options.destroyOnClose)this.container.remove()}});if(typeof Prototype=="undefined")throw"Control.SelectMultiple requires Prototype to be loaded.";if(typeof Object.Event=="undefined")throw"Control.SelectMultiple requires Object.Event to be loaded.";
Control.SelectMultiple=Class.create({select:false,container:false,numberOfCheckedBoxes:0,checkboxes:[],hasExtraOption:false,initialize:function(select,container,options){this.options={checkboxSelector:"input[type=checkbox]",nameSelector:"span.name",labelSeparator:", ",valueSeparator:",",afterChange:Prototype.emptyFunction,overflowString:function(str){return str.truncate()},overflowLength:30};Object.extend(this.options,options||{});this.select=$(select);this.container=$(container);this.checkboxes=
typeof this.options.checkboxSelector=="function"?this.options.checkboxSelector.bind(this)():this.container.getElementsBySelector(this.options.checkboxSelector);var value_was_set=false;if(this.options.value){value_was_set=true;this.setValue(this.options.value);delete this.options.value}this.hasExtraOption=false;this.checkboxes.each(function(checkbox){checkbox.observe("click",this.checkboxOnClick.bind(this,checkbox))}.bind(this));this.select.observe("change",this.selectOnChange.bind(this));this.countAndCheckCheckBoxes();
if(!value_was_set)this.scanCheckBoxes();this.notify("afterChange",this.select.options[this.select.options.selectedIndex].value)},countAndCheckCheckBoxes:function(){this.numberOfCheckedBoxes=this.checkboxes.inject(0,function(number,checkbox){checkbox.checked=this.select.options[this.select.options.selectedIndex].value==checkbox.value;var value_string=this.select.options[this.select.options.selectedIndex].value;var value_collection=$A(value_string.split?value_string.split(this.options.valueSeparator):
value_string);var should_check=value_collection.any(function(value){if(!should_check&&checkbox.value==value)return true}.bind(this));checkbox.checked=should_check;if(checkbox.checked)++number;return number}.bind(this))},setValue:function(value_string){this.numberOfCheckedBoxes=0;var value_collection=$A(value_string.split?value_string.split(this.options.valueSeparator):value_string);this.checkboxes.each(function(checkbox){checkbox.checked=false;value_collection.each(function(value){if(checkbox.value==
value){++this.numberOfCheckedBoxes;checkbox.checked=true}}.bind(this))}.bind(this));this.scanCheckBoxes()},selectOnChange:function(){this.removeExtraOption();this.countAndCheckCheckBoxes();this.notify("afterChange",this.select.options[this.select.options.selectedIndex].value)},checkboxOnClick:function(checkbox){this.numberOfCheckedBoxes=this.checkboxes.findAll(function(c){return c.checked}).length;this.scanCheckBoxes();this.notify("afterChange",this.numberOfCheckedBoxes===0?"":this.select.options[this.select.options.selectedIndex].value)},
scanCheckBoxes:function(){switch(this.numberOfCheckedBoxes){case 1:this.checkboxes.each(function(checkbox){if(checkbox.checked){$A(this.select.options).each(function(option,i){if(option.value==checkbox.value){this.select.options.selectedIndex=i;throw $break;}}.bind(this));throw $break;}}.bind(this));break;case 0:this.removeExtraOption();break;default:this.addExtraOption();break}},getLabelForExtraOption:function(){var label=(typeof this.options.nameSelector=="function"?this.options.nameSelector.bind(this)():
this.container.getElementsBySelector(this.options.nameSelector).inject([],function(labels,name_element,i){if(this.checkboxes[i].checked)labels.push(name_element.innerHTML);return labels}.bind(this))).join(this.options.labelSeparator);return label.length>=this.options.overflowLength&&this.options.overflowLength>0?typeof this.options.overflowString=="function"?this.options.overflowString(label):this.options.overflowString:label},getValueForExtraOption:function(){return this.checkboxes.inject([],function(values,
checkbox){if(checkbox.checked)values.push(checkbox.value);return values}).join(this.options.valueSeparator)},addExtraOption:function(){this.removeExtraOption();this.hasExtraOption=true;this.select.options[this.select.options.length]=new Option(this.getLabelForExtraOption(),this.getValueForExtraOption());this.select.options.selectedIndex=this.select.options.length-1},removeExtraOption:function(){if(this.hasExtraOption){this.select.remove(this.select.options.length-1);this.hasExtraOption=false}}});
Object.Event.extend(Control.SelectMultiple);
BrainstormJs.Forms.Fields.MultiDropDownList=Class.create(BrainstormJs.Forms.Fields.BaseField,{wrapper:false,select:false,addBlank:false,blankLabel:false,popupLink:false,popupContainer:false,popupTitle:false,popupHeader:false,popupTable:false,popupTableBody:false,popupFooter:false,popupCloseButton:false,value:false,selectMultipleControl:false,dropDownChoices:[],popupChoices:[],initialize:function($super,options){options=options||{};options.cssClass="multiDropDownList";$super(options);this.popupTitle=
options.popupTitle||"Select multiple objects";if(options.addBlank!==undefined){this.addBlank=options.addBlank;if(options.blankLabel)this.blankLabel=options.blankLabel}},render:function($super){this.wrapper=new Element("div",{"class":this.cssClass});this.wrapper.identify();this.select=new Element("select",{"tabindex":BrainstormForms.getTabIndex(),"class":"multidropdownselect"});if(this.required&&this.addBlank&&!this.blankLabel)this.select.addClassName("validate-selection");this.popupLink=(new Element("a",
{"href":"","class":"openPopup","tabindex":BrainstormForms.getTabIndex()})).update("Select Multiple");this.popupLink.identify();this.popupContainer=new Element("div",{"style":"display:none;","class":"popupContainer"});this.popupContainer.identify();this.popupHeader=(new Element("div",{"class":"header"})).update(this.popupTitle);this.popupTable=new Element("table",{"cellspacing":"0","cellpadding":"0","width":"100%"});this.popupTableBody=new Element("tbody");this.popupTable.insert(this.popupTableBody);
this.draw(this.addBlank);this.popupFooter=new Element("div",{"class":"footer"});this.popupCloseButton=new Element("input",{"type":"button","value":"Done","tabindex":BrainstormForms.getTabIndex()});this.popupFooter.insert(this.popupCloseButton);this.popupContainer.insert(this.popupHeader);this.popupContainer.insert(this.popupTable);this.popupContainer.insert(this.popupFooter);this.wrapper.insert(this.select);this.wrapper.insert(this.popupLink);this.wrapper.insert(this.popupContainer);return $super([this.wrapper])},
draw:function(addBlank){if(this.options.choices){if(addBlank)this.select.insert((new Element("option",{"value":""})).update(this.blankLabel?this.blankLabel:""));for(var i=0,j=this.options.choices.length;i<j;i++){var choice=this.options.choices[i];var value=typeof choice.value=="undefined"?choice.Value:choice.value;var option=(new Element("option",{"value":value})).update(choice.text||choice.Text);this.dropDownChoices.push(option);this.select.insert(option);if(choice.excludeFromPopup)continue;var choiceRow=
new Element("tr",{"class":i%2==0?"even":"odd"});var choiceNameCell=(new Element("td",{"class":"name"})).update(choice.text||choice.Text);var choiceCheckCell=new Element("td",{"class":"checkbox"});var choiceCheckBox=new Element("input",{"type":"checkbox","value":value});this.popupChoices.push(choiceRow);choiceCheckCell.insert(choiceCheckBox);choiceRow.insert(choiceNameCell);choiceRow.insert(choiceCheckCell);this.popupTableBody.insert(choiceRow)}}},afterRender:function(){this.selectMultipleControl=
new Control.SelectMultiple(this.select,this.popupContainer,{checkboxSelector:"table tr td.checkbox input[type=checkbox]",nameSelector:"table tr td.name",afterChange:function(value){this.value=value;if(this.selectMultipleControl&&this.selectMultipleControl.setSelectedRows)this.selectMultipleControl.setSelectedRows()}.bind(this)});this.selectMultipleControl.setSelectedRows=function(){this.checkboxes.each(function(checkbox){var tr=$(checkbox.parentNode.parentNode);tr.removeClassName("selected");if(checkbox.checked)tr.addClassName("selected")})}.bind(this.selectMultipleControl);
for(var i=0,j=this.selectMultipleControl.checkboxes.length;i<j;i++){var checkbox=$(this.selectMultipleControl.checkboxes[i]);checkbox.observe("click",this.selectMultipleControl.setSelectedRows)}this.selectMultipleControl.setSelectedRows();this.popupLink.observe("click",function(event){if(this.enabled){this.select.style.visibility="hidden";new Effect.BlindDown(this.popupContainer,{duration:0.3})}Event.stop(event);return false}.bind(this));this.popupCloseButton.observe("click",function(event){$(this.select).style.visibility=
"visible";new Effect.BlindUp(this.container,{duration:0.3});Event.stop(event);return false}.bindAsEventListener(this.selectMultipleControl))},hasValue:function(){return this.getValue()!=""},getValue:function(){return this.value},getIntValues:function(){var stringValue=this.getValue();var integers=[];if(!stringValue||stringValue==="")return integers;var parts=stringValue.split(",");for(var i=0,j=parts.length;i<j;i++){var part=parts[i];if(part&&part.strip().length>0)integers.push(parseInt(part,10))}return integers},
setValue:function(value){this.value=value;this.selectMultipleControl.setValue(value)},clear:function(){this.setValue(0);this.select.selectedIndex=0},focus:function(){this.select.focus()},enable:function($super){this.select.disabled=false;this.popupLink.show()},disable:function($super){this.select.disabled=true;Effect.BlindUp(this.popupLink,{duration:0.3})}});
BrainstormJs.Forms.SubscriptionForm=Class.create(BrainstormJs.Forms.BaseForm,{objectType:false,objectId:false,fieldFrequency:false,followersDiv:false,followersFacesDiv:false,initialize:function($super,objectType,objectId,options){options=options||{};options.createTitle=options.createTitle||"Manage email notifications";options.submitButtonTitle=options.submitButtonTitle||"Save";this.objectType=objectType;this.objectId=objectId;$super(null,options)},createFields:function($super){this.fieldFrequency=
this.getFrequencyField(false);this.registerField(this.fieldFrequency)},getFrequencyField:function(addBlank){var choices=[];if(!addBlank)choices.push({value:Brainstorm.Model.Enums.NotificationFrequency.None,text:"None",excludeFromPopup:true});choices.push({value:Brainstorm.Model.Enums.NotificationFrequency.Instant,text:"Instant"});choices.push({value:Brainstorm.Model.Enums.NotificationFrequency.Daily,text:"Daily"});choices.push({value:Brainstorm.Model.Enums.NotificationFrequency.Weekly,text:"Weekly"});
var field=new BrainstormJs.Forms.Fields.MultiDropDownList({title:"Notification Frequency",required:true,choices:choices,addBlank:addBlank||false,popupTitle:"Select multiple frequencies",help:"<p><strong>Instant</strong> - sends an email as soon as activity occurs.</p><p><strong>Daily</strong> - sends an email digest once a day of the activity that happened over the previous day.</p><p><strong>Weekly</strong> - sends an email digest once a week of the activity that happened over the previous week.</p>"});
return field},beforeShow:function(){this.fieldFrequency.setValue($("userCurrentSubs").value)},createNewObject:function($super){var facesDiv=$("followerFaces");var showFaces=facesDiv&&facesDiv.visible()?true:false;var fieldFrequencies=this.fieldFrequency.getIntValues();Brainstorm.Web.Services.Ajax.UpdateSubscriptions(this.objectType,this.objectId,fieldFrequencies,showFaces,this.onSuccess.bind(this),bsCommon.ajaxCallError,fieldFrequencies);$("userCurrentSubs").value=this.fieldFrequency.getValue()},
onSuccess:function(newFollowersHtml,fieldFrequencies){this.closeForm({afterFinish:function(){if(newFollowersHtml&&newFollowersHtml.length>1){this.followersDiv=this.followersDiv||$("followers");this.followersDiv.innerHTML=newFollowersHtml;new Effect.Highlight(this.followersDiv,{delay:0.5})}}});var message="";if($("moduleTagSnapshot"))message=" This tag has also been added to your interests.";bsCommon.subscriptionMessage(message,fieldFrequencies[0]!=undefined&&fieldFrequencies[0]!=0)},afterClose:function($super){if(this.options.destroyOnClose)this.container.remove()}});
BrainstormJs.Forms.SystemSubscriptionForm=Class.create(BrainstormJs.Forms.SubscriptionForm,{fieldBizUnit:false,fieldActivityType:false,initialize:function($super,options){options=options||{};options.createTitle="Subscribe to email notifications";options.submitButtonTitle="Save";$super(false,false,options)},createFields:function($super){var bizUnitChoices=[];bizUnitChoices.push({value:0,text:"All "+$F("BS_Config_AreaName")+"s",excludeFromPopup:true});bizUnitChoices.push(choices_Brainstorm_Model_Data_Ideas_IdeaBusinessUnit);
bizUnitChoices=bizUnitChoices.flatten();this.fieldBizUnit=new BrainstormJs.Forms.Fields.MultiDropDownList({title:$F("BS_Config_AreaName")+"(s)",required:true,choices:bizUnitChoices,addBlank:true,popupTitle:"Select multiple "+$F("BS_Config_AreaName").toLowerCase()+"s",help:"<p>Following "+$F("BS_Config_AreaName")+" activity is a great way to stay on top of the innovation going on in a specific "+$F("BS_Config_AreaName")+".</p><p>Select the desired "+$F("BS_Config_AreaName")+" from the drop down. If you want to follow activity in multiple "+
$F("BS_Config_AreaName")+'s, click "Select Multiple."</p>'});this.registerField(this.fieldBizUnit);var activityChoices=[];activityChoices.push({value:Brainstorm.Model.Enums.SystemSubscriptionType.NewIdeas,text:"New idea submissions only"});activityChoices.push({value:Brainstorm.Model.Enums.SystemSubscriptionType.AllActivity,text:"All activity"});this.fieldActivityType=new BrainstormJs.Forms.Fields.DropDownList({title:"What activity do you want to see?",required:true,choices:activityChoices,addBlank:true});
this.registerField(this.fieldActivityType);this.fieldFrequency=this.getFrequencyField(true);this.registerField(this.fieldFrequency)},beforeShow:function($super){},createNewObject:function($super){Brainstorm.Web.Services.Ajax.CreateSystemSubscriptions(this.fieldBizUnit.getIntValues(),parseInt(this.fieldActivityType.getValue(),10),this.fieldFrequency.getIntValues(),this.onSuccess.bind(this),bsCommon.ajaxCallError)},onSuccess:function(){this.closeForm({afterFinish:function(){bsCommon.showSuccess("Thanks for subscribing! You are now officially awesome!")}})}});
BrainstormJs.Controls.Follow.FollowIdea=Class.create({shareFollowControl:false,wrapper:false,ideaId:false,closeLink:false,loadingDiv:false,content:false,contentLoaded:false,refreshContentLink:false,initialize:function(shareFollowControl,wrapper,ideaId){this.shareFollowControl=shareFollowControl;this.wrapper=wrapper;this.ideaId=ideaId;this.closeLink=this.wrapper.down("div.header a.close");this.closeLink.observe("click",function(e){this.close();e.stop()}.bind(this));this.loadingDiv=this.wrapper.down("div.loading");
this.content=this.wrapper.down("div.followContent")},close:function(){this.wrapper.blindUp({duration:0.5,afterFinish:function(){this.shareFollowControl.afterSubscribe()}.bind(this)})},show:function(){this.wrapper.blindDown({duration:0.5,afterFinish:function(){if(!this.contentLoaded)this.requestContent()}.bind(this)})},requestContent:function(){Brainstorm.Web.Services.Ajax.GetFollowIdeaBody(this.ideaId,this.insertContent.bind(this),bsCommon.ajaxCallError)},refreshContent:function(){this.loadingDiv.blindDown({duration:0.25,
afterFinish:this.requestContent.bind(this)})},insertContent:function(domElement){this.content.innerHTML=domElement.HTML;if(!this.content.visible())this.content.blindDown({duration:0.5});this.loadingDiv.blindUp({duration:0.25,delay:0.05});this.contentLoaded=true;window.setTimeout(function(){this.wireEvents()}.bind(this),1)},wireEvents:function(){this.refreshContentLink=this.content.down("a.refreshTagSubs");if(this.refreshContentLink)this.refreshContentLink.observe("click",function(e){this.refreshContent();
e.stop()}.bind(this));bsCommon.wireSubscriptionCheckboxes()}});
BrainstormJs.Controls.ShareFollow=Class.create({container:false,objectType:false,objectId:false,shareButton:false,shareContainer:false,shareFormContainer:false,shareCopyDiv:false,shareBox:false,followButton:false,followContainer:false,followClose:false,subscribeLink:false,shareForm:false,subscriptionForm:false,followIdea:false,initialize:function(container){this.container=$(container);this.objectType=this.container.down("input.objectType").value;this.objectId=this.container.down("input.objectId").value;
var profile={objectType:this.objectType,id:this.objectId};this.shareButton=this.container.down("a.shareLink");if(this.shareButton){this.shareButton.observe("click",function(e){this.onShare();e.stop()}.bind(this));this.shareContainer=this.container.down("div.shareContainer");this.shareFormContainer=this.shareContainer.down("div.shareFormContainer");this.shareForm=new BrainstormJs.Forms.ShareObjectForm(profile,{parentContainer:this.shareFormContainer,afterClose:this.afterShare.bind(this)});this.shareCopyDiv=
this.shareContainer.down("div.shareCopy");this.shareBox=this.shareCopyDiv.down("input.shareBox");this.shareBox.value=window.location.href.toLowerCase();this.shareBox.observe("click",function(e){e.element().select()})}this.followButton=this.container.down("a.followLink");if(this.followButton){this.followButton.observe("click",function(e){this.onFollow();e.stop()}.bind(this));this.followContainer=this.container.down("div.followContainer");var _formOptions={parentContainer:this.followContainer,afterClose:this.afterSubscribe.bind(this)};
var url=document.location.pathname.toLowerCase();if(url.endsWith("ideas.aspx"))this.subscriptionForm=new BrainstormJs.Forms.SystemSubscriptionForm(_formOptions);else if(url.endsWith("idea.aspx"))this.followIdea=new BrainstormJs.Controls.Follow.FollowIdea(this,this.followContainer.down("div.followIdeaWrapper"),this.objectId);else this.subscriptionForm=new BrainstormJs.Forms.SubscriptionForm(this.objectType,this.objectId,_formOptions)}},onShare:function(){if(this.activateSection(this.shareButton,this.followButton,
this.shareContainer,this.followContainer)){this.shareForm.showForm();var contextualHelpItem=$("shareHelpMessage");if(contextualHelpItem)contextualHelpItem.blindUp()}},onFollow:function(){if(this.activateSection(this.followButton,this.shareButton,this.followContainer,this.shareContainer))if(this.subscriptionForm)this.subscriptionForm.showForm();else if(this.followIdea)this.followIdea.show()},afterShare:function(){this.restoreButtons()},afterSubscribe:function(){this.restoreButtons()},activateSection:function(linkToActivate,
linkToDeactivate,sectionToShow,sectionToHide){if(sectionToShow)sectionToShow.show();if(sectionToHide)sectionToHide.hide();var activated=false;if(linkToActivate.hasClassName("active")||linkToActivate.hasClassName("inactive"))Effect.Shake(linkToActivate,{distance:3});else{linkToActivate.addClassName("active");if(linkToDeactivate){linkToDeactivate.addClassName("inactive");Effect.Fade(linkToDeactivate,{to:0.25,duration:0.5,delay:0.25})}Effect.Fade(linkToActivate,{to:0.8,duration:0.5});activated=true}return activated},
restoreButtons:function(links){var buttons=[];buttons.push(this.shareButton);if(this.followButton!=null)buttons.push(this.followButton);buttons.each(function(button){button.removeClassName("active");button.removeClassName("inactive");Effect.Appear(button,{to:1,duration:0.5})});if(this.shareContainer)this.shareContainer.hide();if(this.followContainer)this.followContainer.hide()}});
BrainstormJs.Controls.SidePanel=Class.create({container:false,addIdeaTab:false,feedbackTab:false,addIdeaTabLink:false,feedbackTabLink:false,formContainer:false,ideaForm:false,feedbackForm:false,links:false,viewportSize:false,minRequiredWidth:1032,scrollExpander:false,initialize:function(){this.links=[];this.container=$("sidePanel");if(!this.container)return;this.addIdeaTab=$("addIdeaTab");this.feedbackTab=$("feedbackTab");this.addIdeaTabLink=$("addIdeaTabLink");this.feedbackTabLink=$("feedbackTabLink");
this.formContainer=$("sidePanelFormContainer");this.scrollExpander=$("scrollExpander");if(this.addIdeaTab)this.ideaForm=new BrainstormJs.Forms.IdeaForm({parentContainer:this.formContainer,destroyOnClose:false,afterClose:this.afterHide.bind(this),scrollToBottom:false});if(this.feedbackTab)this.feedbackForm=new BrainstormJs.Forms.FeedbackForm(this,bsCommon.getPageUrl(true),{parentContainer:this.formContainer,destroyOnClose:false,afterClose:this.afterHide.bind(this),scrollToBottom:false});this.updateViewportSize();
if(this.addIdeaTabLink&&this.feedbackTabLink){this.addIdeaTabLink.observe("click",function(e){this.showForm(this.ideaForm,e.element(),this.feedbackTabLink);e.stop()}.bind(this));this.links.push(this.addIdeaTabLink);this.feedbackTabLink.observe("click",function(e){this.showForm(this.feedbackForm,e.element(),this.addIdeaTabLink);e.stop()}.bind(this));this.links.push(this.feedbackTabLink);for(var i=0,j=this.links.length;i<j;i++){var link=this.links[i];link.observe("mouseover",function(e){this.onButtonEnter(e.element())}.bind(this));
link.observe("mouseout",function(e){this.onButtonLeave(e.element())}.bind(this))}}var minRequiredWidth=1041;this.toggleTabs(true);Event.observe(document.onresize?document:window,"resize",this.updateViewportSize.bind(this));if(this.formContainer){var fxCheckViewportHeight=this.checkViewportHeight.bind(this);new PeriodicalExecuter(fxCheckViewportHeight,1)}},toggleTabs:function(show){if(show){if(this.addIdeaTab&&this.viewportSize.width>=this.minRequiredWidth)Effect.Appear(this.addIdeaTab,{duration:0.5,
delay:0.25});if(this.feedbackTab&&this.viewportSize.width>=this.minRequiredWidth)Effect.Appear(this.feedbackTab,{duration:0.5,delay:0.5})}},showForm:function(form,linkToActivate,linkToDeactivate){if(linkToActivate.hasClassName("activeTabLink")||linkToActivate.hasClassName("inactiveTabLink"))Effect.Shake(linkToActivate,{distance:3});else{linkToActivate.addClassName("activeTabLink");form.showForm();linkToDeactivate.addClassName("inactiveTabLink");Effect.Fade(linkToActivate,{to:0.8,duration:0.5});Effect.Fade(linkToDeactivate,
{to:0.25,duration:0.5,delay:0.25})}},afterHide:function(links){this.addIdeaTabLink.removeClassName("activeTabLink");this.feedbackTabLink.removeClassName("activeTabLink");this.addIdeaTabLink.removeClassName("inactiveTabLink");this.feedbackTabLink.removeClassName("inactiveTabLink");this.addIdeaTabLink.appear();this.feedbackTabLink.appear();new Effect.Morph(this.addIdeaTabLink,{style:"width:29px;",duration:0.25});new Effect.Morph(this.feedbackTabLink,{style:"width:29px;",duration:0.25})},onButtonEnter:function(button){if(!button.hasClassName("activeTabLink")&&
!button.hasClassName("inactiveTabLink"))new Effect.Morph(button,{style:"width:35px;",duration:0.25})},onButtonLeave:function(button){if(!button.hasClassName("activeTabLink")&&!button.hasClassName("inactiveTabLink"))new Effect.Morph(button,{style:"width:29px;",duration:0.25})},updateViewportSize:function(){this.viewportSize=document.viewport.getDimensions();if(this.viewportSize.width<this.minRequiredWidth&&this.container.visible())this.container.hide();else if(this.viewportSize.width>=this.minRequiredWidth&&
!this.container.visible())this.container.show()},checkViewportHeight:function(){if(this.formContainer&&this.formContainer.visible()){var height=this.formContainer.getDimensions().height;if(height>0){var heightNeeded=this.formContainer.getHeight()+this.formContainer.cumulativeScrollOffset().top;var heightAvailable=document.viewport.getHeight()+document.viewport.getScrollOffsets().top;var newHeight=Math.max(0,heightNeeded-heightAvailable);this.scrollExpander.setStyle({height:newHeight+"px"})}}}});
BrainstormJs.Forms.Fields.ImageUploadField=Class.create(BrainstormJs.Forms.Fields.BaseField,{image:false,newImage:false,editOverlay:false,initialize:function($super,options){options=options||{};options.cssClass=" imageUploadField";$super(options)},render:function($super){this.fieldContainer=new Element("div",{"class":"clearfix"});this.imageContainer=new Element("div",{"class":"imageContainer"});this.formContainer=new Element("div",{"id":"imageFormContainer","class":"imageFormContainer","style":"display:none;"});
this.image=new Element("img",{"class":"addImage editable","src":"/images/buttons/add-image-icon-flat.png"});this.imageSrc=new Element("input",{"class":"imageSrc","type":"hidden","value":""});this.addBanner=new Element("div",{"class":"overlayBanner addBanner"});this.backdrop=new Element("div",{"class":"backdrop"});this.span=new Element("span");this.span.innerHTML="Add Image";this.addBanner.insert(this.backdrop);this.addBanner.insert(this.span);this.imageContainer.insert(this.formContainer);this.imageContainer.insert(this.image);
this.imageContainer.insert(this.imageSrc);this.imageContainer.insert(this.addBanner);this.fieldContainer.insert(this.imageContainer);return $super([this.fieldContainer])},afterRender:function(){this.wireOnClick()},wireOnClick:function(){this.image.observe("click",this.onClick.bind(this));this.addBanner.observe("click",this.onClick.bind(this))},onClick:function(e){this.showForm(e.element());e.stop()},showForm:function(linkToActivate,linkToDeactivate){if(this.image.hasClassName("displayed")||linkToActivate.hasClassName("activeTabLink")||
linkToActivate.hasClassName("inactiveTabLink"));else{this.image.addClassName("active");this.image.addClassName("displayed");this.imageUploadForm=new BrainstormJs.Forms.ImageUploadForm3({fieldLabel:"File",submitButtonTitle:"Submit",uploadProfileImage:false,parentContainer:this.formContainer,destroyOnClose:true,imageSaved:this.imageSaved.bind(this),afterClose:this.afterHide.bind(this)});this.formContainer.show();this.imageUploadForm.showForm();this.addBanner.addClassName("hidden")}},afterHide:function(links){this.formContainer.hide();
this.image.removeClassName("active");this.image.removeClassName("displayed");this.hideChange(this.image);new Effect.Highlight(this.fieldContainer)},hideChange:function(elm){if(this.image.src.indexOf("add-image-icon-flat")==-1){this.image.removeClassName("addImage");this.image.addClassName("existingImage")}this.addBanner.removeClassName("hidden")},imageSaved:function(jsonImage){var imageUrl=jsonImage.WasModified?jsonImage.ModifiedImageUrl:jsonImage.ImageUrl;this.setValue(imageUrl);this.imageUploadForm.closeForm()},
setValue:function(imageUrl){this.imageContainer.addClassName("hidden");this.newImage=new Image;this.newImage.onload=function(){this.insertAndClose(imageUrl)}.bind(this);this.newImage.src=imageUrl},insertAndClose:function(imageUrl){this.image.src=imageUrl;if(imageUrl.indexOf("add-image-icon-flat")==-1){this.imageSrc.value=imageUrl;this.image.width=this.newImage.width;this.image.height=this.newImage.height;this.image.addClassName("existingImage");this.image.removeClassName("addImage");this.span.innerHTML=
"Change Image"}else this.span.innerHTML="Add Image";this.imageContainer.removeClassName("hidden")},getValue:function(){return this.imageSrc.value},getElement:function(){return this.image},clear:function(){this.setValue("")},setDefaultImage:function(){this.setValue("/images/buttons/add-image-icon-flat.png")}});
BrainstormJs.Forms.SuccessStoryForm=Class.create(BrainstormJs.Forms.BaseForm,{onCreate:false,successStoryContainer:false,editingStory:false,initialize:function($super,profile,options){options=options||{};options.createTitle="Tell your success story";options.editTitle="Edit your success story";this.successStoryContainer=options.successStoryContainer||false;this.parentObjectId=options.parentObjectId||false;this.parentObjectType=options.parentObjectType||false;this.editObjectType="SuccessStory";this.friendlyObjectName=
"story";if(options.destroyOnClose)this.destroyOnClose=options.destroyOnClose;this.onCreate=options.onCreate;this.onEdit=options.onEdit;$super(profile,options)},createFields:function($super){this.headline=new BrainstormJs.Forms.Fields.TextBox({title:"Headline",required:true,maxLength:1024,dataSelector:".data-Headline"});this.fieldBody=new BrainstormJs.Forms.Fields.TextArea({title:"Description",required:true,enableWysiwyg:true,dataSelector:".data-Body"});this.imageUploadField=new BrainstormJs.Forms.Fields.ImageUploadField({title:"Image (e.g. team photo, diagram)",
fileSizeLimit:"10 MB",fileTypes:"*.jpg;*.jpeg;*.png;*.gif;*.bmp",fileTypesDescription:"Image Files",dataSelector:".data-File"});this.registerField(this.headline);this.registerField(this.fieldBody);this.registerField(this.imageUploadField)},startCreate:function(linkClicked){if(linkClicked.hasClassName("inactiveOpenLink")){Effect.Shake(linkClicked,{distance:3});return}this.showForm({afterFinish:function(){this.imageUploadField.setDefaultImage()}.bind(this),linkClicked:linkClicked})},createNewObject:function($super){$super();
Brainstorm.Web.Services.Ajax.AddSuccessStoryToObject(bsCommon.getRequestToken(),this.parentObjectType,this.parentObjectId,this.headline.getValue(),this.fieldBody.getValue(),this.imageUploadField.getValue(),this.onCreate,bsCommon.ajaxCallError)},startEditing:function(successStory,editLinkClicked){this.editingExisting=true;this.editingStory=successStory;var container=this.editingStory.container;var successStoryWrapper=container.down("div.successStoryWrapper");successStoryWrapper.addClassName("foldedSuccessStory");
this.showForm({afterFinish:function(){this.loadObjectValues(this.editingStory.container)}.bind(this),editMode:true,linkClicked:editLinkClicked})},saveEditedObject:function(){if(this.editingExisting&&this.editingStory)Brainstorm.Web.Services.Ajax.EditSuccessStory(bsCommon.getRequestToken(),this.editingStory.id,this.headline.getValue(),this.fieldBody.getValue(),this.imageUploadField.getValue(),this.storyUpdated.bind(this),this.handleAjaxError.bind(this))},storyUpdated:function(jsonSuccessStory){var container=
this.editingStory.container;this.closeForm({afterFinish:function(){var headline=container.down(this.headline.dataSelector);headline.innerHTML=jsonSuccessStory.Headline;var body=container.down(this.fieldBody.dataSelector);body.innerHTML=jsonSuccessStory.Body;if(jsonSuccessStory.ImageExists){var profileImageHiddenInput=container.down(this.imageUploadField.dataSelector);profileImageHiddenInput.value=jsonSuccessStory.ProfileImageUrl;var storyImageContainer=container.down("a.storyImageContainer");if(!storyImageContainer)storyImageContainer=
container.down("a.noStoryImage");storyImageContainer.href=jsonSuccessStory.ProfileImageUrl;if(jsonSuccessStory.WasModified)storyImageContainer.href=jsonSuccessStory.ImageUrl;var img=storyImageContainer.down("img.storyImage");var newImage=new Element("img",{"class":"storyImage","src":jsonSuccessStory.ProfileImageUrl});img.replace(newImage);storyImageContainer.removeClassName("noStoryImage");storyImageContainer.addClassName("storyImageContainer")}this.onEdit();headline.blindDown();body.blindDown();
new Effect.Highlight(container)}.bind(this)});this.editingStory=false;this.stopEditingObject()},beforeShow:function($super){$super();this.fieldBody.createWysiwyg()},afterClose:function(){this.fieldBody.destroyWysiwyg();if(this.destroyOnClose)this.container.remove()}});
BrainstormJs.Controls.SuccessStoryContainer=Class.create({profile:false,formContainer:false,userId:false,isTenantAdmin:false,initialize:function(profile,options){this.container=$("successStoryContainer");this.successStoryItems=$("successStoryItems");this.profile=profile;this.formContainer=this.container.down("div.successStoryFormContainer");this.parentObjectType=this.container.down("input.parentObjectType").value;this.parentObjectId=parseInt(this.container.down("input.parentObjectId").value,10);this.userId=
parseInt($F("BS_User_Id"),10);this.isTenantAdmin=$F("BS_TenantAdmin")==="1";this.noDataContainer=this.container.down("div.noData");this.successStoryFeed=new BrainstormJs.Controls.SuccessStoryFeed(this.container,{successStoryItems:this.successStoryItems,parentObjectType:this.parentObjectType,parentObjectId:this.parentObjectId,wireMenuItems:this.wireMenuItems.bind(this)});this.successStoryForm=new BrainstormJs.Forms.SuccessStoryForm(this.profile,{successStoryContainer:this,parentContainer:this.formContainer,
parentObjectType:this.parentObjectType,parentObjectId:this.parentObjectId,destroyOnClose:true,onCreate:this.storyCreated.bind(this)});this.wireAddLink($("linkAddSuccessStory"));this.wireAddLink($("linkWriteSuccessStory"));this.wireMenuItems()},wireAddLink:function(unboundOpenLink){unboundOpenLink.observe("click",function(e){this.successStoryForm.startCreate(e.element());e.stop()}.bind(this));this.successStoryForm.addOpenLink(unboundOpenLink)},wireMenuItems:function(){this.wireEditLinks();this.wireDeleteLinks()},
wireEditLinks:function(){var editLinks=[];if(this.isTenantAdmin)editLinks=this.container.select("div.successStory > div.successStoryWrapper > div.title > div.menu > a.editIcon");else editLinks=this.container.select("div.storyby-"+this.userId+" > div.successStoryWrapper > div.title > div.menu > a.editIcon");if(!this.fxOnEditSuccessStory)this.fxOnEditSuccessStory=function(e){this.onEdit(e.element());e.stop()}.bind(this);for(var i=0,j=editLinks.length;i<j;i++){var editLink=editLinks[i];editLink.observe("click",
this.fxOnEditSuccessStory);editLink.show()}},wireDeleteLinks:function(){var archiveLinks=[];if(this.isTenantAdmin)archiveLinks=this.container.select("div.successStory > div.successStoryWrapper > div.title > div.menu > a.archiveIcon");else archiveLinks=this.container.select("div.storyby-"+this.userId+" > div.successStoryWrapper > div.title > div.menu > a.archiveIcon");if(!this.fxOnArchiveSuccessStory)this.fxOnArchiveSuccessStory=function(e){this.onArchive(e.element());e.stop()}.bind(this);for(var i=
0,j=archiveLinks.length;i<j;i++){var archiveLink=archiveLinks[i];archiveLink.observe("click",this.fxOnArchiveSuccessStory);archiveLink.show()}},onEdit:function(editLink){var successStory=this.getSuccessStory(editLink);var successStoryWrapper=successStory.container.down("div.successStoryWrapper");var editFormContainer=successStory.container.down("div.editForm");if(!editFormContainer){editFormContainer=new Element("div",{"class":"editForm"});successStory.container.insert(editFormContainer)}var successStoryEditForm=
new BrainstormJs.Forms.SuccessStoryForm(this.profile,{successStoryContainer:this,parentContainer:successStory.container,replaceElement:successStoryWrapper,parentObjectType:this.parentObjectType,parentObjectId:this.parentObjectId,destroyOnClose:true,onEdit:this.storyEdited.bind(this)});successStoryEditForm.startEditing(successStory,editLink)},onArchive:function(archiveLink){var successStory=this.getSuccessStory(archiveLink);bsCommon.confirm({title:"Removal Confirmation",text:"Are you sure you would like to remove this success story?",
width:450,confirmText:"Yes, remove it!",cancelText:"No, keep it.",onConfirm:function(){this.commitArchiveStory(successStory)}.bind(this)})},commitArchiveStory:function(successStory){Brainstorm.Web.Services.Ajax.ArchiveSuccessStory(bsCommon.getRequestToken(),successStory.id,function(){this.afterArchiveStory(successStory)}.bind(this),bsCommon.ajaxCallError)},afterArchiveStory:function(successStory){Effect.BlindUp(successStory.container,{duration:0.5,afterFinish:function(){successStory.container.remove();
var successStories=this.successStoryItems.immediateDescendants();if(successStories&&successStories.length==0)this.noDataContainer.blindDown({duration:0.25})}.bind(this)})},storyEdited:function(){this.successStoryFeed.wireReadMoreLinks()},storyCreated:function(jsonObjectView){this.successStoryForm.closeForm();this.successStoryItems.insert({top:jsonObjectView.HTML});if(this.noDataContainer.style.display=="")this.noDataContainer.blindUp({duration:0.25});var newSuccessStory=this.successStoryItems.immediateDescendants().first();
this.wireEditLinks();this.wireDeleteLinks();this.successStoryFeed.wireReadMoreLinks();var highlightBodyFx=function(){new Effect.Highlight(newSuccessStory,{duration:1.3})};var displaySuccessStoryFx=function(){newSuccessStory.appear({duration:0.5,afterFinish:function(){highlightBodyFx()}})};displaySuccessStoryFx()},getSuccessStory:function(menuLink){var successStoryDiv=menuLink.up("div.successStory");var successStoryId=bsCommon.parseObjectGuid(successStoryDiv).id;var successStory={id:successStoryId,
container:successStoryDiv};return successStory}});
BrainstormJs.Controls.SuccessStoryFeed=Class.create({options:false,listType:false,contextId:false,earliestEventId:false,container:false,items:false,loadMoreArea:false,loadMoreLink:false,loadLessLink:false,spinner:false,wireMenuItems:false,numItemsToRemove:false,initialize:function(container,options){this.numItemsToRemove=1;this.options=options||{};this.container=$(container);if(this.options.successStoryItems)this.items=this.options.successStoryItems;else this.items=this.container.down("div.successStoryItems");
if(this.options.singleItem)this.wireReadMoreLinks();else{this.loadMoreArea=this.container.down("div.loadMoreArea");this.loadMoreLink=this.loadMoreArea.down("a.linkLoadMore");this.loadLessLink=null;if(this.options.parentObjectType)this.parentObjectType=this.options.parentObjectType;else this.parentObjectType=this.container.down("input.parentObjectType");if(this.options.parentObjectId)this.parentObjectId=this.options.parentObjectId;else this.parentObjectId=parseInt(this.container.down("input.parentObjectId").value,
10);if(this.options.wireMenuItems)this.wireMenuItems=options.wireMenuItems;this.spinner=this.loadMoreArea.down(".spinner");this.loadMoreLink.observe("click",function(e){this.showMore();e.stop()}.bind(this));this.refresh()}},showMore:function(){this.loadMoreLink.hide();if(this.loadLessLink)this.loadLessLink.hide();this.spinner.show();if(this.parentObjectType&&this.parentObjectId)Brainstorm.Web.Services.Ajax.LoadMoreSuccessStoriesFromObject(bsCommon.getRequestToken(),this.earliestEventId,this.parentObjectType,
this.parentObjectId,this.addNewItems.bind(this),bsCommon.ajaxCallError);else Brainstorm.Web.Services.Ajax.LoadMoreSuccessStories(bsCommon.getRequestToken(),this.earliestEventId,this.addNewItems.bind(this),bsCommon.ajaxCallError)},showLess:function(){this.loadMoreLink.hide();this.loadLessLink.hide();this.spinner.show();var tempContainer=new Element("div",{"class":"tempContainer"});var childElementsArr=this.items.childElements();var childElementCount=childElementsArr.length;var j=0;childElementsArr.reverse();
for(var i=0;i<this.numItemsToRemove&&i<childElementCount-1;i++)childElementsArr[i].wrap(tempContainer);Effect.BlindUp(tempContainer,{duration:0.5,afterFinish:function(){tempContainer.remove();this.refresh();this.spinner.hide();if(this.items.childElements().length>this.numItemsToRemove)this.loadLessLink.show();this.loadMoreLink.show()}.bind(this)})},addNewItems:function(newItems){if(!newItems){this.loadMoreArea.blindUp();return}var tempContainer=new Element("div",{"class":"tempContainer","style":"display:none;"});
tempContainer.insert(newItems);this.items.insert(tempContainer);tempContainer.blindDown({afterFinish:function(){this.items.insert(tempContainer.innerHTML);tempContainer.remove();bsCommon.scrollIfBelowFold(this.spinner,20,{afterFinish:function(){this.spinner.hide();if(!this.loadLessLink){this.loadLessLink=(new Element("a",{"class":"linkLoadLess","style":"display:visible;",href:"#"})).update("show less");this.loadMoreArea.insert(this.loadLessLink);this.loadLessLink.observe("click",function(e){this.showLess();
e.stop()}.bind(this))}this.loadLessLink.show();this.loadMoreLink.show();if(!this.refreshFx)this.refreshFx=this.refresh.bind(this);this.refreshFx.defer();if(this.wireMenuItems)this.wireMenuItems()}.bind(this)})}.bind(this)})},refresh:function(){var hasEvents=this.findEarliestId();if(hasEvents){this.wireReadMoreLinks();Effect.BlindDown(this.loadMoreArea,{duration:0.5})}},findEarliestId:function(){if(this.items!=null){var lastListItem=this.items.immediateDescendants().last();if(lastListItem){this.earliestEventId=
parseInt(lastListItem.id.split("_").last(),10);return true}}return false},wireReadMoreLinks:function(){if(!this.fxOnReadMore)this.fxOnReadMore=function(e){this.readMore(e.element());e.stop()}.bind(this);if(!this.fxOnReadLess)this.fxOnReadLess=function(e){this.readLess(e.element());e.stop()}.bind(this);var items=this.items.immediateDescendants();for(var i=0;i<items.length;++i){var successStoryWrapper=items[i].down("div.successStoryWrapper");var linkReadMore=items[i].down("a.linkReadMore");var linkReadLess=
items[i].down("a.linkReadLess");var fade=items[i].down("div.fade");if(successStoryWrapper.scrollHeight>300){linkReadMore.observe("click",this.fxOnReadMore);linkReadLess.observe("click",this.fxOnReadLess);linkReadMore.show();fade.addClassName("fadeEffect");linkReadLess.hide()}else{linkReadMore.hide();linkReadLess.hide()}}},readMore:function(linkReadMore){bsCommon.scrollTo(linkReadMore,{offset:-100});var successStoryWrapper=linkReadMore.up().previous();successStoryWrapper.removeClassName("foldedSuccessStory");
var fade=successStoryWrapper.down("div.fade");fade.removeClassName("fadeEffect");linkReadMore.hide();linkReadMore.next().show()},readLess:function(linkReadLess){var successStoryWrapper=linkReadLess.up().previous();bsCommon.scrollTo(successStoryWrapper,{offset:-20});successStoryWrapper.addClassName("foldedSuccessStory");var fade=successStoryWrapper.down("div.fade");fade.addClassName("fadeEffect");linkReadLess.hide();linkReadLess.previous().show()}});
BrainstormJs.Controls.TagUpdater=Class.create({profile:false,container:false,refreshArea:false,tagForm:false,tagCategory:false,cloudContainer:false,openLink:false,contentFetchMethod:false,onContentPlaced:false,preambleText:false,activeTags:false,onTagFormClose:false,initialize:function(options){this.container=$(options.sectionId);if(!this.container)return;this.refreshArea=this.container.down("div.refreshArea");this.tagCategory=options.tagCategory;this.contentFetchMethod=options.contentFetchMethod||
false;this.cloudContainer=$(options.cloudContainer);this.editTitle=options.editTitle||"Edit tags";this.preambleText=options.preambleText||false;this.onTagFormClose=options.onTagFormClose||false;this.profile=options.profile||false;this.onContentPlaced=options.onContentPlaced;this.openLink=this.container.down("a.updateTags");if(this.openLink){this.openLink.observe("click",function(e){this.startUpdate();e.stop()}.bind(this));this.openLink.blindDown({duration:0.5})}},startUpdate:function(){if(!this.tagForm){var formContainer=
this.container.down("div.tagUpdaterFormContainer");var activeTagWrapper=formContainer.down(".activeTagValues");if(activeTagWrapper)this.activeTags=activeTagWrapper.innerHTML.split(",");this.tagForm=new BrainstormJs.Forms.TagForm(this.profile,this.tagCategory,{parentContainer:formContainer,cloudContainer:this.cloudContainer,openLinks:this.openLink?[this.openLink]:false,bindOpenLinks:false,onTagsChanged:this.onTagsChanged.bind(this),editTitle:this.editTitle,preambleText:this.preambleText,activeTags:this.activeTags,
beforeShow:this.onFormShow.bind(this),afterClose:this.onFormClose.bind(this)})}this.tagForm.startEditing()},onFormShow:function(){var currentInterests=this.refreshArea.down(".currentInterests");if(currentInterests)currentInterests.hide()},onFormClose:function(){var currentInterests=this.refreshArea.down(".currentInterests");if(currentInterests&&currentInterests.down(".interest"))currentInterests.show();if(this.onTagFormClose)this.onTagFormClose()},onTagsChanged:function(){this.contentFetchMethod(this.newContentLoaded.bind(this),
bsCommon.ajaxCallError)},newContentLoaded:function(domElement){if(domElement.HTML&&domElement.HTML.length>0){var noData=this.refreshArea.down("div.noData");if(noData)noData.blindUp({duration:0.5,afterFinish:function(){this.insertContent(this.refreshArea,domElement,true)}.bind(this)});else this.insertContent(this.refreshArea,domElement,false)}else this.refreshArea.innerHTML='<div class="noData">There doesn\'t seem to be anything here ... perhaps you can try to add more tags?</div>'},insertContent:function(refreshArea,
domElement,blind){refreshArea.innerHTML=domElement.HTML;if(!this.refreshFx)this.refreshFx=function(){this.refreshContent(domElement.Id,blind)}.bind(this);this.refreshFx.defer()},refreshContent:function(newContentId,blind){var newContent=$(newContentId);if(newContent){newContent[blind?"blindDown":"appear"]();if(this.onContentPlaced)this.onContentPlaced(newContent)}}});
BrainstormJs.Controls.Comments.CommentEntry=Class.create({container:false,options:false,parentObject:false,wiredUp:false,userPhoto:false,inputDiv:false,textarea:false,wysiwyg:false,defaultText:false,buttonsDiv:false,submitButton:false,validator:false,cancelButton:false,spinner:false,fxWireControl:false,nonEmptyHtmlThreshold:40,initialize:function(options){this.options=options;this.container=options.container;this.parentObject=options.parentObject;if(!this.parentObject)this.parentObject=BrainstormJs.Controls.Comments.CommentUtils.getParentObject(this.container);
this.userPhoto=this.container.down("img.userPhoto");this.inputDiv=this.container.down("div.input");this.textarea=this.inputDiv.down("textarea");this.defaultText=this.textarea.title;this.textarea.disabled=false;this.textarea.tabIndex=BrainstormForms.getTabIndex();BrainstormForms.getTabIndex();BrainstormForms.getTabIndex();this.wysiwyg=new BrainstormJs.Controls.WysiwygTextarea(this.textarea,{lazyWire:true,autoExpand:true,onFocus:this._onInputFocus.bind(this),onBlur:this._onInputBlur.bind(this),defaultText:this.defaultText});
if(this.options.trigger)this.options.trigger.observe("click",function(e){e.stop();if(this.options.onTrigger)this.options.onTrigger(e.element());var wysiwyg=this.wysiwyg;var container=this.container;window.setTimeout(function(){wysiwyg._onFocus();bsCommon.scrollIfBelowFold(container,125)},1)}.bind(this))},show:function(focus){var fxAfterFinish=function(){};if(focus)fxAfterFinish=function(){this.wysiwyg._onFocus();bsCommon.scrollIfBelowFold(this.container,125)}.bind(this);if(!this.container.visible())this.container.appear({duration:0.5,
afterFinish:fxAfterFinish});else fxAfterFinish()},hide:function(){this.container.fade({duration:0.49})},_wireControl:function(){if(!this.wiredUp){this.buttonsDiv=this.inputDiv.down("div.buttons");this.submitButton=this.buttonsDiv.down(".submitButton");this.validator=this.buttonsDiv.down("span.validator");this.cancelButton=this.buttonsDiv.down(".cancelButton");this.spinner=this.buttonsDiv.down("img.progressSpinner");this.submitButton.observe("click",function(e){this._submitComment();e.stop()}.bind(this));
this.cancelButton.observe("click",function(e){this._cancelComment();e.stop()}.bind(this));this.wysiwyg.setTabIndex(this.textarea.tabIndex);this.submitButton.tabIndex=this.textarea.tabIndex+1;this.cancelButton.tabIndex=this.textarea.tabIndex+2;this.wiredUp=true}},_onInputFocus:function(){this._wireControl();this._changePhoto(this.userPhoto.readAttribute("data-small-src"),true);if(!this.buttonsDiv.visible())this.buttonsDiv.show()},_onInputBlur:function(changed){if(changed){this._changePhoto(this.userPhoto.readAttribute("data-icon-src"),
false);if(this.buttonsDiv.visible())this.buttonsDiv.hide()}},_changePhoto:function(newSrc,zoom){if(this.userPhoto.src!=newSrc){this.userPhoto.src=newSrc;this.userPhoto.hide();if(zoom)this.container.addClassName("expandedEntry");else this.container.removeClassName("expandedEntry");this.userPhoto.show()}},_submitComment:function(){this.validator.hide();BrainstormJs.Utils.disableTinyMceSpellChecking();var commentBody=this.wysiwyg.getContent();var commentBodyText=commentBody.stripTags().strip();if(this.validator&&
commentBodyText==""&&commentBody.length<this.nonEmptyHtmlThreshold){this.validator.show();this.validator.pulsate({duration:1.5,queue:"top"});return}this.submitButton.disabled=true;this.cancelButton.hide();this.spinner.show();Brainstorm.Web.Services.Ajax.AddCommentToObject(bsCommon.getRequestToken(),this.parentObject.type,this.parentObject.id,commentBody,this.parentObject.isPrivate,this._onSubmitSuccess.bind(this),this._onSubmitError.bind(this))},_onSubmitSuccess:function(commentDomElement){if(this.options.onCommentAdded)this.options.onCommentAdded(commentDomElement,
this.options.commentContainer);this._close()},_onSubmitError:function(error){this.submitButton.disabled=false;this.cancelButton.show();this.spinner.hide();bsCommon.alert("Oops, there was an error while trying to submit your comment. Please try again.");BrainstormJs.LogScriptError(error)},_cancelComment:function(){var htmlContent=this.wysiwyg.getContent();var textContent=htmlContent.stripTags().strip();if(textContent!=""&&textContent!=this.defaultText||htmlContent.length>=this.nonEmptyHtmlThreshold)bsCommon.confirm({title:"Confirmation",
text:"Woah, that's starting to look like a really great comment!<br/>Are you sure you would like to cancel?",width:450,confirmText:"Yes, cancel it!",cancelText:"No, let me keep typing",onConfirm:this._forceCancel.bind(this)});else this._forceCancel()},_forceCancel:function(){this._close();if(this.options.afterCancel)this.options.afterCancel(this.container)},_close:function(){this.wysiwyg.toggleOff();this._changePhoto(this.userPhoto.readAttribute("data-icon-src"),false);if(this.buttonsDiv.visible())this.buttonsDiv.hide();
this.submitButton.disabled=false;this.validator.hide();this.cancelButton.show();this.spinner.hide()}});
BrainstormJs.Controls.Comments.CommentThread=Class.create({container:false,options:false,parentObject:false,threadScope:false,userId:false,isTenantAdmin:false,toggle:false,commentCount:false,commentCountSpan:false,addLinks:false,addLinkBottom:false,noCommentsDiv:false,lazy:false,lazyPane:false,loaded:false,commentContainer:false,formContainer:false,commentEntry:false,fxOnCommentAdded:false,fxOnEditComment:false,initialize:function(container,options){this.container=container;this.options=options;if(!this.container){console.error("Could not find container for comment thread.");
return}this.parentObject=BrainstormJs.Controls.Comments.CommentUtils.getParentObject(container);this.threadScope=parseInt(container.readAttribute("data-scope"),10);this.userId=parseInt($F("BS_User_Id"),10);this.isTenantAdmin=$F("BS_TenantAdmin")==="1";this.commentCount=parseInt(container.readAttribute("data-comment-count"),10);this.toggle=this.container.down("a.toggle");this.addLinks=this.container.select("a.addComment");this.addLinkBottom=this.container.down("a.addCommentBottom");this.noCommentsDiv=
this.container.down(".noComments");this.commentContainer=this.container.down("div.commentContainer");this.formContainer=this.commentContainer.next("div.formContainer");this.loaded=this.commentCount==0;this.lazy=container.hasClassName("lazy");if(this.lazy){var lazyCommentPane=this.container.down("div.lazyCommentPane");this.lazyPane=new BrainstormJs.Controls.AjaxContentPane(lazyCommentPane)}if(this.toggle){this.toggle.observe("click",function(e){this.toggleComments();e.stop()}.bind(this));this.commentCountSpan=
this.toggle.down(".commentCount");this.commentCount=parseInt(this.commentCountSpan.innerHTML.strip())}if(this.addLinks){var fxStartNewComment=function(e){this.startNewComment(e.element());e.stop()}.bind(this);for(var i=0,j=this.addLinks.length;i<j;i++)this.addLinks[i].observe("click",fxStartNewComment)}this.fxOnCommentAdded=this.onCommentAdded.bind(this);var commentEntryDiv=this.commentContainer.next("div.commentEntry");if(commentEntryDiv)this.commentEntry=new BrainstormJs.Controls.Comments.CommentEntry({parentObject:this.parentObject,
container:commentEntryDiv,commentContainer:this.commentContainer,onCommentAdded:this.fxOnCommentAdded});this._wireReplyControls();if(!this.lazy){this._wireEditLinks();this._wireLikeLinks();this._wireUnlikeLinks()}},toggleComments:function(){if(this.commentContainer.visible()){this.hideComments();this.hideCommentEntry();this.toggle.addClassName("collapsed")}else{this.showComments(this.fxShowCommentEntry);this.showCommentEntry(false);this.toggle.removeClassName("collapsed")}},showComments:function(afterFinish){if(this.lazy&&
!this.loaded){this.commentContainer.show();this.lazyPane.startLoading({dataMethod:this.loadComments.bind(this),afterContentVisible:afterFinish})}else if(!this.commentContainer.visible())this.commentContainer.appear({duration:0.5,afterFinish:afterFinish});else if(afterFinish)afterFinish()},hideComments:function(afterFinish){if(this.commentContainer.visible())this.commentContainer.fade({duration:0.5,afterFinish:afterFinish})},loadComments:function(){Brainstorm.Web.Services.Ajax.GetCommentThread(this.parentObject.type,
this.parentObject.id,this.parentObject.isPrivate,this.threadScope,this.onCommentsLoaded.bind(this),this.onLoadError.bind(this))},onCommentsLoaded:function(jsonCommentThread){this.lazyPane.insertContent(jsonCommentThread.HTML,{onContentReady:this.initComments.bind(this)});this.updateCommentCount(jsonCommentThread.CommentCount)},onLoadError:function(error){bsCommon.alert("Oops, there was an issue trying to load those comments. Please try again.");BrainstormJs.LogScriptError(error)},initComments:function(){this._wireReplyControls();
this._wireEditLinks();this._wireLikeLinks();this._wireUnlikeLinks();this.loaded=true;this.lazyPane.showContent({fadeTransition:true});if(this.addLinkBottom&&!this.addLinkBottom.visible())this.addLinkBottom.appear()},updateCommentCount:function(newCount){if(this.commentCountSpan&&this.commentCount!=newCount){this.commentCountSpan.innerHTML=newCount;new Effect.Highlight(this.commentCountSpan,{delay:0.5})}},increaseCommentCount:function(){var currentCount=this.toggle.down(".commentCount");if(currentCount){var newCount=
parseInt(currentCount.innerHTML.strip(),10)+1;this.updateCommentCount(newCount)}},startNewComment:function(linkClicked){if(linkClicked.hasClassName("inactiveOpenLink")){Effect.Shake(linkClicked,{distance:3});return}this.toggle.removeClassName("collapsed");this.showComments(function(){this.showCommentEntry(true)}.bind(this))},showCommentEntry:function(focus){this.commentEntry.show(focus)},hideCommentEntry:function(){this.commentEntry.hide()},onCommentAdded:function(jsonDomElement,commentContainer){BrainstormJs.Controls.Comments.CommentUtils.addNewComment({jsonCommentElement:jsonDomElement,
commentContainer:commentContainer,scrollToComment:true,afterFinish:this.afterCommentAdded.bind(this)});if(commentContainer.hasClassName("repliesContainer"))commentContainer.addClassName("hasReplies")},afterCommentAdded:function(newCommentDiv){if(this.noCommentsDiv&&this.noCommentsDiv.visible())if(this.lazy)this.noCommentsDiv.fade({duration:0.5});else this.noCommentsDiv.blindUp({duration:0.5});this._wireReplyControls();this._wireEditLinks(newCommentDiv);this._wireLikeLinks(newCommentDiv);this._wireUnlikeLinks();
this.toggle.show();this.toggle.removeClassName("collapsed");this.increaseCommentCount()},_wireReplyControls:function(){var commentReplyControls=this.commentContainer.select("div.comment div.commentReplies div.unwiredCommentEntry");for(var i=0,j=commentReplyControls.length;i<j;i++){var container=commentReplyControls[i];var repliesDiv=container.up("div.commentReplies");var commentFooter=repliesDiv.previous("div.innerBox").down("div.footer");var replyLink=commentFooter.down("a.reply");if(replyLink&&
!this.fxOnReply)this.fxOnReply=this._onReply.bind(this);if(replyLink&&!repliesDiv.hasClassName("hasReplies")&&!this.fxOnCancelReply)this.fxOnCancelReply=this._onCancelReply.bind(this);var replyCommentEntry=new BrainstormJs.Controls.Comments.CommentEntry({container:container,commentContainer:container.previous("div.repliesContainer"),trigger:replyLink,onTrigger:this.fxOnReply,onCommentAdded:this.fxOnCommentAdded,afterCancel:this.fxOnCancelReply});container.removeClassName("unwiredCommentEntry")}},
_onReply:function(linkClicked){var repliesDiv=linkClicked.up("div.innerBox").next("div.commentReplies");if(!repliesDiv)return;if(!repliesDiv.visible()){var footer=linkClicked.up("div.footer");repliesDiv.show();footer.hide()}},_onCancelReply:function(commentEntryDiv){var repliesDiv=commentEntryDiv.up("div.commentReplies");if(repliesDiv&&!repliesDiv.down("div.repliesContainer").hasClassName("hasReplies")){var footerDiv=repliesDiv.previous("div.innerBox").down("div.footer");if(footerDiv){footerDiv.blindDown({duration:0.5});
repliesDiv.blindUp({duration:0.5})}}},_wireEditLinks:function(newCommentDiv){var editLinks=[];if(newCommentDiv)editLinks=newCommentDiv.select("a.editLink");else if(this.isTenantAdmin)editLinks=this.commentContainer.select("div.comment a.editLink");else editLinks=this.commentContainer.select("div.commentby-"+this.userId+" > div.innerBox > div.header > a.editLink");if(!this.fxOnEditComment)this.fxOnEditComment=function(e){this._onEdit(e.element());e.stop()}.bind(this);for(var i=0,j=editLinks.length;i<
j;i++){var editLink=editLinks[i];if(editLink.visible())continue;editLink.observe("click",this.fxOnEditComment);editLink.show()}},_onEdit:function(editLink){var commentDiv=editLink.up("div.comment");var bodyWrapper=commentDiv.down("div.innerBox > div.commentBody");var commentBody=bodyWrapper.down("> div.data-Body");var editFormContainer=bodyWrapper.down("> div.editForm");if(!editFormContainer){editFormContainer=new Element("div",{"class":"editForm"});bodyWrapper.insert(editFormContainer)}var commentForm=
new BrainstormJs.Forms.CommentForm({destroyOnClose:true,replaceElement:commentBody,parentContainer:editFormContainer,openLinks:[editLink],bindOpenLinks:false,editTitle:"Edit comment"});var commentId=bsCommon.parseObjectGuid(commentDiv).id;var comment={id:commentId,container:commentDiv};commentForm.startEditing(comment,editLink)},_wireLikeLinks:function(newCommentDiv){var likeLinks=[];if(newCommentDiv)likeLinks=newCommentDiv.select("a.likeButton");else likeLinks=this.commentContainer.select("div.comment > div.innerBox > div.footer > div.likes > a.likeButton");
if(!this.fxOnLikeComment)this.fxOnLikeComment=function(e){this._onLike(e.element());e.stop()}.bind(this);for(var i=0,j=likeLinks.length;i<j;i++){var likeLink=likeLinks[i];likeLink.observe("click",this.fxOnLikeComment)}},_onLike:function(likeLink){var commentDiv=likeLink.up("div.comment");var commentId=bsCommon.parseObjectGuid(commentDiv).id;Brainstorm.Web.Services.Ajax.LikeComment(commentId,this._updateLikeElements.bind(this),this._onLikeError.bind(this),commentDiv)},_onLikeError:function(like){bsCommon.alert("Oops, there was an error while trying to mark this comment as helpful. Please try again.");
BrainstormJs.LogScriptError(error)},_wireUnlikeLinks:function(){var unlikeLinks=this.commentContainer.select("div.comment > div.innerBox > div.footer > div.likes > a.unwiredUndoButton");if(!this.fxOnUnlikeComment)this.fxOnUnlikeComment=function(e){this._onUnlike(e.element());e.stop()}.bind(this);for(var i=0,j=unlikeLinks.length;i<j;i++){var unlikeLink=unlikeLinks[i];unlikeLink.observe("click",this.fxOnUnlikeComment);unlikeLink.removeClassName("unwiredUndoButton")}},_onUnlike:function(undoLink){var commentDiv=
undoLink.up("div.comment");var commentId=bsCommon.parseObjectGuid(commentDiv).id;Brainstorm.Web.Services.Ajax.UnlikeComment(commentId,this._updateLikeElements.bind(this),this._onUnlikeError.bind(this),commentDiv)},_onUnlikeError:function(){bsCommon.alert("Oops, there was an error while trying to perform the undo operation. Please try again.");BrainstormJs.LogScriptError(error)},_updateLikeElements:function(jsonComment,commentDiv){var likes=commentDiv.down("div.likes");var noLikesArea=likes.down(".noLikes");
var hasLikesArea=noLikesArea.next(".hasLikes");var you=hasLikesArea.down(".selfLike");var and=you.next(".and");var othersLike=and.next(".othersLike");var likesByOthersCount=othersLike.down(".count");var other=likesByOthersCount.next(".other");var person=other.next(".singular");var people=person.next(".plural");var didYou=hasLikesArea.next(".didYou");var likeButton=didYou.next(".likeButton");var undoButton=likeButton.next(".undoButton");var likedByBoth=jsonComment.LikedByUser&&jsonComment.LikesByOthers>
0;var likedOnlyByOthers=!jsonComment.LikedByUser&&jsonComment.LikesByOthers>0;likesByOthersCount.innerHTML=jsonComment.LikesByOthers;noLikesArea[jsonComment.LikeCount==0?"show":"hide"]();hasLikesArea[jsonComment.LikeCount>0?"show":"hide"]();you[jsonComment.LikedByUser?"show":"hide"]();and[likedByBoth?"show":"hide"]();othersLike[jsonComment.LikesByOthers>0?"show":"hide"]();other[likedByBoth?"show":"hide"]();person[jsonComment.LikesByOthers==1?"show":"hide"]();people[jsonComment.LikesByOthers!=1?"show":
"hide"]();didYou[likedOnlyByOthers?"show":"hide"]();likeButton[!jsonComment.LikedByUser?"show":"hide"]();undoButton[jsonComment.LikedByUser?"show":"hide"]();if(!undoButton.hasClassName("prewiredUndoButton")){undoButton.observe("click",this.fxOnUnlikeComment);undoButton.addClassName("prewiredUndoButton")}if(jsonComment.LikeCount>=2)commentDiv.addClassName("helpfulComment");else commentDiv.removeClassName("helpfulComment");new Effect.Highlight(hasLikesArea.visible()?hasLikesArea:noLikesArea,{duration:0.75,
startcolor:"#ffff99",endcolor:"#ffffff",restorecolor:"#ffffff"})}});
BrainstormJs.Controls.Comments.CommentUtils={wireComments:function(){var commentThreads=$$("div.unboundCommentThread");for(var i=0,j=commentThreads.length;i<j;i++){var threadDiv=commentThreads[i];var threadObj=new BrainstormJs.Controls.Comments.CommentThread(threadDiv);threadDiv.removeClassName("unboundCommentThread")}},addNewComment:function(options){var noDataDiv=options.commentContainer.down("div.noData");if(noDataDiv)noDataDiv.blindUp({duration:0.25,afterFinish:function(){noDataDiv.remove()}});
options.commentContainer.insert(options.jsonCommentElement.HTML);if(!options.commentContainer.visible())options.commentContainer.show();var comments=options.commentContainer.select("div.comment");var newComment=comments[comments.length-1];var highlightBodyFx=function(){var body=newComment.down("div.commentBody");new Effect.Highlight(body,{duration:1.3})};var displayCommentFx=function(){newComment.appear({duration:0.5,afterFinish:function(){if(options.scrollToComment)bsCommon.scrollIfBelowFold(newComment,
10,{afterFinish:highlightBodyFx});else highlightBodyFx();if(options.afterFinish)options.afterFinish(newComment)}})};displayCommentFx()},editComment:function(linkClicked){var commentDiv=linkClicked.up("div.comment");var commentBody=commentDiv.down("div.commentBody div.data-Body");var commentForm=new BrainstormJs.Forms.CommentForm(this,{destroyOnClose:true,replaceElement:commentBody,openLinks:[linkClicked],bindOpenLinks:false,editTitle:"Edit comment"});var commentDiv=linkClicked.up("div.comment");var commentId=
parseInt(commentDiv.readAttribute("data-id"),10);var comment={id:commentId,container:commentDiv};commentForm.startEditing(comment,linkClicked)},getParentObject:function(element){var ParentTypeAttrib="data-parent-type";var ParentIdAttrib="data-parent-id";var IsPrivateAttrib="data-private";var ReplyContainerAttrib="data-reply-container";if(!element||!element.hasAttribute(ParentTypeAttrib)||!element.hasAttribute(ParentIdAttrib)){console.error("Cannot find comment context for element: %o",element);return}var parentType=
element.readAttribute(ParentTypeAttrib);var parentId=parseInt(element.readAttribute(ParentIdAttrib),10);var isPrivate=element.hasAttribute(IsPrivateAttrib)?element.readAttribute(IsPrivateAttrib)=="1":false;var replyContainer=false;if(element.hasAttribute(ReplyContainerAttrib))replyContainer=$(element.readAttribute(ReplyContainerAttrib));return{type:parentType,id:parentId,isPrivate:isPrivate,replyContainer:replyContainer}}};
BrainstormJs.Forms.Fields.DropDownList=Class.create(BrainstormJs.Forms.Fields.BaseField,{select:false,addBlank:false,blankLabel:false,defaultValue:false,initialize:function($super,options){options=options||{};options.cssClass="dropdownlist";$super(options);if(options.addBlank!==undefined){this.addBlank=options.addBlank;this.blankLabel=options.blankLabel||""}this.defaultValue=options.defaultValue||false},render:function($super,renderOptions){this.select=new Element("select",{"class":"dropdownlist",
"tabindex":this.tabIndex});this.select.identify();if(this.required&&this.addBlank)this.select.addClassName("validate-selection");if(this.addBlank)this.select.insert((new Element("option",{"value":""})).update(this.blankLabel));if(this.options.choices)for(var i=0,j=this.options.choices.length;i<j;i++){var choice=this.options.choices[i];var option;if(this.defaultValue!=false&&choice.value==this.defaultValue)option=(new Element("option",{"value":choice.value,"selected":"selected"})).update(choice.text);
else option=(new Element("option",{"value":choice.value})).update(choice.text);this.select.insert(option)}if(renderOptions&&renderOptions.controlOnly)return this.select;else return $super([this.select])},afterRender:function(){},hasValue:function(){return this.getValue()!=""},getValue:function(){return this.select.options[this.select.selectedIndex].value},setIndex:function(index){if(bsCommon.isInteger(index))this.select.selectedIndex=index},setValue:function(value){for(var i=0,j=this.select.options.length;i<
j;i++){var option=this.select.options[i];if(option.value==value){option.selected=true;return}}for(var i=0,j=this.select.options.length;i<j;i++){var option=this.select.options[i];if(option.text.toString()==value.toString()){option.selected=true;return}}},removeOptionWithValue:function(value){for(var i=0,j=this.select.options.length;i<j;i++){var option=this.select.options[i];if(option.value==value){this.select.remove(i);return true}}return false},isEmpty:function(){return this.select.options.length==
1&&this.select.options[0].value.strip()==""},clear:function(){if(this.options.selectedValue)this.setValue(this.options.selectedValue);else this.setIndex(0)},focus:function(){this.select.focus()},getElement:function(){return this.select}});
BrainstormJs.Controls.CustomFields.Forms.BaseCustomFieldForm=Class.create(BrainstormJs.Forms.BaseForm,{customField:false,fieldName:false,fieldVisibility:false,initialize:function($super,customField,options){this.customField=customField;options=options||{};options.editTitle=options.editTitle||"Edit field";options.submitButtonTitle="Save";$super({},options)},createFields:function($super){this.fieldName=new BrainstormJs.Forms.Fields.TextBox({title:this.getNameFieldLabel(),maxLength:256,required:true,
help:this.getNameFieldHelp(),dataSelector:".data-Name"});this.registerField(this.fieldName);this.registerCustomFields();if(this.customField.isVisibilityEditable()){var parentName=this.customField.getParentTypeName().toLowerCase();this.fieldVisibility=new BrainstormJs.Forms.Fields.DropDownList({title:"Visibility",required:true,choices:[{text:"Only "+parentName+" team members",value:Brainstorm.Model.Enums.CustomFieldVisibility.PrivateTeam},{text:"Everyone",value:Brainstorm.Model.Enums.CustomFieldVisibility.PublicReadOnly}],
addBlank:false,dataSelector:".data-Visibility"});this.registerField(this.fieldVisibility)}},createNewObject:function($super){},startEditing:function(){this.editingExisting=true;this.showForm({afterFinish:function(){this.loadObjectValues(this.customField.getContainer())}.bind(this),editMode:true,blindDuration:0})},saveEditedObject:function(){},customFieldUpdated:function(jsonCustomField){if(this.customField.validateSavedValue(jsonCustomField))this.customField.updateAfterSave(jsonCustomField)},afterCancel:function(){this.customField.stopEditing()},
getCustomField:function(){return this.customField},getVisibilityValue:function(){if(this.fieldVisibility)return this.fieldVisibility.getValue();return null},isSubmissionField:function(){return this.customField.getFieldCategory()==Brainstorm.Model.Enums.CustomFieldCategory.Submission},getNameFieldLabel:function(){if(this.isSubmissionField())return"Question for participant to answer";return"Name"},getNameFieldHelp:function(){if(this.isSubmissionField()){var parentName=this.customField.getParentTypeName().toLowerCase();
return"The question that must be answered by users when they submit ideas to this "+parentName+"."}return"This is the name of the field that will appear to users."},registerCustomFields:function(){}});
BrainstormJs.Controls.CustomFields.Forms.CustomDropDownChoices=Class.create(BrainstormJs.Forms.Fields.BaseField,{wrapper:false,errorMessage:false,renameWarning:false,choicesDiv:false,addLink:false,customField:false,choiceCount:0,deletedClass:"deletedChoice",justAddedClass:"freshChoice",fxStartDeleteChoice:false,fxStartRenameChoice:false,initialize:function($super,options){options=options||{};options.cssClass="customChoices";$super(options)},render:function($super){this.wrapper=new Element("div",{"class":"choiceWrapper"});
this.renameWarning=(new Element("div",{"class":"renameWarning"})).update("<strong>Caution:</strong> careful if you're changing the meaning of the choice.  If you rename a choice, it will apply to every object that has this choice selected.");this.renameWarning.hide();this.wrapper.insert(this.renameWarning);this.choicesDiv=new Element("div",{"class":"choices"});this.wrapper.insert(this.choicesDiv);this.addLink=(new Element("a",{"class":"addChoice","href":"#","tabindex":this.tabIndex})).update("Add a new drop down choice");
this.addLink.observe("click",function(e){this.startAddChoice();e.stop()}.bind(this));this.wrapper.insert(this.addLink);return $super([this.wrapper])},afterRender:function(){},beforeFormShow:function(){this.renameWarning.hide();this.customField=this.form.getCustomField();var choices=this.customField.getChoices();if(choices){this.choicesDiv.innerHTML="";for(var i=0,j=choices.length;i<j;i++){var choice=choices[i];this.addChoiceRow(choice.Id,choice.RawLabel,false,choice.JustAutoCreated)}this.refreshSortable()}},
startAddChoice:function(refreshSortable){if(bsCommon.shakeIfDisabled(this.addLink))return;this.addChoiceRow(0,"Untitled Choice",true)},addChoiceRow:function(id,label,isNew,autoCreated){if(!this.fxStartRenameChoice){this.fxStartDeleteChoice=function(e){this.startDeleteChoice(e.element(),e.shiftKey);e.stop()}.bind(this);this.fxStartRenameChoice=function(e){this.startRenameChoice(e.element());e.stop()}.bind(this)}var choiceDiv=new Element("div",{"class":"customChoice clearfix"});var idElem=new Element("input",
{"type":"hidden","class":"data-Id","value":id});var fieldLabel=(new Element("span",{"class":"staticLabel"})).update(label);var textbox=new Element("input",{"type":"text","class":"data-Label","maxlength":60,"tabindex":this.tabIndex,"value":label});var editLink=new Element("a",{"class":"edit","href":"#"});var reorderIcon=new Element("div",{"class":"reorder"});var deleteLink=new Element("a",{"class":"delete","href":"#"});editLink.observe("click",this.fxStartRenameChoice);deleteLink.observe("click",this.fxStartDeleteChoice);
choiceDiv.insert(idElem);choiceDiv.insert(fieldLabel);choiceDiv.insert(textbox);choiceDiv.insert(editLink);choiceDiv.insert(reorderIcon);choiceDiv.insert(deleteLink);if(isNew||autoCreated){fieldLabel.hide();editLink.hide()}else textbox.hide();if(isNew&&id===0){choiceDiv.addClassName(this.justAddedClass);choiceDiv.hide()}this.choicesDiv.insert(choiceDiv);this.choiceCount++;if(isNew){choiceDiv.blindDown({duration:0.5,afterFinish:function(){textbox.focus();textbox.select()}});this.refreshSortable()}},
startRenameChoice:function(editLink){var choiceDiv=editLink.up("div.customChoice");var textbox=choiceDiv.down("input.data-Label");var label=choiceDiv.down("span.staticLabel");label.hide();editLink.hide();textbox.show();if(!this.renameWarning.visible())this.renameWarning.blindDown({duration:1});textbox.focus();textbox.select()},showError:function(message){if(!this.errorMessage){this.errorMessage=(new Element("div",{"class":"renameWarning"})).update(message);this.errorMessage.hide();this.wrapper.insert({top:this.errorMessage})}else this.errorMessage.innerHTML=
message;var errorMessage=this.errorMessage;errorMessage.blindDown({duration:1,afterFinish:function(){errorMessage.fade({duration:0.5,delay:5})}})},startDeleteChoice:function(linkClicked,noConfirm){if(this.choiceCount==1){this.showError("You cannot remove the last choice. Please add another choice before removing this one.");return}var choiceDiv=linkClicked.up("div.customChoice");if(choiceDiv.hasClassName(this.justAddedClass)){choiceDiv.blindUp({duration:0.5,afterFinish:function(){choiceDiv.remove()}});
this.choiceCount--}else if(noConfirm)this.markChoiceDeleted(choiceDiv);else bsCommon.confirm({title:"Removal Confirmation",text:"Are you sure you want to remove this choice? Removing it will DELETE the data associated with the choice from each idea it touches.",width:450,confirmText:"Yes, remove it!",cancelText:"No, keep it.",onConfirm:function(){this.markChoiceDeleted(choiceDiv)}.bind(this)})},markChoiceDeleted:function(choiceDiv){choiceDiv.addClassName(this.deletedClass);choiceDiv.fade();this.choiceCount--},
refreshSortable:function(){Sortable.create(this.choicesDiv,{dropOnEmpty:false,tag:"div",only:"customChoice",handle:"reorder",constraint:"vertical",scroll:window})},hasValue:function(){return true},getValue:function(){var choiceDivs=this.choicesDiv.select("div.customChoice");var visibleChoices=new Array;var removedChoices=new Array;for(var i=0,j=choiceDivs.length;i<j;i++){var choiceDiv=choiceDivs[i];var choiceId=parseInt(choiceDiv.down("input.data-Id").value,10);var choiceLabel=choiceDiv.down("input.data-Label").value;
var choice={Id:choiceId,Label:choiceLabel};if(choiceDiv.hasClassName(this.deletedClass))removedChoices.push(choice);else visibleChoices.push(choice)}return{visible:visibleChoices,removed:removedChoices}},getElement:function(){return false},disable:function(){},enable:function(){}});
BrainstormJs.Controls.CustomFields.Forms.CustomDropDownForm=Class.create(BrainstormJs.Controls.CustomFields.Forms.BaseCustomFieldForm,{fieldChoices:false,initialize:function($super,customField,options){options=options||{};options.editTitle=options.editTitle||"Edit drop down";$super(customField,options)},registerCustomFields:function(){this.fieldChoices=new BrainstormJs.Controls.CustomFields.Forms.CustomDropDownChoices({title:"Choices",help:"These are the choices that will appear to reviewers as they evaluate ideas.",
required:true});this.registerField(this.fieldChoices)},saveEditedObject:function(){var choices=this.fieldChoices.getValue();Brainstorm.Web.Services.Ajax.SaveCustomDropDownField(this.customField.getParentObjectType(),this.customField.getParentObjectId(),this.customField.getFieldId(),this.fieldName.getValue(),this.getVisibilityValue(),choices.visible,choices.removed,this.customFieldUpdated.bind(this),function(error){bsCommon.ajaxCallError(error,this.onSaveError)}.bind(this))},onSaveError:function(){},
customFieldUpdated:function($super,jsonCustomField){$super(jsonCustomField);this.customField.updateGlobalChoices(jsonCustomField.Choices)},beforeShow:function(){this.fieldChoices.beforeFormShow()}});
BrainstormJs.Controls.CustomFields.Forms.CustomTextFieldForm=Class.create(BrainstormJs.Controls.CustomFields.Forms.BaseCustomFieldForm,{fieldType:false,initialize:function($super,customField,options){options=options||{};options.editTitle=options.editTitle||"Edit text field";if(customField.getFieldCategory()==Brainstorm.Model.Enums.CustomFieldCategory.Submission)options.editTitle="Edit question";$super(customField,options)},registerCustomFields:function(){},saveEditedObject:function(){Brainstorm.Web.Services.Ajax.SaveCustomTextField(this.customField.getParentObjectType(),
this.customField.getParentObjectId(),this.customField.getFieldId(),this.fieldName.getValue(),this.getVisibilityValue(),this.customFieldUpdated.bind(this),bsCommon.ajaxCallError)}});
BrainstormJs.Controls.CustomFields.Forms.CustomRatingLabelsField=Class.create(BrainstormJs.Forms.Fields.BaseField,{wrapper:false,errorMessage:false,renameWarning:false,choicesDiv:false,addLink:false,customField:false,labelInputs:false,initialize:function($super,options){options=options||{};options.cssClass="ratingLabels";$super(options)},render:function($super){this.wrapper=new Element("div",{"class":"labelsWrapper"});this.labelInputs=[];var customFieldContainer=this.getForm().getCustomField().getContainer();
for(var i=1;i<=5;i++){var ratingLabel=new Element("div",{"class":"ratingLabel ratingLabel-"+i});var starBg=new Element("span",{"class":"small_stars_bg"});var starFg=new Element("span",{"class":"small_stars_fg small_stars_"+i+"_0"});var labelInput=new Element("input",{"type":"text","class":"validation-ignore","maxlength":200,"tabindex":this.tabIndex,"value":customFieldContainer.down("input.data-RatingLabel"+i).value,"placeholder":i==1?"Enter a meaning for this choice...":"..."});this.labelInputs.push(labelInput);
starBg.insert(starFg);ratingLabel.insert(starBg);ratingLabel.insert(labelInput);this.wrapper.insert(ratingLabel)}return $super([this.wrapper])},afterRender:function(){},hasValue:function(){return true},setValue:function(val){},getValue:function(){var labelValues=[];for(var i=0,j=this.labelInputs.length;i<j;i++)labelValues.push(this.labelInputs[i].value);return labelValues},getElement:function(){return false},disable:function(){},enable:function(){}});
BrainstormJs.Controls.CustomFields.Forms.CustomRatingFieldForm=Class.create(BrainstormJs.Controls.CustomFields.Forms.BaseCustomFieldForm,{labelsField:false,initialize:function($super,customField,options){options=options||{};options.editTitle=options.editTitle||"Edit average rating field";$super(customField,options)},registerCustomFields:function(){this.labelsField=new BrainstormJs.Controls.CustomFields.Forms.CustomRatingLabelsField({title:"Choices",subtitle:"Provide a meaning for each choice to help your reviewers make consistent decisions.",
required:false});this.registerField(this.labelsField)},saveEditedObject:function(){Brainstorm.Web.Services.Ajax.SaveCustomRatingField(this.customField.getParentObjectType(),this.customField.getParentObjectId(),this.customField.getFieldId(),this.fieldName.getValue(),this.getVisibilityValue(),this.labelsField.getValue(),this.customFieldUpdated.bind(this),function(error){bsCommon.ajaxCallError(error,this.onSaveError)}.bind(this))},onSaveError:function(){},customFieldUpdated:function($super,jsonCustomField){$super(jsonCustomField)},
beforeShow:function(){}});
BrainstormJs.Controls.CustomFields.BaseCustomField=Class.create({container:false,editor:false,formHolder:false,expose:false,actionsDiv:false,editLink:false,deleteLink:false,privateIcon:false,isEditing:false,editingClassName:"editingField",editForm:false,fieldId:false,fieldGuid:false,fieldType:false,fieldName:false,fieldCategory:false,parentTypeName:false,visibilityEditable:false,isVanilla:false,isOwner:false,frontendMode:false,backendMode:true,parentObjectType:false,parentObjectId:false,childObjectType:false,
childObjectId:false,initialize:function(container,options){this.container=container;this.frontendMode=options&&options.frontendMode;this.backendMode=!this.frontendMode;this.editor=options.editor||false;this.formHolder=this.container.down("div.anchor div.wrapper");this.actionsDiv=this.container.down("div.actions");this.fieldId=parseInt(this.container.down("input.data-Id").value,10);this.fieldGuid=this.container.down("input.data-Guid").value;this.fieldType=options.fieldType||parseInt(this.container.down("input.data-FieldType").value,
10);this.fieldCategory=parseInt(this.container.down("input.data-Category").value,10);this.visibilityEditable=parseInt(this.container.down("input.data-VisibilityEditable").value,10);this.parentTypeName=this.container.down("input.data-ParentTypeName").value;if(this.backendMode){this.nameDiv=this.container.down("div.fieldWrapper > div.name");this.fieldName=this.container.down("input.data-Name").value;this.editLink=this.actionsDiv.down("a.action-edit");this.deleteLink=this.actionsDiv.down("a.action-delete");
this.privateIcon=this.actionsDiv.down("a.action-visibility");this.isVanilla=this.container.down("input.data-IsVanilla").value=="1";this.wireBackendControls()}else if(this.frontendMode){this.nameDiv=this.container.down("div.leftCol span.fieldName");this.editLink=this.container.down("div.rightCol a.editLink");this.privateIcon=this.container.down("div.rightCol span.private");this.isOwner=this.container.down("input.data-IsOwner").value=="1";var evalDiv=this.container.up("div.ideaEvaluation");this.parentObjectType=
evalDiv.down("input.evaluationParentType").value;this.parentObjectId=parseInt(evalDiv.down("input.evaluationParentId").value,10);this.childObjectType=evalDiv.down("input.evaluationObjectType").value;this.childObjectId=parseInt(evalDiv.down("input.evaluationObjectId").value,10);this.wireFrontendControls()}if(this.editLink)this.editLink.observe("click",function(e){this.startEditing();e.stop()}.bind(this));if(this.deleteLink)this.deleteLink.observe("click",function(e){this.startArchive(e.shiftKey);e.stop()}.bind(this))},
startEditing:function(justCreated){if(this.isEditing){this.editLink.shake({distance:3});return}this.isEditing=true;this.exposeField();if(!this.editForm){var typeEnum=Brainstorm.Model.Enums.CustomFieldType;var formOptions={parentContainer:this.formHolder,closeSkipBlind:true,closeManually:true};this.editForm=this.getEditForm(formOptions)}if(this.editor)this.editor.toggleFieldPanel(false);this.editForm.startEditing();this.formHolder.blindDown({duration:0.5,afterFinish:function(){bsCommon.scrollIfBelowFold(this.formHolder,
10);this.editForm.focusFirstField()}.bind(this)})},stopEditing:function(closeForm){this.container.removeClassName(this.editingClassName);this.formHolder.blindUp({duration:0.5});if(closeForm)this.editForm.closeForm();this.isEditing=false;if(this.expose&&this.expose.isLoaded())this.expose.close();if(this.editor)this.editor.toggleFieldPanel(true);if(!closeForm&&this.isVanilla)this.deleteVanilla()},exposeField:function(){this.container.addClassName(this.editingClassName);this.expose=new Expose(this.container,
{detectPrototip:true,closeOnClick:false,closeOnEsc:false,onBeforeClose:function(){this.expose=false}.bind(this)})},validateSavedValue:function(jsonCustomField){var valid=true;if(jsonCustomField&&jsonCustomField.ErrorCode){var errorCode=jsonCustomField.ErrorCode;if(errorCode==Brainstorm.Model.Enums.CustomFieldError.FieldRemoved){bsCommon.alert("Oops! It looks like the custom field you are trying to edit or save has been removed. Please refresh this page to make sure you are working with the most up-to-date data.");
valid=false}else if(errorCode==Brainstorm.Model.Enums.CustomFieldError.ChoiceRemoved){bsCommon.alert("Oops! It looks like the drop down choice you selected is not longer available. Please refresh this page to make sure you are working with the most up-to-date choices.");valid=false}}if(!valid)this.stopEditing(true);return valid},updateAfterSave:function(jsonCustomField){this.afterSave(jsonCustomField);this.isVanilla=false;this.container.down("input.data-Name").value=jsonCustomField.Name;if(this.backendMode){this.nameDiv.innerHTML=
jsonCustomField.NameTruncated;this.nameDiv.title="";Tipped.remove(this.nameDiv);if(jsonCustomField.IsNameLong){this.nameDiv.addClassName("tipped");this.nameDiv.setAttribute("data-tipped-options","skin:'dark', maxWidth: 284, showDelay: 0.25, offset: { x: 1 }");this.nameDiv.title=jsonCustomField.Name;Tipped.refresh(this.nameDiv)}}else this.nameDiv.innerHTML=jsonCustomField.Name;this.container.down("input.data-Visibility").value=jsonCustomField.Visibility;if(this.privateIcon)if(jsonCustomField.IsPrivate&&
!this.privateIcon.visible())this.privateIcon.appear();else if(!jsonCustomField.IsPrivate&&this.privateIcon.visible())this.privateIcon.fade();this.fieldType=jsonCustomField.FieldType;this.container.down("input.data-FieldType").value=this.fieldType;this.stopEditing(true)},startArchive:function(shiftKey){if(this.frontendMode){console.error("Deleting fields not allowed from the frontend - please use the custom fields editor.");return}if(shiftKey)this.commitArchive();else bsCommon.confirm({title:"Removal Confirmation",
text:this.getArchiveConfirmationText()+" Removing it will DELETE the data associated with the list from each idea it touches.",width:450,confirmText:"Yes, remove it!",cancelText:"No, keep it.",onConfirm:this.commitArchive.bind(this)})},commitArchive:function(){Brainstorm.Web.Services.Ajax.ArchiveCustomField(this.getParentObjectType(),this.getParentObjectId(),this.fieldId,this.afterArchive.bind(this),bsCommon.ajaxCallError)},afterArchive:function(retvalue,fieldName){Effect.BlindUp(this.container,{duration:0.5,
afterFinish:function(){this.container.remove();this.editor.unregisterField(this);var confirmMessage="'"+this.fieldName+"' has been successfully removed.";if(retvalue>0)confirmMessage+=" As a result, "+retvalue+" ideas have had their value for this field reset.";bsCommon.showSuccess(confirmMessage)}.bind(this)})},deleteVanilla:function(){Brainstorm.Web.Services.Ajax.DeleteCustomField(this.getParentObjectType(),this.getParentObjectId(),this.fieldId,this.afterDelete.bind(this),bsCommon.ajaxCallError)},
afterDelete:function(fieldDeleted){if(fieldDeleted)Effect.BlindUp(this.container,{duration:0.5,afterFinish:function(){this.container.remove();this.editor.unregisterField(this)}.bind(this)})},getParentObjectType:function(){if(this.editor)return this.editor.getParentObjectType();return this.parentObjectType},getParentObjectId:function(){if(this.editor)return this.editor.getParentObjectId();return this.parentObjectId},getChildObjectType:function(){return this.childObjectType},getChildObjectId:function(){return this.childObjectId},
getContainer:function(){return this.container},getFieldId:function(){return this.fieldId},getFieldType:function(){return this.fieldType},getFieldCategory:function(){return this.fieldCategory},getParentTypeName:function(){return this.parentTypeName},getGuid:function(){return this.fieldGuid;return this.getParentObjectType()+"_"+this.getParentObjectId()+"_Field_"+this.getFieldId()},isVisibilityEditable:function(){return this.visibilityEditable},wireFrontendControls:function(){},wireBackendControls:function(){},
afterProvision:function(jsonCustomField){},afterSave:function(jsonCustomField){},getEditForm:function(formOptions){},getArchiveConfirmationText:function(){}});
BrainstormJs.Controls.CustomFields.CustomDropDownField=Class.create(BrainstormJs.Controls.CustomFields.BaseCustomField,{dropDown:false,initialize:function($super,container,editor,options){$super(container,editor,options)},getChoices:function(){if(BS_CustomFieldChoices){var choices=BS_CustomFieldChoices[this.getGuid()];if(!choices)console.error("fieldGuid %o is not defined ...",this.getGuid());return choices}},updateGlobalChoices:function(choices){if(BS_CustomFieldChoices)BS_CustomFieldChoices[this.getGuid()]=
choices},wireFrontendControls:function(){this.dropDown=this.container.down("select.customDropDown");if(this.dropDown)this.dropDown.observe("change",function(e){this.saveDropDownValue(e.element());e.stop()}.bind(this))},afterProvision:function(jsonCustomField){BS_CustomFieldChoices[jsonCustomField.Guid]=jsonCustomField.Choices},afterSave:function(jsonCustomField){if(this.frontendMode&&jsonCustomField.IsChoiceField){var dropDown=this.container.down("select.customDropDown");if(dropDown){var currentSelectedValue=
dropDown.options[dropDown.selectedIndex].value;dropDown.innerHTML='<option value="" />';for(var i=0,j=jsonCustomField.Choices.length;i<j;i++){var choice=jsonCustomField.Choices[i];var option=(new Element("option",{"value":choice.Id})).update(choice.Label);dropDown.insert(option);if(option.value==currentSelectedValue)option.selected=true}}}},getEditForm:function(formOptions){return new BrainstormJs.Controls.CustomFields.Forms.CustomDropDownForm(this,formOptions)},getArchiveConfirmationText:function(){return"Are you sure you want to remove this custom drop down list?"},
saveDropDownValue:function(dropDown){var dropDownValue=dropDown.options[dropDown.selectedIndex].value;Brainstorm.Web.Services.Ajax.SaveCustomDropDownValue(this.getChildObjectType(),this.getChildObjectId(),this.getFieldId(),dropDownValue,this.afterSaveDropDownValue.bind(this),bsCommon.ajaxCallError,dropDown)},afterSaveDropDownValue:function(jsonCustomField,dropDown){if(this.validateSavedValue(jsonCustomField)){var confirm=dropDown.next("span.saveConfirm");confirm.appear({duration:0.25,afterFinish:function(){confirm.fade({delay:0.25,
duration:1})}})}}});
BrainstormJs.Controls.CustomFields.CustomTextField=Class.create(BrainstormJs.Controls.CustomFields.BaseCustomField,{multiLine:false,saveLink:false,savedValue:false,unsavedClass:"unsaved",initialize:function($super,container,options){$super(container,options)},wireFrontendControls:function(){var editArea=this.container.down("div.editTextField");if(editArea){this.multiLine=editArea.down("textarea.multiLine");this.savedValue=this.getActiveInput().value;this.saveLink=editArea.down("input.saveValue");this.saveLink.observe("click",
this.saveTextValue.bind(this));var fxOnInputChange=this.onInputChange.bind(this);this.multiLine.observe("keyup",fxOnInputChange);this.multiLine.observe("paste",fxOnInputChange);this.multiLine.observe("blur",fxOnInputChange)}},getActiveInput:function(){return this.multiLine},showSaveLink:function(){if(!this.saveLink.visible()){this.saveLink.disabled=false;this.saveLink.value="Save";this.saveLink.addClassName(this.unsavedClass);this.saveLink.appear({duration:0.5,from:0,to:1})}},hideSaveLink:function(showSavedConfirmation){if(this.saveLink.visible()){this.saveLink.removeClassName(this.unsavedClass);
this.saveLink.fade({duration:0.25,from:1,to:0});if(showSavedConfirmation){var confirm=this.saveLink.next("span.saveConfirm");confirm.appear({delay:0.25,duration:0.25,afterFinish:function(){confirm.fade({delay:0.5,duration:1.25})}})}}},onInputChange:function(){var newValue=this.getActiveInput().value;if(newValue!=this.savedValue)this.showSaveLink();else this.hideSaveLink()},afterProvision:function(jsonCustomField){},afterSave:function(jsonCustomField){},getEditForm:function(formOptions){return new BrainstormJs.Controls.CustomFields.Forms.CustomTextFieldForm(this,
formOptions)},getArchiveConfirmationText:function(){return"Are you sure you want to remove this text field?"},saveTextValue:function(){var textValue=this.getActiveInput().value.strip();this.saveLink.disabled=true;this.saveLink.value="...";Brainstorm.Web.Services.Ajax.SaveCustomTextFieldValue(this.getChildObjectType(),this.getChildObjectId(),this.getFieldId(),textValue,this.afterSaveTextValue.bind(this),bsCommon.ajaxCallError)},afterSaveTextValue:function(jsonCustomField){if(this.validateSavedValue(jsonCustomField)){var newValue=
jsonCustomField.Value;this.savedValue=newValue;this.multiLine.value=newValue;this.hideSaveLink(true)}}});
BrainstormJs.Controls.CustomFields.CustomRatingField=Class.create(BrainstormJs.Controls.CustomFields.BaseCustomField,{savedValue:false,unsavedClass:"unsaved",summaryDiv:false,choiceGuide:false,choiceGuideWired:false,ratingStars:false,avgRatingSpan:false,totalRatingsSpan:false,pluralRatingsSpan:false,showSummaryLink:false,disagreementIcon:false,noRatingsDiv:false,userRatingDiv:false,alreadyRatedDiv:false,userRatingSpan:false,clearLink:false,noUserRatingDiv:false,incompleteMessage:false,summaryPane:false,
initialize:function($super,container,options){this.container=container;$super(container,options)},wireFrontendControls:function(){this.incompleteMessage=this.container.up("div.fieldGroupBody").down("div.incompleteReview");var commonRatingsDiv=this.container.down("div.commonRatings");this.choiceGuide=commonRatingsDiv.down(".choiceGuide");this.summaryDiv=commonRatingsDiv.down(".summary");this.avgRatingSpan=this.summaryDiv.down(".avgRating");this.totalRatingsSpan=this.summaryDiv.down(".totalRatings");
this.pluralRatingsSpan=this.summaryDiv.down(".pluralRatings");this.showSummaryLink=this.summaryDiv.down("a.showRatings");this.disagreementIcon=commonRatingsDiv.down(".disagreement");this.noRatingsDiv=commonRatingsDiv.down(".noRatings");this.userRatingDiv=this.container.down("div.userRating");this.alreadyRatedDiv=this.userRatingDiv.down(".alreadyRated");this.userRatingSpan=this.alreadyRatedDiv.down(".rating");this.clearLink=this.alreadyRatedDiv.down(".clearRating");this.noUserRatingDiv=this.userRatingDiv.down(".noRating");
this.clearLink.observe("click",function(e){this.confirmClear();e.stop()}.bind(this));if(this.showSummaryLink)this.showSummaryLink.observe("click",function(e){this.showSummary();e.stop()}.bind(this));if(this.choiceGuide&&(Prototype.Browser.IE6||Prototype.Browser.IE7))this.choiceGuide=false;this.wireStarRating()},afterProvision:function(jsonCustomField){},afterSave:function(jsonCustomField){if(this.frontendMode&&this.choiceGuide)for(var i=0;i<5;i++){var labelSpan=this.choiceGuide.down("span.label-"+
(i+1));labelSpan.innerHTML=jsonCustomField.Labels[i]}},getEditForm:function(formOptions){return new BrainstormJs.Controls.CustomFields.Forms.CustomRatingFieldForm(this,formOptions)},getArchiveConfirmationText:function(){return"Are you sure you want to remove this rating field?"},wireStarRating:function(){var starContainer=this.container.down("div.starContainer");if(starContainer){var averageRating=parseFloat(starContainer.readAttribute("data-AvgRating"));var totalRatings=parseInt(starContainer.readAttribute("data-TotalRatings"));
var userRating=parseInt(starContainer.readAttribute("data-UserRating"));this.ratingStars=new BrainstormJs.Controls.RatingStars({element:starContainer,average:averageRating,total:totalRatings,userRating:userRating,overlay:"square_overlay.png",onRate:this.onRate.bind(this),onHoverChange:this.choiceGuide?this.showChoiceGuide.bind(this):false,hoverDelay:350,onMouseLeave:this.choiceGuide?this.hideChoiceGuide.bind(this):false,ghosting:false})}},onRate:function(element,details){this.hideChoiceGuide();Brainstorm.Web.Services.Ajax.SaveCustomRating(this.getChildObjectType(),
this.getChildObjectId(),this.fieldId,details.rated,this.afterRate.bind(this),bsCommon.ajaxCallError)},showChoiceGuide:function(rating){if(!this.choiceGuide)return;if(!this.choiceGuideWired){this.choiceGuide.observe("mouseout",this.hideChoiceGuide.bind(this));this.choiceGuideWired=true}for(var i=1;i<=5;i++)this.choiceGuide.removeClassName("choiceHover-"+i);this.choiceGuide.addClassName("choiceHover-"+rating);if(!this.choiceGuide.visible())this.choiceGuide.appear({duration:0.25,queue:"end",to:1})},
hideChoiceGuide:function(){if(!this.choiceGuide)return;if(this.choiceGuide.visible())this.choiceGuide.fade({duration:0.25,queue:"end",to:0})},afterRate:function(jsonRatingField){this.updateFrontendView(jsonRatingField)},commitClear:function(){Brainstorm.Web.Services.Ajax.SaveCustomRating(this.getChildObjectType(),this.getChildObjectId(),this.fieldId,null,this.afterClear.bind(this),bsCommon.ajaxCallError)},afterClear:function(jsonRatingField){this.updateFrontendView(jsonRatingField);this.ratingStars.setState({average:jsonRatingField.ExactAverage,
total:jsonRatingField.TotalRatings,rated:0})},updateFrontendView:function(jsonRatingField){if(jsonRatingField.ErrorCode)if(errorCode==Brainstorm.Model.Enums.CustomFieldError.FieldRemoved){bsCommon.alert("Oops! It looks like the field you are trying to rate has been removed. Please refresh this page to make sure you are working with the most up-to-date data.");return}this.avgRatingSpan.innerHTML=jsonRatingField.ExactAverageStr+" ";this.totalRatingsSpan.innerHTML=jsonRatingField.TotalRatings+" ";if(jsonRatingField.ExactAverage>
0){this.pluralRatingsSpan[jsonRatingField.TotalRatings==1?"hide":"show"]();this.noRatingsDiv.hide();this.summaryDiv.show()}else{this.summaryDiv.hide();this.noRatingsDiv.show()}for(var i=1;i<=5;i++)this.userRatingDiv.removeClassName("userRating-"+i);if(jsonRatingField.UserRating){this.userRatingDiv.addClassName("userRating-"+jsonRatingField.UserRating);this.userRatingSpan.innerHTML=jsonRatingField.UserRating;this.noUserRatingDiv.hide();this.alreadyRatedDiv.show();this.container.addClassName("userRated");
var fieldSection=this.container.up();var numFields=fieldSection.childElements().length;var numFieldsRated=fieldSection.select("> div.userRated").length;if(numFieldsRated==numFields&&this.incompleteMessage&&this.incompleteMessage.visible())this.incompleteMessage.blindUp({duration:0.5})}else{this.alreadyRatedDiv.hide();this.noUserRatingDiv.show();this.container.removeClassName("userRated");if(this.incompleteMessage&&!this.incompleteMessage.visible())this.incompleteMessage.blindDown({duration:0.5})}if(jsonRatingField.Disagreement){if(!this.disagreementIcon.visible())this.disagreementIcon.appear({duration:0.5})}else if(this.disagreementIcon.visible())this.disagreementIcon.fade({duration:0.25})},
showSummary:function(){if(!this.summaryPane){var pane=this.userRatingDiv.next("div.ratingSummaryPane");this.summaryPane=new BrainstormJs.Controls.AjaxContentPane(pane)}this.showSummaryLink.fade({duration:0.25,to:0});this.summaryPane.startLoading({dataMethod:this.loadSummaryView.bind(this)})},loadSummaryView:function(){Brainstorm.Web.Services.Ajax.GetCustomRatingSummary(this.getChildObjectType(),this.getChildObjectId(),this.fieldId,this.onSummaryLoaded.bind(this),bsCommon.ajaxCallError)},onSummaryLoaded:function(jsonDomElement){this.summaryPane.insertContent(jsonDomElement.HTML,
{onContentReady:this.afterSummaryLoaded.bind(this)})},afterSummaryLoaded:function(){var closeLink=this.summaryPane.getContentDiv().down("a.close");closeLink.observe("click",function(e){this.hideSummary();e.stop()}.bind(this));this.summaryPane.showContent()},hideSummary:function(){this.summaryPane.close({destroyContent:true});this.showSummaryLink.appear({duration:0.5})},confirmClear:function(){bsCommon.confirm({title:"Confirmation",text:"Are you sure you want to clear your rating?",width:450,confirmText:"Yep!",
cancelText:"No, keep it.",onConfirm:this.commitClear.bind(this)})}});
BrainstormJs.Controls.CustomFields.CustomFieldHelper={getFieldInstance:function(fieldDiv,options){var fieldType=parseInt(fieldDiv.down("input.data-FieldType").value,10);var typeEnum=Brainstorm.Model.Enums.CustomFieldType;var instance=false;Object.extend(options,{fieldType:fieldType});if(fieldType==typeEnum.DropDown)instance=new BrainstormJs.Controls.CustomFields.CustomDropDownField(fieldDiv,options);else if(fieldType==typeEnum.PlainTextMultiLine)instance=new BrainstormJs.Controls.CustomFields.CustomTextField(fieldDiv,
options);else if(fieldType==typeEnum.AverageRating)instance=new BrainstormJs.Controls.CustomFields.CustomRatingField(fieldDiv,options);else{console.error("Could not locate custom field class for field type: "+fieldType);return false}return instance},wireFrontendFields:function(container){if(!container){alert("Cannot set up custom fields for element: "+container);return}var customRows=container.select("div.editableField");for(var i=0,j=customRows.length;i<j;i++){var row=customRows[i];var field=BrainstormJs.Controls.CustomFields.CustomFieldHelper.getFieldInstance(row,
{frontendMode:true})}},updateGlobalChoices:function(jsonChoiceFields){if(!BS_CustomFieldChoices){console.error("Could not locate global custom field choice collection");return}if(!jsonChoiceFields||!jsonChoiceFields.length)return;for(var i=0,j=jsonChoiceFields.length;i<j;i++){var jsonField=jsonChoiceFields[i];BS_CustomFieldChoices[jsonField.Guid]=jsonField.Choices}},convertToFormFields:function(jsonFields){if(!jsonFields)return;var formFields=[];for(var i=0,j=jsonFields.length;i<j;i++){var jsonField=
jsonFields[i];var jsonFieldType=jsonField.FieldTypeInt!=null?jsonField.FieldTypeInt:jsonField.Type;if(jsonFieldType==Brainstorm.Model.Enums.CustomFieldType.PlainTextMultiLine){var textareaField=new BrainstormJs.Forms.Fields.TextArea({title:jsonField.Name,required:true,enableWysiwyg:false,customFieldId:jsonField.Id});formFields.push(textareaField)}else if(jsonFieldType==Brainstorm.Model.Enums.CustomFieldType.DropDown){var dropDownField=new BrainstormJs.Forms.Fields.DropDownList({title:jsonField.Name,
required:true,choices:jsonField.Choices,customFieldId:jsonField.Id,addBlank:true});formFields.push(dropDownField)}else console.error("Field of type "+jsonField.Type+" cannot be converted to a form field.")}return formFields}};
BrainstormJs.Controls.CustomFields.CustomFieldsEditorGroup=Class.create({container:false,options:false,wrapperBox:false,parentObjectType:false,parentObjectId:false,editors:false,initialize:function(container,options){this.container=container;this.options=options;this.editors=options.jsonEditors;if(!this.container){console.error("Invalid container for custom fields editor group.");return}this.parentObjectType=options.parentObjectType;this.parentObjectId=options.parentObjectId;this.wrapperBox=new BrainstormJs.Controls.ActionBox(this.container,
{afterClose:this.onClose.bind(this)});this.wireEditors()},wireEditors:function(){for(var i=0,j=this.editors.length;i<j;i++){var editor=this.editors[i];var editorContainer=this.container.down("#"+editor.EditorId);var editor=new BrainstormJs.Controls.CustomFields.CustomFieldsEditor(editorContainer,{fieldCategory:editor.CategoryInt,groupBox:this.wrapperBox,parentObjectType:this.parentObjectType,parentObjectId:this.parentObjectId})}},onClose:function(){if(this.options.afterClose)this.options.afterClose()}});
BrainstormJs.Controls.CustomFields.CustomFieldsConfigPanel=Class.create({container:false,configBar:false,editorHolder:false,editorId:false,parentObjectType:false,parentObjectId:false,fieldCategory:false,editorAjaxPane:false,editorGroup:false,contextualHelp:false,initialize:function(container,options){this.container=container;this.parentObjectType=this.container.down("input.parentObjectType").value;this.parentObjectId=parseInt(this.container.down("input.parentObjectId").value,10);this.editorHolder=
this.container.down("div#editorHolder");this.editorAjaxPane=new BrainstormJs.Controls.AjaxContentPane(this.editorHolder);this.configBar=this.container.down("div.configBar");var fxStartEditing=function(e){this.startEditing(e.element());e.stop()}.bind(this);this.configBar.select("a.editFields").each(function(link){link.observe("click",fxStartEditing)});this.contextualHelp=$("customizeHelpMessage");if(this.contextualHelp)this.contextualHelp.blindDown()},startEditing:function(linkClicked){if(this.contextualHelp)this.contextualHelp.blindUp();
this.fieldCategory=parseInt(linkClicked.readAttribute("data-Category"),10);if(this.editorGroup){this.editorHolder.blindDown({duration:1});this.configBar.blindUp({duration:0.5})}else this.editorAjaxPane.startLoading({hideElements:[this.configBar],dataMethod:this.loadEditorGroup.bind(this)})},loadEditorGroup:function(){Brainstorm.Web.Services.Ajax.GetCustomFieldEditorGroup(this.parentObjectType,this.parentObjectId,this.fieldCategory,true,this.insertEditorGroup.bind(this),bsCommon.ajaxCallError)},insertEditorGroup:function(jsonObjectView){var jsonEditorGroup=
jsonObjectView.Object;var jsonEditors=jsonEditorGroup.Editors;var jsonChoiceFields=jsonEditorGroup.ChoiceFields;var editorGroupView=jsonObjectView.View;BrainstormJs.Controls.CustomFields.CustomFieldHelper.updateGlobalChoices(jsonChoiceFields);this.editorAjaxPane.insertContent(editorGroupView.HTML,{onContentReady:function(){this.bindEditorGroup(jsonEditors)}.bind(this)})},bindEditorGroup:function(jsonEditors){var editorGroupDiv=this.editorAjaxPane.getContentDiv().firstDescendant();if(!editorGroupDiv)console.error("Could not find the editor group element.");
this.editorGroup=new BrainstormJs.Controls.CustomFields.CustomFieldsEditorGroup(editorGroupDiv,{jsonEditors:jsonEditors,parentObjectType:this.parentObjectType,parentObjectId:this.parentObjectId,afterClose:this.afterEditorGroupClose.bind(this)});this.editorAjaxPane.showContent()},afterEditorGroupClose:function(){this.editorGroup=false;var contextualHelpItem=$("shareHelpMessage");if(contextualHelpItem)if(!contextualHelpItem.visible())contextualHelpItem.blindDown();this.editorAjaxPane.close({destroyContent:true})}});
BrainstormJs.Controls.CustomFields.CustomFieldsEditor=Class.create({container:false,options:false,parentObjectType:false,parentObjectId:false,fieldCategory:false,fieldsDiv:false,noFieldsDiv:false,addFieldPanel:false,groupBox:false,disabledPanelClass:"disabled",fields:false,isEmpty:false,initialize:function(container,options){this.container=container;this.options=options;this.groupBox=options.groupBox;if(!this.container){console.error("Invalid container for custom fields editor.");return}this.parentObjectType=
options.parentObjectType;this.parentObjectId=options.parentObjectId;this.fieldCategory=options.fieldCategory;this.fieldsDiv=this.container.down("div.editorFields");this.noFieldsDiv=this.container.down("div.noCustomFields");this.addFieldPanel=this.container.down("div.editorAddFieldPanel");this.isEmpty=this.noFieldsDiv.visible();var addLinks=this.addFieldPanel.select("a.addField");var fxStartAddField=function(e){this.startAddField(e.element());e.stop()}.bind(this);for(var i=0,j=addLinks.length;i<j;i++)addLinks[i].observe("click",
fxStartAddField);this.fields=[];var fieldEls=this.fieldsDiv.select("div.customField");for(var i=0,j=fieldEls.length;i<j;i++)this.registerField(fieldEls[i],false);this.refreshSortable()},registerField:function(fieldDiv,refreshSortable){if(this.isEmpty){this.noFieldsDiv.blindUp({duration:0.25});this.isEmpty=false}var field=BrainstormJs.Controls.CustomFields.CustomFieldHelper.getFieldInstance(fieldDiv,{editor:this});this.fields.push(field);if(refreshSortable)this.refreshSortable();return field},unregisterField:function(field){this.fields=
this.fields.without(field);this.isEmpty=this.fields.length==0;if(this.isEmpty)this.noFieldsDiv.blindDown({duration:0.5})},refreshSortable:function(){Sortable.create(this.fieldsDiv,{dropOnEmpty:false,tag:"div",only:"customField",handle:"fieldWrapper",constraint:"vertical",scroll:window,onUpdate:function(sortableContainer){this.saveNewFieldOrder(sortableContainer)}.bind(this)})},saveNewFieldOrder:function(sortableContainer){var serialized=bsCommon.serializeSortable(sortableContainer);Brainstorm.Web.Services.Ajax.SaveCustomFieldOrder(this.parentObjectType,
this.parentObjectId,this.fieldCategory,bsCommon.serializeSortable(sortableContainer),this.fieldOrderSaved.bind(this),bsCommon.ajaxCallError)},fieldOrderSaved:function(){bsCommon.showSuccess("The new order for the custom fields has been saved.")},startAddField:function(linkClicked){if(this.addFieldPanel.hasClassName(this.disabledPanelClass)){this.addFieldPanel.shake({distance:3});return}var fieldType=false;if(linkClicked.hasClassName("addDropDown"))fieldType=Brainstorm.Model.Enums.CustomFieldType.DropDown;
else if(linkClicked.hasClassName("addTextBox"))fieldType=Brainstorm.Model.Enums.CustomFieldType.PlainTextMultiLine;else if(linkClicked.hasClassName("addRating"))fieldType=Brainstorm.Model.Enums.CustomFieldType.AverageRating;if(fieldType||fieldType===0)this.provisionField(fieldType);else alert("Oops, we couldn't create the custom field. Please try refreshing this page.")},provisionField:function(fieldType){this.toggleFieldPanel(false);Brainstorm.Web.Services.Ajax.ProvisionCustomField(this.parentObjectType,
this.parentObjectId,fieldType,this.fieldCategory,this.afterFieldProvisioned.bind(this),function(error){bsCommon.ajaxCallError(error,this.onProvisionError.bind(this))}.bind(this))},onProvisionError:function(){this.toggleFieldPanel(true)},afterFieldProvisioned:function(jsonObjectView){var jsonCustomField=jsonObjectView.Object;var jsonDomElement=jsonObjectView.View;if(jsonCustomField.MaxReached){var customType="field";if(jsonCustomField.IsDropDown)customType="drop down list";else if(jsonCustomField.IsOpenText)customType=
"open text field";else if(jsonCustomField.IsAvgRating)customType="average rating field";bsCommon.alert("You've reached the maximum limit for "+customType+"s on this pipeline. We created the limit to ensure that pages remain quick and snappy. "+'If this limit is a problem, <a href="mailto:support@intuitbrainstorm.com?subject=Custom Field Limit Reached">please let us know</a>. '+"In the meantime, you can remove one of your other "+customType+"s and then add another.");this.toggleFieldPanel(true);return}this.fieldsDiv.insert(jsonDomElement.HTML);
var newFieldDiv=this.fieldsDiv.down("#"+jsonDomElement.Id);var newField=this.registerField(newFieldDiv,true);newFieldDiv.blindDown({duration:0.25,afterFinish:function(){newField.afterProvision(jsonCustomField);newField.startEditing(true)}})},toggleFieldPanel:function(enable){var disabled=this.addFieldPanel.hasClassName(this.disabledPanelClass);if(enable){if(disabled){this.addFieldPanel.appear({from:0.5,to:1});this.groupBox.showCloseLink()}this.addFieldPanel.removeClassName(this.disabledPanelClass)}else{if(!disabled){this.addFieldPanel.fade({from:1,
to:0.5});this.groupBox.hideCloseLink()}this.addFieldPanel.addClassName(this.disabledPanelClass)}},getParentObjectType:function(){return this.parentObjectType},getParentObjectId:function(){return this.parentObjectId},getFieldCategory:function(){return this.fieldCategory}});
BrainstormJs.Forms.Grid.SaveFilterSetForm=Class.create(BrainstormJs.Forms.BaseForm,{fieldName:false,gridType:false,parentProfileId:false,fxAfterSave:false,initialize:function($super,options){options=options||{};options.createTitle="Save view";options.submitButtonTitle="Save";this.gridType=options.gridType;this.parentProfileId=options.parentProfileId;this.fxAfterSave=options.afterSave;$super(null,options)},createFields:function($super){this.fieldName=new BrainstormJs.Forms.Fields.TextBox({title:"Name",
maxLength:120,required:true,submitOnEnter:true});this.registerField(this.fieldName)},createNewObject:function(){Brainstorm.Web.Services.Ajax.SaveFilterSet(this.gridType,this.parentProfileId,this.fieldName.getValue(),this.onSuccess.bind(this),this.handleAjaxError.bind(this))},onSuccess:function(jsonFilterSet){if(this.fxAfterSave)this.fxAfterSave(jsonFilterSet);this.closeForm({afterFinish:function(){bsCommon.showSuccess("Successfully saved view.")}})}});
BrainstormJs.Controls.Grid.GridWrapper=Class.create({container:false,gridObject:false,options:false,filtersAndGrid:false,heightPlaceholder:false,expandLink:false,collapseLink:false,closeLink:false,expandedClass:"expandedGrid",collapseClass:"collapseGrid",expose:false,sideMargin:15,minWidth:940,resizeObserver:false,initialize:function(container,options){if(!container)return;this.options=options;this.gridObject=options.gridObject||false;if(options.createStructure==true)this.buildWrapper(container);
else{this.container=container;this.filtersAndGrid=this.container.down("div.filtersAndGrid");this.heightPlaceholder=this.container.down("div.heightPlaceholder")}this.expandLink=options.expandLink||false;if(this.expandLink)this.expandLink.observe("click",function(e){this.expandGrid();e.stop()}.bind(this));this.collapseLink=options.collapseLink||false;if(this.collapseLink)this.collapseLink.observe("click",function(e){this.collapseGrid();e.stop()}.bind(this));this.closeLink=this.container.down("a.collapseGrid");
if(this.closeLink)this.closeLink.observe("click",function(e){this.collapseGrid();e.stop()}.bind(this))},buildWrapper:function(gridContainer){var wrapper=new Element("div",{"class":"gridWrapper"});var closeBar=new Element("div",{"class":"buttons clearfix"});var closeLink=(new Element("a",{"class":"collapseGrid",href:"#",style:"display:none;"})).update("close");this.heightPlaceholder=new Element("div",{"class":"heightPlaceholder"});this.filtersAndGrid=gridContainer.wrap("div",{"class":"filtersAndGrid"});
this.filtersAndGrid.insert({top:closeBar.insert(closeLink)});this.container=this.filtersAndGrid.wrap(wrapper);this.container.insert(this.heightPlaceholder)},expandGrid:function(){if(!this.resizeObserver)this.resizeObserver=this.onWindowResize.bind(this);this.filtersAndGrid.addClassName(this.expandedClass);this.adjustWidth();this.heightPlaceholder.setStyle({height:this.filtersAndGrid.getHeight()+"px"});this.toggleHiddenColumns(true);this.expose=new Expose(this.filtersAndGrid,{detectPrototip:true,closeOnClick:false,
closeOnEsc:false,onBeforeClose:function(){this.expose=false;this.collapseGrid()}.bind(this)});this.closeLink.show();Event.observe(window,"resize",this.resizeObserver);if(this.gridObject)this.gridObject.trackAction("expand")},toggleHiddenColumns:function(show){var browserSucks=Prototype.Browser.IE6||Prototype.Browser.IE7;if(!browserSucks)return;var hiddenCells=this.filtersAndGrid.select(".hideable");for(var i=0,j=hiddenCells.length;i<j;i++)hiddenCells[i].style.display=show?"block":""},collapseGrid:function(){this.closeLink.hide();
this.filtersAndGrid.setStyle({left:"0px",width:"auto"});this.filtersAndGrid.removeClassName(this.expandedClass);this.toggleHiddenColumns(false);this.heightPlaceholder.setStyle({height:0+"px"});Event.stopObserving(window,"resize",this.resizeObserver);if(this.expose&&this.expose.isLoaded())this.expose.close();if(this.gridObject)this.gridObject.trackAction("collapse")},adjustWidth:function(){var screenWidth=document.viewport.getWidth()-20;var gridWidth=Math.max(this.minWidth,screenWidth-this.sideMargin*
2);this.filtersAndGrid.setStyle({left:this.sideMargin+"px",width:gridWidth+"px"})},onWindowResize:function(){this.adjustWidth()}});BrainstormJs.Controls.DataFilters.Input.BaseDataFilterInput=Class.create({container:false,editor:false,initialize:function(container,editor,options){this.container=container;this.editor=editor},getEditor:function(){return this.editor},getValue:function(){},destroy:function(){}});
BrainstormJs.Controls.DataFilters.Input.DropDownList=Class.create(BrainstormJs.Controls.DataFilters.Input.BaseDataFilterInput,{dropDown:false,selectedValue:false,initialize:function($super,container,editor,options){$super(container,editor,options);this.dropDown=this.container.down("select.dropDown");this.dropDown.observe("change",this.onChangeValue.bind(this))},onChangeValue:function(){var selectedIndex=this.dropDown.selectedIndex;var selectedOption=this.dropDown.options[selectedIndex];this.selectedValue=
parseInt(selectedOption.value,10);this.getEditor().toggleCreateButton(!isNaN(this.selectedValue))},getValue:function(){return this.selectedValue},destroy:function(){this.dropDown.stopObserving();this.dropDown=false}});dhtmlx=function(obj){for(var a in obj)dhtmlx[a]=obj[a];return dhtmlx};
dhtmlx.extend_api=function(name,map,ext){var t=window[name];if(!t)return;window[name]=function(obj){if(obj&&typeof obj=="object"&&!obj.tagName){var that=t.apply(this,map._init?map._init(obj):arguments);for(var a in dhtmlx)if(map[a])this[map[a]](dhtmlx[a]);for(var a in obj)if(map[a])this[map[a]](obj[a]);else if(a.indexOf("on")==0)this.attachEvent(a,obj[a])}else var that=t.apply(this,arguments);if(map._patch)map._patch(this);return that||this};window[name].prototype=t.prototype;if(ext)dhtmlXHeir(window[name].prototype,
ext)};dhtmlxAjax={get:function(url,callback){var t=new dtmlXMLLoaderObject(true);t.async=arguments.length<3;t.waitCall=callback;t.loadXML(url);return t},post:function(url,post,callback){var t=new dtmlXMLLoaderObject(true);t.async=arguments.length<4;t.waitCall=callback;t.loadXML(url,true,post);return t},getSync:function(url){return this.get(url,null,true)},postSync:function(url,post){return this.post(url,post,null,true)}};
function dtmlXMLLoaderObject(funcObject,dhtmlObject,async,rSeed){this.xmlDoc="";if(typeof async!="undefined")this.async=async;else this.async=true;this.onloadAction=funcObject||null;this.mainObject=dhtmlObject||null;this.waitCall=null;this.rSeed=rSeed||false;return this}
dtmlXMLLoaderObject.prototype.waitLoadFunction=function(dhtmlObject){var once=true;this.check=function(){if(dhtmlObject&&dhtmlObject.onloadAction!=null)if(!dhtmlObject.xmlDoc.readyState||dhtmlObject.xmlDoc.readyState==4){if(!once)return;once=false;if(typeof dhtmlObject.onloadAction=="function")dhtmlObject.onloadAction(dhtmlObject.mainObject,null,null,null,dhtmlObject);if(dhtmlObject.waitCall){dhtmlObject.waitCall.call(this,dhtmlObject);dhtmlObject.waitCall=null}}};return this.check};
dtmlXMLLoaderObject.prototype.getXMLTopNode=function(tagName,oldObj){if(this.xmlDoc.responseXML){var temp=this.xmlDoc.responseXML.getElementsByTagName(tagName);if(temp.length==0&&tagName.indexOf(":")!=-1)var temp=this.xmlDoc.responseXML.getElementsByTagName(tagName.split(":")[1]);var z=temp[0]}else var z=this.xmlDoc.documentElement;if(z){this._retry=false;return z}if(_isIE&&!this._retry){var xmlString=this.xmlDoc.responseText;var oldObj=this.xmlDoc;this._retry=true;this.xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
this.xmlDoc.async=false;this.xmlDoc["loadXM"+"L"](xmlString);return this.getXMLTopNode(tagName,oldObj)}dhtmlxError.throwError("LoadXML","Incorrect XML",[oldObj||this.xmlDoc,this.mainObject]);return document.createElement("DIV")};
dtmlXMLLoaderObject.prototype.loadXMLString=function(xmlString){try{var parser=new DOMParser;this.xmlDoc=parser.parseFromString(xmlString,"text/xml")}catch(e){this.xmlDoc=new ActiveXObject("Microsoft.XMLDOM");this.xmlDoc.async=this.async;this.xmlDoc["loadXM"+"L"](xmlString)}this.onloadAction(this.mainObject,null,null,null,this);if(this.waitCall){this.waitCall();this.waitCall=null}};
dtmlXMLLoaderObject.prototype.loadXML=function(filePath,postMode,postVars,rpc){if(this.rSeed)filePath+=(filePath.indexOf("?")!=-1?"&":"?")+"a_dhx_rSeed="+(new Date).valueOf();this.filePath=filePath;if(!_isIE&&window.XMLHttpRequest)this.xmlDoc=new XMLHttpRequest;else if(document.implementation&&document.implementation.createDocument){this.xmlDoc=document.implementation.createDocument("","",null);this.xmlDoc.onload=new this.waitLoadFunction(this);this.xmlDoc.load(filePath);return}else this.xmlDoc=new ActiveXObject("Microsoft.XMLHTTP");
if(this.async)this.xmlDoc.onreadystatechange=new this.waitLoadFunction(this);this.xmlDoc.open(postMode?"POST":"GET",filePath,this.async);if(rpc){this.xmlDoc.setRequestHeader("User-Agent","dhtmlxRPC v0.1 ("+navigator.userAgent+")");this.xmlDoc.setRequestHeader("Content-type","text/xml")}else if(postMode)this.xmlDoc.setRequestHeader("Content-type","application/x-www-form-urlencoded");this.xmlDoc.setRequestHeader("X-Requested-With","XMLHttpRequest");this.xmlDoc.send(null||postVars);if(!this.async)(new this.waitLoadFunction(this))()};
dtmlXMLLoaderObject.prototype.destructor=function(){this._filterXPath=null;this._getAllNamedChilds=null;this._retry=null;this.async=null;this.rSeed=null;this.filePath=null;this.onloadAction=null;this.mainObject=null;this.xmlDoc=null;this.doXPath=null;this.doXPathOpera=null;this.doXSLTransToObject=null;this.doXSLTransToString=null;this.loadXML=null;this.loadXMLString=null;this.doSerialization=null;this.xmlNodeToJSON=null;this.getXMLTopNode=null;this.setXSLParamValue=null;return null};
dtmlXMLLoaderObject.prototype.xmlNodeToJSON=function(node){var t={};for(var i=0;i<node.attributes.length;i++)t[node.attributes[i].name]=node.attributes[i].value;t["_tagvalue"]=node.firstChild?node.firstChild.nodeValue:"";for(var i=0;i<node.childNodes.length;i++){var name=node.childNodes[i].tagName;if(name){if(!t[name])t[name]=[];t[name].push(this.xmlNodeToJSON(node.childNodes[i]))}}return t};
function callerFunction(funcObject,dhtmlObject){this.handler=function(e){if(!e)e=window.event;funcObject(e,dhtmlObject);return true};return this.handler}function getAbsoluteLeft(htmlObject){return getOffset(htmlObject).left}function getAbsoluteTop(htmlObject){return getOffset(htmlObject).top}function getOffsetSum(elem){var top=0,left=0;while(elem){top=top+parseInt(elem.offsetTop);left=left+parseInt(elem.offsetLeft);elem=elem.offsetParent}return{top:top,left:left}}
function getOffsetRect(elem){var box=elem.getBoundingClientRect();var body=document.body;var docElem=document.documentElement;var scrollTop=window.pageYOffset||docElem.scrollTop||body.scrollTop;var scrollLeft=window.pageXOffset||docElem.scrollLeft||body.scrollLeft;var clientTop=docElem.clientTop||body.clientTop||0;var clientLeft=docElem.clientLeft||body.clientLeft||0;var top=box.top+scrollTop-clientTop;var left=box.left+scrollLeft-clientLeft;return{top:Math.round(top),left:Math.round(left)}}
function getOffset(elem){if(elem.getBoundingClientRect)return getOffsetRect(elem);else return getOffsetSum(elem)}function convertStringToBoolean(inputString){if(typeof inputString=="string")inputString=inputString.toLowerCase();switch(inputString){case "1":case "true":case "yes":case "y":case 1:case true:return true;break;default:return false}}function getUrlSymbol(str){if(str.indexOf("?")!=-1)return"&";else return"?"}
function dhtmlDragAndDropObject(){if(window.dhtmlDragAndDrop)return window.dhtmlDragAndDrop;this.lastLanding=0;this.dragNode=0;this.dragStartNode=0;this.dragStartObject=0;this.tempDOMU=null;this.tempDOMM=null;this.waitDrag=0;window.dhtmlDragAndDrop=this;return this}dhtmlDragAndDropObject.prototype.removeDraggableItem=function(htmlNode){htmlNode.onmousedown=null;htmlNode.dragStarter=null;htmlNode.dragLanding=null};
dhtmlDragAndDropObject.prototype.addDraggableItem=function(htmlNode,dhtmlObject){htmlNode.onmousedown=this.preCreateDragCopy;htmlNode.dragStarter=dhtmlObject;this.addDragLanding(htmlNode,dhtmlObject)};dhtmlDragAndDropObject.prototype.addDragLanding=function(htmlNode,dhtmlObject){htmlNode.dragLanding=dhtmlObject};
dhtmlDragAndDropObject.prototype.preCreateDragCopy=function(e){if((e||window.event)&&(e||event).button==2)return;if(window.dhtmlDragAndDrop.waitDrag){window.dhtmlDragAndDrop.waitDrag=0;document.body.onmouseup=window.dhtmlDragAndDrop.tempDOMU;document.body.onmousemove=window.dhtmlDragAndDrop.tempDOMM;return false}window.dhtmlDragAndDrop.waitDrag=1;window.dhtmlDragAndDrop.tempDOMU=document.body.onmouseup;window.dhtmlDragAndDrop.tempDOMM=document.body.onmousemove;window.dhtmlDragAndDrop.dragStartNode=
this;window.dhtmlDragAndDrop.dragStartObject=this.dragStarter;document.body.onmouseup=window.dhtmlDragAndDrop.preCreateDragCopy;document.body.onmousemove=window.dhtmlDragAndDrop.callDrag;window.dhtmlDragAndDrop.downtime=(new Date).valueOf();if(e&&e.preventDefault){e.preventDefault();return false}return false};
dhtmlDragAndDropObject.prototype.callDrag=function(e){if(!e)e=window.event;dragger=window.dhtmlDragAndDrop;if((new Date).valueOf()-dragger.downtime<100)return;if(e.button==0&&_isIE)return dragger.stopDrag();if(!dragger.dragNode&&dragger.waitDrag){dragger.dragNode=dragger.dragStartObject._createDragNode(dragger.dragStartNode,e);if(!dragger.dragNode)return dragger.stopDrag();dragger.dragNode.onselectstart=function(){return false};dragger.gldragNode=dragger.dragNode;document.body.appendChild(dragger.dragNode);
document.body.onmouseup=dragger.stopDrag;dragger.waitDrag=0;dragger.dragNode.pWindow=window;dragger.initFrameRoute()}if(dragger.dragNode.parentNode!=window.document.body){var grd=dragger.gldragNode;if(dragger.gldragNode.old)grd=dragger.gldragNode.old;grd.parentNode.removeChild(grd);var oldBody=dragger.dragNode.pWindow;if(grd.pWindow&&grd.pWindow.dhtmlDragAndDrop.lastLanding)grd.pWindow.dhtmlDragAndDrop.lastLanding.dragLanding._dragOut(grd.pWindow.dhtmlDragAndDrop.lastLanding);if(_isIE){var div=document.createElement("Div");
div.innerHTML=dragger.dragNode.outerHTML;dragger.dragNode=div.childNodes[0]}else dragger.dragNode=dragger.dragNode.cloneNode(true);dragger.dragNode.pWindow=window;dragger.gldragNode.old=dragger.dragNode;document.body.appendChild(dragger.dragNode);oldBody.dhtmlDragAndDrop.dragNode=dragger.dragNode}dragger.dragNode.style.left=e.clientX+15+(dragger.fx?dragger.fx*-1:0)+(document.body.scrollLeft||document.documentElement.scrollLeft)+"px";dragger.dragNode.style.top=e.clientY+3+(dragger.fy?dragger.fy*-1:
0)+(document.body.scrollTop||document.documentElement.scrollTop)+"px";if(!e.srcElement)var z=e.target;else z=e.srcElement;dragger.checkLanding(z,e)};
dhtmlDragAndDropObject.prototype.calculateFramePosition=function(n){if(window.name){var el=parent.frames[window.name].frameElement.offsetParent;var fx=0;var fy=0;while(el){fx+=el.offsetLeft;fy+=el.offsetTop;el=el.offsetParent}if(parent.dhtmlDragAndDrop){var ls=parent.dhtmlDragAndDrop.calculateFramePosition(1);fx+=ls.split("_")[0]*1;fy+=ls.split("_")[1]*1}if(n)return fx+"_"+fy;else this.fx=fx;this.fy=fy}return"0_0"};
dhtmlDragAndDropObject.prototype.checkLanding=function(htmlObject,e){if(htmlObject&&htmlObject.dragLanding){if(this.lastLanding)this.lastLanding.dragLanding._dragOut(this.lastLanding);this.lastLanding=htmlObject;this.lastLanding=this.lastLanding.dragLanding._dragIn(this.lastLanding,this.dragStartNode,e.clientX,e.clientY,e);this.lastLanding_scr=_isIE?e.srcElement:e.target}else if(htmlObject&&htmlObject.tagName!="BODY")this.checkLanding(htmlObject.parentNode,e);else{if(this.lastLanding)this.lastLanding.dragLanding._dragOut(this.lastLanding,
e.clientX,e.clientY,e);this.lastLanding=0;if(this._onNotFound)this._onNotFound()}};
dhtmlDragAndDropObject.prototype.stopDrag=function(e,mode){dragger=window.dhtmlDragAndDrop;if(!mode){dragger.stopFrameRoute();var temp=dragger.lastLanding;dragger.lastLanding=null;if(temp)temp.dragLanding._drag(dragger.dragStartNode,dragger.dragStartObject,temp,_isIE?event.srcElement:e.target)}dragger.lastLanding=null;if(dragger.dragNode&&dragger.dragNode.parentNode==document.body)dragger.dragNode.parentNode.removeChild(dragger.dragNode);dragger.dragNode=0;dragger.gldragNode=0;dragger.fx=0;dragger.fy=
0;dragger.dragStartNode=0;dragger.dragStartObject=0;document.body.onmouseup=dragger.tempDOMU;document.body.onmousemove=dragger.tempDOMM;dragger.tempDOMU=null;dragger.tempDOMM=null;dragger.waitDrag=0};
dhtmlDragAndDropObject.prototype.stopFrameRoute=function(win){if(win)window.dhtmlDragAndDrop.stopDrag(1,1);for(var i=0;i<window.frames.length;i++)try{if(window.frames[i]!=win&&window.frames[i].dhtmlDragAndDrop)window.frames[i].dhtmlDragAndDrop.stopFrameRoute(window)}catch(e){}try{if(parent.dhtmlDragAndDrop&&parent!=window&&parent!=win)parent.dhtmlDragAndDrop.stopFrameRoute(window)}catch(e){}};
dhtmlDragAndDropObject.prototype.initFrameRoute=function(win,mode){if(win){window.dhtmlDragAndDrop.preCreateDragCopy();window.dhtmlDragAndDrop.dragStartNode=win.dhtmlDragAndDrop.dragStartNode;window.dhtmlDragAndDrop.dragStartObject=win.dhtmlDragAndDrop.dragStartObject;window.dhtmlDragAndDrop.dragNode=win.dhtmlDragAndDrop.dragNode;window.dhtmlDragAndDrop.gldragNode=win.dhtmlDragAndDrop.dragNode;window.document.body.onmouseup=window.dhtmlDragAndDrop.stopDrag;window.waitDrag=0;if(!_isIE&&mode&&(!_isFF||
_FFrv<1.8))window.dhtmlDragAndDrop.calculateFramePosition()}try{if(parent.dhtmlDragAndDrop&&parent!=window&&parent!=win)parent.dhtmlDragAndDrop.initFrameRoute(window)}catch(e){}for(var i=0;i<window.frames.length;i++)try{if(window.frames[i]!=win&&window.frames[i].dhtmlDragAndDrop)window.frames[i].dhtmlDragAndDrop.initFrameRoute(window,!win||mode?1:0)}catch(e){}};var _isFF=false;var _isIE=false;var _isOpera=false;var _isKHTML=false;var _isMacOS=false;var _isChrome=false;
if(navigator.userAgent.indexOf("Macintosh")!=-1)_isMacOS=true;if(navigator.userAgent.toLowerCase().indexOf("chrome")>-1)_isChrome=true;
if(navigator.userAgent.indexOf("Safari")!=-1||navigator.userAgent.indexOf("Konqueror")!=-1){var _KHTMLrv=parseFloat(navigator.userAgent.substr(navigator.userAgent.indexOf("Safari")+7,5));if(_KHTMLrv>525){_isFF=true;var _FFrv=1.9}else _isKHTML=true}else if(navigator.userAgent.indexOf("Opera")!=-1){_isOpera=true;_OperaRv=parseFloat(navigator.userAgent.substr(navigator.userAgent.indexOf("Opera")+6,3))}else if(navigator.appName.indexOf("Microsoft")!=-1){_isIE=true;if(navigator.appVersion.indexOf("MSIE 8.0")!=
-1&&document.compatMode!="BackCompat")_isIE=8}else{_isFF=true;var _FFrv=parseFloat(navigator.userAgent.split("rv:")[1])}
dtmlXMLLoaderObject.prototype.doXPath=function(xpathExp,docObj,namespace,result_type){if(_isKHTML||!_isIE&&!window.XPathResult)return this.doXPathOpera(xpathExp,docObj);if(_isIE){if(!docObj)if(!this.xmlDoc.nodeName)docObj=this.xmlDoc.responseXML;else docObj=this.xmlDoc;if(!docObj)dhtmlxError.throwError("LoadXML","Incorrect XML",[docObj||this.xmlDoc,this.mainObject]);if(namespace!=null)docObj.setProperty("SelectionNamespaces","xmlns:xsl='"+namespace+"'");if(result_type=="single")return docObj.selectSingleNode(xpathExp);
else return docObj.selectNodes(xpathExp)||new Array(0)}else{var nodeObj=docObj;if(!docObj)if(!this.xmlDoc.nodeName)docObj=this.xmlDoc.responseXML;else docObj=this.xmlDoc;if(!docObj)dhtmlxError.throwError("LoadXML","Incorrect XML",[docObj||this.xmlDoc,this.mainObject]);if(docObj.nodeName.indexOf("document")!=-1)nodeObj=docObj;else{nodeObj=docObj;docObj=docObj.ownerDocument}var retType=XPathResult.ANY_TYPE;if(result_type=="single")retType=XPathResult.FIRST_ORDERED_NODE_TYPE;var rowsCol=new Array;var col=
docObj.evaluate(xpathExp,nodeObj,function(pref){return namespace},retType,null);if(retType==XPathResult.FIRST_ORDERED_NODE_TYPE)return col.singleNodeValue;var thisColMemb=col.iterateNext();while(thisColMemb){rowsCol[rowsCol.length]=thisColMemb;thisColMemb=col.iterateNext()}return rowsCol}};function _dhtmlxError(type,name,params){if(!this.catches)this.catches=new Array;return this}_dhtmlxError.prototype.catchError=function(type,func_name){this.catches[type]=func_name};
_dhtmlxError.prototype.throwError=function(type,name,params){if(this.catches[type])return this.catches[type](type,name,params);if(this.catches["ALL"])return this.catches["ALL"](type,name,params);alert("Error type: "+arguments[0]+"\nDescription: "+arguments[1]);return null};window.dhtmlxError=new _dhtmlxError;
dtmlXMLLoaderObject.prototype.doXPathOpera=function(xpathExp,docObj){var z=xpathExp.replace(/[\/]+/gi,"/").split("/");var obj=null;var i=1;if(!z.length)return[];if(z[0]==".")obj=[docObj];else if(z[0]==""){obj=(this.xmlDoc.responseXML||this.xmlDoc).getElementsByTagName(z[i].replace(/\[[^\]]*\]/g,""));i++}else return[];for(i;i<z.length;i++)obj=this._getAllNamedChilds(obj,z[i]);if(z[i-1].indexOf("[")!=-1)obj=this._filterXPath(obj,z[i-1]);return obj};
dtmlXMLLoaderObject.prototype._filterXPath=function(a,b){var c=new Array;var b=b.replace(/[^\[]*\[\@/g,"").replace(/[\[\]\@]*/g,"");for(var i=0;i<a.length;i++)if(a[i].getAttribute(b))c[c.length]=a[i];return c};
dtmlXMLLoaderObject.prototype._getAllNamedChilds=function(a,b){var c=new Array;if(_isKHTML)b=b.toUpperCase();for(var i=0;i<a.length;i++)for(var j=0;j<a[i].childNodes.length;j++)if(_isKHTML){if(a[i].childNodes[j].tagName&&a[i].childNodes[j].tagName.toUpperCase()==b)c[c.length]=a[i].childNodes[j]}else if(a[i].childNodes[j].tagName==b)c[c.length]=a[i].childNodes[j];return c};function dhtmlXHeir(a,b){for(var c in b)if(typeof b[c]=="function")a[c]=b[c];return a}
function dhtmlxEvent(el,event,handler){if(el.addEventListener)el.addEventListener(event,handler,false);else if(el.attachEvent)el.attachEvent("on"+event,handler)}dtmlXMLLoaderObject.prototype.xslDoc=null;
dtmlXMLLoaderObject.prototype.setXSLParamValue=function(paramName,paramValue,xslDoc){if(!xslDoc)xslDoc=this.xslDoc;if(xslDoc.responseXML)xslDoc=xslDoc.responseXML;var item=this.doXPath("/xsl:stylesheet/xsl:variable[@name='"+paramName+"']",xslDoc,"http://www.w3.org/1999/XSL/Transform","single");if(item!=null)item.firstChild.nodeValue=paramValue};
dtmlXMLLoaderObject.prototype.doXSLTransToObject=function(xslDoc,xmlDoc){if(!xslDoc)xslDoc=this.xslDoc;if(xslDoc.responseXML)xslDoc=xslDoc.responseXML;if(!xmlDoc)xmlDoc=this.xmlDoc;if(xmlDoc.responseXML)xmlDoc=xmlDoc.responseXML;if(!_isIE){if(!this.XSLProcessor){this.XSLProcessor=new XSLTProcessor;this.XSLProcessor.importStylesheet(xslDoc)}var result=this.XSLProcessor.transformToDocument(xmlDoc)}else{var result=new ActiveXObject("Msxml2.DOMDocument.3.0");try{xmlDoc.transformNodeToObject(xslDoc,result)}catch(e){result=
xmlDoc.transformNode(xslDoc)}}return result};dtmlXMLLoaderObject.prototype.doXSLTransToString=function(xslDoc,xmlDoc){var res=this.doXSLTransToObject(xslDoc,xmlDoc);if(typeof res=="string")return res;return this.doSerialization(res)};dtmlXMLLoaderObject.prototype.doSerialization=function(xmlDoc){if(!xmlDoc)xmlDoc=this.xmlDoc;if(xmlDoc.responseXML)xmlDoc=xmlDoc.responseXML;if(!_isIE){var xmlSerializer=new XMLSerializer;return xmlSerializer.serializeToString(xmlDoc)}else return xmlDoc.xml};
dhtmlxEventable=function(obj){obj.attachEvent=function(name,catcher,callObj){name="ev_"+name.toLowerCase();if(!this[name])this[name]=new this.eventCatcher(callObj||this);return name+":"+this[name].addEvent(catcher)};obj.callEvent=function(name,arg0){name="ev_"+name.toLowerCase();if(this[name])return this[name].apply(this,arg0);return true};obj.checkEvent=function(name){return!!this["ev_"+name.toLowerCase()]};obj.eventCatcher=function(obj){var dhx_catch=[];var z=function(){var res=true;for(var i=0;i<
dhx_catch.length;i++)if(dhx_catch[i]!=null){var zr=dhx_catch[i].apply(obj,arguments);res=res&&zr}return res};z.addEvent=function(ev){if(typeof ev!="function")ev=eval(ev);if(ev)return dhx_catch.push(ev)-1;return false};z.removeEvent=function(id){dhx_catch[id]=null};return z};obj.detachEvent=function(id){if(id!=false){var list=id.split(":");this[list[0]].removeEvent(list[1])}};obj.detachAllEvents=function(){for(var name in this)if(name.indexOf("ev_")==0)delete this[name]}};
function dhtmlxDblCalendarObject(contId,isAutoDraw,options){this.scriptName="dhtmlxcalendar.js";this.entObj=document.createElement("DIV");this.winHeader=null;this.style="dhtmlxdblcalendar";this.uid="sc&dblCal"+Math.round(1E6*Math.random());this.numLoaded=2;this.options={isWinHeader:false,headerText:"dhtmlxDblCalendarObject",headerButtons:"",isWinDrag:false,msgClose:"Close",msgMinimize:"Minimize",msgToday:"Today",msgClear:"Clear"};if(options)for(x in options)this.options[x]=options[x];this.entBox=
document.createElement("TABLE");this.entBox.cellPadding="0px";this.entBox.cellSpacing="0px";this.entBox.className=this.style;this.entObj.appendChild(this.entBox);var entRow=this.entBox.insertRow(0);var calLeft=entRow.insertCell(0);calLeft.style.paddingRight="2px";var calRight=entRow.insertCell(1);this.leftCalendar=new dhtmlxCalendarObject(calLeft,false,this.options);this.leftCalendar._dblC=this;this.leftCalendar.setOnClickHandler(this.doOnCLeftClick);this.rightCalendar=new dhtmlxCalendarObject(calRight,
false,this.options);this.rightCalendar._dblC=this;this.rightCalendar.setOnClickHandler(this.doOnCRightClick);this.doOnClick=null;this.onLanguageLoaded=null;this.getPosition=this.leftCalendar.getPosition;this.startDrag=this.leftCalendar.startDrag;this.stopDrag=this.leftCalendar.stopDrag;this.onDrag=this.leftCalendar.onDrag;this.drawHeader=this.leftCalendar.drawHeader;dhtmlxEventable(this);var self=this;if(typeof contId!="string")this.con=contId;else this.con=document.getElementById(contId);if(isAutoDraw)this.draw()}
dhtmlXDblCalendarObject=dhtmlxDblCalendarObject;dhtmlxDblCalendarObject.prototype.setHeader=function(isVisible,isDrag,btnsOpt){this.leftCalendar.options.isWinHeader=this.options.isWinHeader=isVisible;this.leftCalendar.options.isWinDrag=this.options.isWinDrag=isDrag;if(btnsOpt)this.options.headerButtons=this.leftCalendar.options.headerButtons=btnsOpt;if(this.isAutoDraw)this.drawHeader()};
dhtmlxDblCalendarObject.prototype.setYearsRange=function(minYear,maxYear){var cs=[this.leftCalendar,this.rightCalendar];for(var ind=0;ind<cs.length;ind++){cs[ind].options.yearsRange=[parseInt(minYear),parseInt(maxYear)];cs[ind].allYears=[];for(var i=minYear;i<=maxYear;i++)cs[ind].allYears.push(i)}};dhtmlxDblCalendarObject.prototype.show=function(){this.parent.style.display="block"};dhtmlxDblCalendarObject.prototype.hide=function(){this.parent.style.display="none"};
dhtmlxDblCalendarObject.prototype.createStructure=function(){if(this.options.isWinHeader){var headerRow=this.entBox.insertRow(0).insertCell(0);headerRow.colSpan=2;headerRow.align="right";this.winHeader=document.createElement("DIV");headerRow.appendChild(this.winHeader)}this.setParent(this.con)};dhtmlxDblCalendarObject.prototype.draw=function(){if(!this.parent)this.createStructure();this.drawHeader();this.leftCalendar.draw();this.rightCalendar.draw();this.isAutoDraw=true};
dhtmlxDblCalendarObject.prototype.loadUserLanguage=function(lang,userCBfunction){this.numLoaded=0;if(userCBfunction)this.onLanguageLoaded=userCBfunction;this.leftCalendar.loadUserLanguage(lang,this.languageLoaded);this.rightCalendar.loadUserLanguage(lang,this.languageLoaded)};
dhtmlxDblCalendarObject.prototype.languageLoaded=function(status){var self=this._dblC;self.numLoaded++;if(self.numLoaded==2){for(param in this.options)self.options[param]=this.options[param];if(this.isAutoDraw)self.drawHeader();if(self.onLanguageLoaded)self.onLanguageLoaded(status)}};dhtmlxDblCalendarObject.prototype.setParent=function(newParent){if(newParent){this.parent=newParent;this.parent.style.display="block";this.parent.appendChild(this.entObj)}};
dhtmlxDblCalendarObject.prototype.setOnClickHandler=function(func){this.doOnClick=func};dhtmlxDblCalendarObject.prototype.doOnCLeftClick=function(date){date=new Date(date);this._dblC.rightCalendar.setSensitive(date,null);if(this._dblC.doOnClick)this._dblC.doOnClick(date,this,"left");return true};dhtmlxDblCalendarObject.prototype.doOnCRightClick=function(date){date=new Date(date);this._dblC.leftCalendar.setSensitive(null,date);if(this._dblC.doOnClick)this._dblC.doOnClick(date,this,"right");return true};
dhtmlxDblCalendarObject.prototype.setSensitive=function(){this.rightCalendar.setSensitive(null,this.leftCalendar.date[0]);this.leftCalendar.setSensitive(this.rightCalendar.date[0],null)};dhtmlxDblCalendarObject.prototype.minimize=function(){if(!this.winHeader)return;var tr=this.winHeader.parentNode.parentNode.nextSibling;tr.parentNode.parentNode.style.width=parseInt(tr.parentNode.parentNode.offsetWidth)+"px";if(tr)tr.style.display=tr.style.display=="none"?"block":"none"};
dhtmlxDblCalendarObject.prototype.setDate=function(dateFrom,dateTo){this.leftCalendar.setDate(dateFrom);this.rightCalendar.setDate(dateTo);this.leftCalendar.setSensitive(null,this.rightCalendar.date[0]);this.rightCalendar.setSensitive(this.leftCalendar.date[0],null)};dhtmlxDblCalendarObject.prototype.setDateFormat=function(format){this.leftCalendar.setDateFormat(format);this.rightCalendar.setDateFormat(format)};
dhtmlxDblCalendarObject.prototype.isVisible=function(){return this.parent.style.display=="block"?true:false};dhtmlxDblCalendarObject.prototype.setHolidays=function(dates){this.leftCalendar.setHolidays(dates);this.rightCalendar.setHolidays(dates)};
function dhtmlxCalendarObject(base,isAutoDraw,options){if(typeof base=="object"&&base.parent){options={};for(i in base)options[i]=base[i]}this.isAutoDraw=base.autoDraw===false?false:isAutoDraw===false?false:true;this.contId=base.parent||base;this.scriptName="dhtmlxcalendar.js";this.date=[this.cutTime(new Date)];this.selDate=[this.cutTime(new Date)];this.curDate=this.cutTime(new Date);this.entObj=document.createElement("DIV");this.monthPan=document.createElement("TABLE");this.dlabelPan=document.createElement("TABLE");
this.daysPan=document.createElement("TABLE");this.parent=null;this.style="dhtmlxcalendar";this.skinName=dhtmlx.skin||"";this.doOnClick=null;this.sensitiveFrom=null;this.sensitiveTo=null;this.insensitiveDates=null;this.activeCell=null;this.hotCell=null;this.winHeader=null;this.onLanguageLoaded=null;this.dragging=false;this.minimized=false;this.uid="sc&Cal"+Math.round(1E6*Math.random());this.holidays=null;this.time=false;this.daysCells={};this.weekCells={};this.con=[];this.conInd=[];this.activeCon=
null;this.activeConInd=0;this.userPosition=false;this.useIframe=true;this._c=this;dhtmlxEventable(this);this.options={btnPrev:"&laquo;",btnBgPrev:null,btnNext:"&raquo;",btnBgNext:null,yearsRange:[1900,2100],isMonthEditable:false,isYearEditable:false,isWinHeader:false,headerText:"Calendar header",headerButtons:"TMX",isWinDrag:true};defLeng={langname:"en-us",dateformat:"%Y-%m-%d",monthesFNames:["January","February","March","April","May","June","July","August","September","October","November","December"],
monthesSNames:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],daysFNames:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],daysSNames:["Su","Mo","Tu","We","Th","Fr","Sa"],weekend:[0,6],weekstart:0,msgClose:"Close",msgMinimize:"Minimize",msgToday:"Today",msgClear:"Clear"};if(!window.dhtmlxCalendarLangModules)window.dhtmlxCalendarLangModules={};window.dhtmlxCalendarLangModules["en-us"]=defLeng;if(window.dhtmlxCalendarObjects)window.dhtmlxCalendarObjects.push(this);
else window.dhtmlxCalendarObjects=[this];dhtmlxEvent(document.body,"click",function(ev){for(var i=0;i<window.dhtmlxCalendarObjects.length;i++){var wCal=window.dhtmlxCalendarObjects[i];if(wCal.con[0].nodeName=="INPUT")wCal.hide()}});for(lg in defLeng)this.options[lg]=defLeng[lg];if(options)for(param in options)this.options[param]=options[param];this.loadUserLanguage();if(options)for(param in options)this.options[param]=options[param];this.allYears=Array();with(this.options)for(var i=yearsRange[0];i<=
yearsRange[1];i++)this.allYears.push(i);if(this.isAutoDraw!==false)this.draw(options);return this}dhtmlXCalendarObject=dhtmlxCalendarObject;
dhtmlxCalendarObject.prototype={createStructure:function(){var self=this;if(!this.entObj.className)this.setSkin(this.skinName);this.entObj.style.position="relative";if(this.options.isWinHeader){this.winHeader=document.createElement("DIV");this.entObj.appendChild(this.winHeader)}this.entBox=document.createElement("TABLE");this.entBox.className="entbox";with(this.entBox){cellPadding="0px";cellSpacing="0px";width="100%"}this.entObj.appendChild(this.entBox);var monthBox=this.entBox.insertRow(0).insertCell(0);
with(this.monthPan){cellPadding="0px";cellSpacing="0px";width="100%";align="center"}this.monthPan.className="dxcalmonth";monthBox.appendChild(this.monthPan);var dlabelBox=this.entBox.insertRow(1).insertCell(0);dlabelBox.appendChild(this.dlabelPan);with(this.dlabelPan){cellPadding="0px";cellSpacing="0px";width="100%";align="center"}this.dlabelPan.className="dxcaldlabel";var daysBox=this.entBox.insertRow(2).insertCell(0);daysBox.appendChild(this.daysPan);with(this.daysPan){cellPadding="1px";cellSpacing=
"0px";width="100%";align="center"}if(_isIE||_isKHTML)this.daysPan.className="dxcaldays_ie";else this.daysPan.className="dxcaldays";this.daysPan.onmousemove=function(e){self.doHotKeys(e)};this.daysPan.onmouseout=function(){self.endHotKeys()};if(typeof this.contId!="string")if(!this.contId.nodeName)for(var i=0;i<this.contId.length;i++){this.con[i]=document.getElementById(this.contId[i]);this.selDate[i]=this.cutTime(new Date);this.conInd[this.contId[i]]=i}else{this.con[0]=this.contId;this.conInd[this.contId.id]=
0}else{this.con[0]=document.getElementById(this.contId);this.conInd[this.contId]=0}this.activeCon=this.con[0];if(this.con[0].nodeName=="INPUT"){var div=document.createElement("DIV");with(div.style){position="absolute";display="none";zIndex=5101}this.setParent(div);document.body.appendChild(div);conOnclick=function(e){if(self.isVisible())self.hide();else{self.activeCon=this;if(this.value)self.setFormatedDate(null,this.value);else if(self.time)self.tp.reset();self.show(this.id);self.draw()}if(this.id!=
self.activeCon.id){self.show(this.id);self.draw()}(e||event).cancelBubble=true};this.doOnClick=function(date){self.hide();self.activeCon.focus();return true};conOnkeydown=function(e){if((e||window.event).keyCode==27)self.hide();else if((e||window.event).keyCode==13)self.show()};for(i in this.con){this.con[i].onclick=conOnclick;this.con[i].onkeydown=conOnkeydown}}else this.setParent(this.con[0]);if(_isIE&&this.useIframe){if(this.parent.style.zIndex==0)this.parent.style.zIndex=100;if(this.ifr==undefined&&
this._dblC==undefined){this.ifr=document.createElement("IFRAME");this.ifr.src="javascript:'';";this.ifr.style.position="absolute";this.ifr.style.zIndex=1;this.ifr.frameBorder="no";this.ifr.style.top=getAbsoluteTop(this.entObj)+"px";this.ifr.scrolling="no";this.ifr.style.display=this.parent.style.display;this.ifr.className=this.style+(this.skinName?"_":"")+this.skinName+"_ifr";this.parent.appendChild(this.ifr)}}this.entObj.onclick=function(e){e=e||event;if(e.stopPropagation)e.stopPropagation();else e.cancelBubble=
true};if(!this.entObj.className)this.setSkin(this.skinName)},drawHeader:function(){if(this._dblC||!this.options.isWinHeader||!this.winHeader)return;var self=this;while(this.winHeader.hasChildNodes())this.winHeader.removeChild(this.winHeader.firstChild);this.winHeader.className="winHeader";this.winHeader.onselectstart=function(){return false};this.headerLabel=document.createElement("div");this.headerLabel.className="winTitle";this.headerLabel.appendChild(document.createTextNode(this.options.headerText));
this.headerLabel.setAttribute("title",this.options.headerText);this.winHeader.appendChild(this.headerLabel);if(this.options.isWinDrag)this.winHeader.onmousedown=function(e){self.startDrag(e)};if(this.options.headerButtons.indexOf("X")>=0){var btnClose=document.createElement("DIV");btnClose.className="btn_close";btnClose.setAttribute("title",this.options.msgClose);btnClose.onmousedown=function(e){(e||event).cancelBubble=true};btnClose.onclick=function(e){(e||event).cancelBubble=true;self.hide()};this.winHeader.appendChild(btnClose)}if(this.options.headerButtons.indexOf("M")>=
0){var btnMin=document.createElement("DIV");btnMin.className="btn_mini";btnMin.setAttribute("title",this.options.msgMinimize);btnMin.onmousedown=function(e){(e||event).cancelBubble=true};btnMin.onclick=function(e){this.className=this.className=="btn_mini"?"btn_maxi":"btn_mini";(e||event).cancelBubble=true;self.minimize()};this.winHeader.appendChild(btnMin)}if(this.options.headerButtons.indexOf("C")>=0){var btnClear=document.createElement("DIV");btnClear.className="btn_clear";btnClear.setAttribute("title",
this.options.msgClear);btnClear.onmousedown=function(e){(e||event).cancelBubble=true};btnClear.onclick=function(e){(e||event).cancelBubble=true;self.activeCon.value="";self.hide()};this.winHeader.appendChild(btnClear)}if(this.options.headerButtons.indexOf("T")>=0){var btnToday=document.createElement("DIV");btnToday.className="btn_today";btnToday.setAttribute("title",this.options.msgToday);btnToday.onmousedown=function(e){(e||event).cancelBubble=true};btnToday.onclick=function(e){(e||event).cancelBubble=
true;self.setDate(new Date)};this.winHeader.appendChild(btnToday)}},drawMonth:function(){var self=this;if(this.monthPan.hasChildNodes())this.monthPan.removeChild(this.monthPan.firstChild);var row=this.monthPan.insertRow(0);var cArLeft=row.insertCell(0);var cContent=row.insertCell(1);var cArRight=row.insertCell(2);cArLeft.align="left";cArLeft.className="month_btn_left";var btnLabel=document.createElement("div");btnLabel.innerHTML=" ";cArLeft.appendChild(btnLabel);cArLeft.onclick=function(){self.prevMonth()};
cArLeft.onselectstart=function(){return false};cArRight.align="right";cArRight.className="month_btn_right";var btnLabel=document.createElement("div");btnLabel.innerHTML=" ";cArRight.appendChild(btnLabel);cArRight.onclick=function(){self.nextMonth()};cArRight.onselectstart=function(){return false};cContent.align="center";var mHeader=document.createElement("TABLE");with(mHeader){cellPadding="0px";cellSpacing="0px";align="center"}var mRow=mHeader.insertRow(0);var cMonth=mRow.insertCell(0);var cComma=
mRow.insertCell(1);var cYear=mRow.insertCell(2);cContent.appendChild(mHeader);var date=this.date[0];this.planeMonth=document.createElement("DIV");this.planeMonth._c=this;this.planeMonth.appendChild(document.createTextNode(this.options.monthesFNames[date.getMonth()]));this.planeMonth.className="planeMonth";cMonth.appendChild(this.planeMonth);if(this.options.isMonthEditable){this.planeMonth.style.cursor="pointer";this.editorMonth=new dhtmlxRichSelector({nodeBefore:this.planeMonth,valueList:[0,1,2,3,
4,5,6,7,8,9,10,11],titleList:this.options.monthesFNames,activeValue:this.options.monthesFNames[date.getMonth()],onSelect:this.onMonthSelect,isAllowUserValue:false});this.editorMonth._c=this}cComma.appendChild(document.createTextNode(","));cComma.className="comma";this.planeYear=document.createElement("DIV");this.planeYear._c=this;this.planeYear.appendChild(document.createTextNode(date.getFullYear()));this.planeYear.className="planeYear";cYear.appendChild(this.planeYear);if(this.options.isYearEditable){this.planeYear.style.cursor=
"pointer";this.editorYear=new dhtmlxRichSelector({nodeBefore:this.planeYear,valueList:this.allYears,titleList:this.allYears,activeValue:date.getFullYear(),onSelect:this.onYearSelect,isOrderedList:true,isNumbersList:true,isAllowUserValue:true});this.editorYear._c=this}},drawDayLabels:function(){var self=this;if(!this.dlabelPan.hasChildNodes()){var row=this.dlabelPan.insertRow(-1);row.className="daynames";for(var i=0;i<7;i++)(this.weekCells[i]=row.insertCell(i)).appendChild(document.createTextNode(this.getDayName(i)))}else for(var i=
0;i<7;i++)this.weekCells[i].childNodes[0].nodeValue=this.getDayName(i)},drawDays:function(){var self=this;var row={},cell;if(!this.daysPan.hasChildNodes())for(var weekNumber=0;weekNumber<6;weekNumber++){row=this.daysPan.insertRow(-1);this.daysCells[weekNumber]={};for(var i=0;i<7;i++)(this.daysCells[weekNumber][i]=row.insertCell(-1)).appendChild(document.createTextNode(""))}var date=this.date[0],tempDate=new Date(date);var selectedDate=this.selDate[this.activeConInd].toDateString();tempDate.setDate(1);
var day1=(tempDate.getDay()-this.options.weekstart)%7;if(day1<=0)day1+=7;tempDate.setDate(-day1);tempDate.setDate(tempDate.getDate()+1);if(tempDate.getDate()<tempDate.getDay())tempDate.setMonth(tempDate.getMonth()-1);var curDay=null;for(var weekNumber=0;weekNumber<6;weekNumber++)for(var i=0;i<7;i++){if(curDay==tempDate.getDate())tempDate.setDate(tempDate.getDate()+1);curDay=tempDate.getDate();cell=this.daysCells[weekNumber][i];cell.setAttribute("id",this.uid+tempDate.getFullYear()+tempDate.getMonth()+
tempDate.getDate());cell.childNodes[0].nodeValue=tempDate.getDate();cell.thisdate=tempDate.toString();cell.className="thismonth";cell.onclick=null;if(tempDate.getMonth()!=date.getMonth())cell.className="othermonth";if(this.insensitiveDates){var c=false;for(var j=0;j<this.insensitiveDates.length;j++){var s=/\.|\-/.exec(this.insensitiveDates[j]);if(s)var f=this.insensitiveDates[j].split(s).length==2?"%m"+s+"%d":"%Y"+s+"%m"+s+"%d";if(s&&this.getFormatedDate(f,tempDate)==this.insensitiveDates[j]||tempDate.getDay()==
this.insensitiveDates[j]){this.addClass(cell,"insensitive");tempDate.setDate(tempDate.getDate()+1);c=true;break}}if(c)continue}if(this.sensitiveFrom&&this.sensitiveFrom instanceof Array){var c=true;for(var j=0;j<this.sensitiveFrom.length;j++){var s=/\.|\-/.exec(this.sensitiveFrom[j]);var f=this.sensitiveFrom[j].split(s).length==2?"%m"+s+"%d":"%Y"+s+"%m"+s+"%d";if(this.getFormatedDate(f,tempDate)==this.sensitiveFrom[j])c=false}if(c){this.addClass(cell,"insensitive");tempDate.setDate(tempDate.getDate()+
1);continue}}if(this.sensitiveFrom&&tempDate.valueOf()<this.sensitiveFrom.valueOf()||this.sensitiveTo&&tempDate.valueOf()>this.sensitiveTo.valueOf()){this.addClass(cell,"insensitive");tempDate.setDate(tempDate.getDate()+1);continue}if(this.isWeekend(i)&&tempDate.getMonth()==date.getMonth())cell.className="weekend";if(tempDate.toDateString()==this.curDate.toDateString())this.addClass(cell,"current");if(tempDate.toDateString()==selectedDate){this.activeCell=cell;this.addClass(cell,"selected")}if(this.holidays)for(var j=
0;j<this.holidays.length;j++){var s=/\.|\-/.exec(this.holidays[j]);var f=this.holidays[j].split(s).length==2?"%m"+s+"%d":"%Y"+s+"%m"+s+"%d";if(this.getFormatedDate(f,tempDate)==this.holidays[j])this.addClass(cell,"holiday")}cell.onclick=function(){var date=new Date(this.thisdate);self.setDate(date);if(!self.doOnClick||self.doOnClick(date))self.callEvent("onClick",[date])};tempDate.setDate(tempDate.getDate()+1)}},draw:function(){if(!this.parent)this.createStructure();var self=this;if(this.loadingLanguage){setTimeout(function(){self.draw();
return},20);return}this.drawHeader();this.drawMonth();this.drawDayLabels();this.drawDays();this.isAutoDraw=true},loadUserLanguage:function(language,userCBfunction){if(userCBfunction)this.onLanguageLoaded=userCBfunction;if(!language)language="en-us";this.loadingLanguage=language;if(!language){this.loadUserLanguageCallback(false);return}if(language==this.options.langname){this.loadUserLanguageCallback(true);return}var __lm=window.dhtmlxCalendarLangModules;if(__lm[language]){for(lg in __lm[language])this.options[lg]=
__lm[language][lg];this.loadUserLanguageCallback(true);return}var src,path=null;var scripts=document.getElementsByTagName("SCRIPT");for(var i=0;i<scripts.length;i++)if(src=scripts[i].getAttribute("src"))if(src.indexOf(this.scriptName)>=0){path=src.substr(0,src.indexOf(this.scriptName));break}if(path===null){this.loadUserLanguageCallback(false);return}this.options.langname=language;var langPath=path+"lang/"+language+".js";for(var i=0;i<scripts.length;i++)if(src=scripts[i].getAttribute("src"))if(src==
langPath)return;var script=document.createElement("SCRIPT");script.setAttribute("language","Java-Script");script.setAttribute("type","text/javascript");script.setAttribute("src",langPath);document.body.appendChild(script)},loadUserLanguageCallback:function(status){this.loadingLanguage=null;if(this.isAutoDraw)this.draw();if(this.onLanguageLoaded&&typeof this.onLanguageLoaded=="function")this.onLanguageLoaded(status)},loadLanguageModule:function(langModule){var __c=window.dhtmlxCalendarObjects;for(var i=
0;i<__c.length;i++)if(__c[i].loadingLanguage==langModule.langname){for(lg in langModule)__c[i].options[lg]=langModule[lg];__c[i].loadUserLanguageCallback(true)}window.dhtmlxCalendarLangModules[langModule.langname]=langModule},show:function(conId){this.activeCon=this.con[this._activeConInd(conId)];this.parent.style.display="";this.parent.style.visibility="hidden";if(this.activeCon.nodeName=="INPUT"&&!this.userPosition){if(typeof window.innerWidth=="number"){docWidth=window.innerWidth;docHeight=window.innerHeight}else{docWidth=
document.body.offsetWidth;docHeight=document.body.offsetHeight}var aLeft=getAbsoluteLeft(this.activeCon);var aTop=getAbsoluteTop(this.activeCon);if(aTop+this.parent.offsetHeight>docHeight&&this.parent.offsetHeight<aTop)this.parent.style.top=aTop-this.parent.offsetHeight+this.activeCon.offsetHeight+"px";else this.parent.style.top=aTop+"px";if(aLeft+this.parent.offsetWidth+this.activeCon.offsetWidth>docWidth)this.parent.style.left=aLeft+"px";else this.parent.style.left=aLeft+this.activeCon.offsetWidth+
"px"}if(this.ifr!=undefined){this.ifr.style.top=this.entObj.offsetTop+"px";this.ifr.style.left=this.entObj.offsetLeft+"px";this.ifr.style.display="block"}if(this.time&&!this.minimized){this.tp.setPosition(getAbsoluteLeft(this.parent)+30,getAbsoluteTop(this.parent)+147);this.tp.show()}this.parent.style.visibility="visible";return this},hide:function(){this.parent.style.display="none";if(this.ifr!=undefined)this.ifr.style.display="none";if(this.time)this.tp.hide();return this},setDateFormat:function(format){this.options.dateformat=
format},cutTime:function(date){date=new Date(date);var ndate=new Date(date.getFullYear(),date.getMonth(),date.getDate(),1,1);return ndate},setParent:function(newParent){if(newParent){this.parent=newParent;this.parent.appendChild(this.entObj)}},setDate:function(date,conId){tmpDate=date;conId=this._activeConInd(conId);this.activeCon=this.con[conId];if(typeof date!="Object")date=this.setFormatedDate(null,tmpDate);if(isNaN(date)||!date)date=new Date;this.date[conId]=new Date(this.cutTime(date));this.selDate[conId]=
new Date(this.cutTime(date));if(this.isAutoDraw)this.draw();if(this.activeCon.nodeName=="INPUT")this.activeCon.value=!tmpDate?"":this.getFormatedDate(this.options.dateformat,date)},addClass:function(obj,styleName){obj.className+=" "+styleName},resetClass:function(obj){obj.className=obj.className.toString().split(" ")[0]},resetHotClass:function(obj){obj.className=obj.className.toString().replace(/hover/,"")},setSkin:function(newSkin){this.skinName=newSkin;var mode="";mode=this.minimized?"_mini":this.time?
"_long":this.options.isWinHeader?"_maxi":"";this.entObj.className=this.style+(newSkin?"_"+newSkin:"");if(mode)this.entObj.className+=" "+this.entObj.className+mode;if(this.ifr!=undefined)this.ifr.className=this.style+(newSkin?"_"+newSkin:"")+mode+"_ifr";if(this.time)this.isVisible()&&!this.minimized?this.tp.show():this.tp.hide()},getDate:function(conId){return this.selDate[this._activeConInd(conId)].toString()},nextMonth:function(){var date=this.date[0],month;date.setDate(1);date.setMonth(month=date.getMonth()+
1);this.callEvent("onChangeMonth",[month+1>12?1:month+1,month||12]);if(this.isAutoDraw)this.draw()},prevMonth:function(){var date=this.date[0],month;date.setDate(1);date.setMonth(month=date.getMonth()-1);this.callEvent("onChangeMonth",[month+1||12,month+2>12?1:month+2||12]);if(this.isAutoDraw)this.draw()},setOnClickHandler:function(func){this.attachEvent("onClick",func)},getFormatedDate:function(dateformat,date,conInd){if(!dateformat)dateformat=this.options.dateformat;if(!date)date=this.selDate[this._activeConInd(conInd)];
date=new Date(date);var out="";var plain=true;for(var i=0;i<dateformat.length;i++){var replStr=dateformat.substr(i,1);if(plain){if(replStr=="%"){plain=false;continue}out+=replStr}else{switch(replStr){case "e":replStr=date.getDate();break;case "d":replStr=date.getDate();if(replStr.toString().length==1)replStr="0"+replStr;break;case "j":var x=new Date(date.getFullYear(),0,0,0,0,0,0);replStr=Math.ceil((date.valueOf()-x.valueOf())/1E3/60/60/24-1);while(replStr.toString().length<3)replStr="0"+replStr;
break;case "a":replStr=this.options.daysSNames[date.getDay()];break;case "W":replStr=this.options.daysFNames[date.getDay()];break;case "c":replStr=1+date.getMonth();break;case "m":replStr=1+date.getMonth();if(replStr.toString().length==1)replStr="0"+replStr;break;case "b":replStr=this.options.monthesSNames[date.getMonth()];break;case "M":replStr=this.options.monthesFNames[date.getMonth()];break;case "y":replStr=date.getFullYear();replStr=replStr.toString().substr(2);break;case "Y":replStr=date.getFullYear();
break;case "H":case "h":case "i":case "s":case "f":if(this.time)replStr=this.tp.getFormatedTime("%"+replStr,arguments[2]);break}out+=replStr;plain=true}}return out},setFormatedDate:function(dateformatarg,date,conInd,skip){if(!date||!(typeof date=="string"))return date;if(date=="0000-00-00"){this.setDate(new Date,conInd);return new Date}if(!dateformatarg)dateformatarg=this.options.dateformat;if(this.time)this.tp.setFormatedTime(dateformatarg,date);function parseMonth(val){var tmpAr=new Array(this.options.monthesSNames,
this.options.monthesFNames);for(var j=0;j<tmpAr.length;j++)for(var i=0;i<tmpAr[j].length;i++)if(tmpAr[j][i].indexOf(val)==0)return i;return-1}var outputDate=new Date(2008,0,1);var j=0;for(var i=0;i<dateformatarg.length;i++){var _char=dateformatarg.charAt(i);if(_char=="%"){var _cd=dateformatarg.charAt(i+1);var _nextpc=dateformatarg.indexOf("%",i+1);var _nextDelim=dateformatarg.substr(i+2,_nextpc-i-1-1);var _nDelimInDatePos=date.indexOf(_nextDelim,j);if(_nextDelim=="")_nDelimInDatePos=date.length;if(_nDelimInDatePos==
-1)return null;var value=date.substr(j,_nDelimInDatePos-j);if(_cd!="M"&&_cd!="b")value=parseFloat(value);j=_nDelimInDatePos+_nextDelim.length;switch(_cd){case "d":case "e":outputDate.setDate(parseFloat(value));break;case "c":case "m":outputDate.setMonth(parseFloat(value)-1);break;case "M":var val=parseMonth.call(this,value);if(val!=-1)outputDate.setMonth(parseFloat(val));else return null;break;case "b":var val=parseMonth.call(this,value);if(val!=-1)outputDate.setMonth(parseFloat(val));else return null;
break;case "Y":outputDate.setFullYear(parseFloat(value));break;case "y":var year=parseFloat(value);outputDate.setFullYear((year>20?1900:2E3)+year);break}}}if(isNaN(outputDate))outputDate=new Date(this.selDate[this._activeConInd]);if(skip)return outputDate;this.setDate(outputDate,conInd);return this.selDate[this.activeConInd]},isWeekend:function(k){var q=k+this.options.weekstart;if(q>6)q-=7;for(var i=0;i<this.options.weekend.length;i++)if(this.options.weekend[i]==q)return true;return false},getDayName:function(k){var q=
k+this.options.weekstart;if(q>6)q=q-7;return this.options.daysSNames[q]},isVisible:function(){return this.parent.style.display!="none"},doHotKeys:function(e){e=e||event;var cell=e.target||e.srcElement;if(cell.className.toString().indexOf("insensitive")>=0)this.endHotKeys();else{if(this.hotCell)this.resetHotClass(this.hotCell);this.addClass(cell,"hover");this.hotCell=cell}},endHotKeys:function(){if(this.hotCell){this.resetHotClass(this.hotCell);this.hotCell=null}},_activeConInd:function(ind){if(!this.parent)this.createStructure();
return this.activeConInd=(this.conInd[ind]==0?"0":this.conInd[ind])||(ind==0?"0":ind)||this.conInd[this.activeCon.id]||0}};
function dhtmlxRichSelector(parametres){for(x in parametres)this[x]=parametres[x];this.initValue=this.activeValue;if(!this.selectorSize)this.selectorSize=7;var self=this;this.blurTimer=null;this.nodeBefore.onclick=function(){self.show()};this.editor=document.createElement("TEXTAREA");this.editor.value=this.activeValue;this.editor._s=this;this.editor.className="dhtmlxRichSelector";this.editor.onfocus=this.onFocus;this.editor.onblur=this.onBlur;this.selector=document.createElement("SELECT");this.selector.size=
this.selectorSize;this.selector.className="dhtmlxRichSelector";if(this.valueList)for(var i=0;i<this.valueList.length;i++)this.selector.options[i]=new Option(this.titleList[i],this.valueList[i],false,false);this.selector._s=this;this.selector.onfocus=this.onFocus;this.selector.onblur=this.onBlur;this.selector.onclick=function(){window.t=self;self.onSelect(self.selector.value);clearTimeout(self.blurTimer)};this.selector.getIndexByValue=function(Value,isFull){var Select=this;Value=Value.toString().toUpperCase();
if(!isFull)isFull=false;for(var i=0;i<Select.length;i++){var i_value=Select[i].text.toUpperCase();if(isFull){if(i_value==Value)return i}else if(i_value.indexOf(Value)==0)return i}if(Select._s.isOrderedList){if(Select._s.isNumbersList)if(isNaN(Value))return-1;i_value=Select[0].text.substring(0,Value.length).toUpperCase();if(i_value>Value)return 0;i_value=Select[Select.length-1].text.substring(0,Value.length);if(i_value<Value)return Select.length-1}return-1};this.con=document.createElement("DIV");this.con.className=
"dhtmlxRichSelector";with(this.con.style){width="auto";display="none"}this.con.appendChild(this.editor);this.con.appendChild(this.selector);this.nodeBefore.parentNode.insertBefore(this.con,this.nodeBefore);return this}
dhtmlxRichSelector.prototype.show=function(){this.con.style.display="block";with(this.selector.style){marginTop=parseInt(this.nodeBefore.offsetHeight)+"px";width="auto"}with(this.editor.style){width=parseInt(this.nodeBefore.offsetWidth)+15+"px";height=parseInt(this.nodeBefore.offsetHeight)+"px"}this.selector.selectedIndex=this.selector.getIndexByValue(this.activeValue);this.editor.focus()};dhtmlxRichSelector.prototype.hide=function(){this.con.style.display="none"};
dhtmlxRichSelector.prototype.onBlur=function(){var self=this._s;self.blurTimer=setTimeout(function(){if(self.isAllowUserValue){if(self.onSelect(self.editor.value))self.activeValue=self.editor.value}else if(self.onSelect(self.selector.value))self.activeValue=self.selector.value},10)};dhtmlxRichSelector.prototype.onFocus=function(){var self=this._s;if(self.blurTimer){clearTimeout(self.blurTimer);self.blurTimer=null}if(this===this._s.selector)self.editor.focus()};
dhtmlxCalendarObject.prototype.setHeader=function(isVisible,isDrag,btnsOpt){with(this.options){isWinHeader=isVisible;isWinDrag=isDrag;if(btnsOpt)headerButtons=btnsOpt}this.setSkin(this.skinName)};dhtmlxCalendarObject.prototype.setYearsRange=function(minYear,maxYear){this.options.yearsRange=[parseInt(minYear),parseInt(maxYear)];this.allYears=[];for(var i=minYear;i<=maxYear;i++)this.allYears.push(i)};
dhtmlxCalendarObject.prototype.startDrag=function(e){e=e||event;if(e.button===0||e.button===1){if(this.dragging)this.stopDrag(e);this.drag_mx=e.clientX;this.drag_my=e.clientY;this.drag_spos=this.getPosition(this.parent);document.body.appendChild(this.parent);with(this.parent.style){left=this.drag_spos[0]+"px";top=this.drag_spos[1]+"px";margin="0px";position="absolute"}if(this.ifr){this.ifr.style.top="0px";this.ifr.style.left="0px"}this.bu_onmousemove=document.body.onmousemove;var self=this;document.body.onmousemove=
function(e){self.onDrag(e)};this.bu_onmouseup=document.body.onmouseup;document.body.onmouseup=function(e){self.stopDrag(e)};this.dragging=true}};
dhtmlxCalendarObject.prototype.onDrag=function(e){e=e||event;if(e.button===0||e.button===1){var delta_x=this.drag_mx-e.clientX;var delta_y=this.drag_my-e.clientY;this.parent.style.left=this.drag_spos[0]-delta_x+"px";this.parent.style.top=this.drag_spos[1]-delta_y+"px";if(this.time)this.tp.setPosition(getAbsoluteLeft(this.parent)+30,getAbsoluteTop(this.parent)+160);if(this.ifr!=undefined){this.ifr.style.left=0;this.ifr.style.top=0}}else this.stopDrag(e)};
dhtmlxCalendarObject.prototype.stopDrag=function(e){e=e||event;document.body.onmouseup=this.bu_onmouseup===window.undefined?null:this.bu_onmouseup;document.body.onmousemove=this.bu_onmousemove===window.undefined?null:this.bu_onmousemove;this.dragging=false};dhtmlxCalendarObject.prototype.minimize=function(){if(!this.winHeader)return;this.minimized=!this.minimized;this.entBox.style.display=!this.minimized?"":"none";this.setSkin(this.skinName)};
dhtmlxCalendarObject.prototype.onYearSelect=function(value){if(!isNaN(value))this._c.date[0].setFullYear(Math.min(Math.max(value,this._c.allYears[0]),this._c.allYears.slice(-1)));this._c.draw();return!isNaN(value)};dhtmlxCalendarObject.prototype.onMonthSelect=function(value){this._c.date[0].setMonth(value);this._c.draw();return true};
dhtmlxCalendarObject.prototype.setPosition=function(argA,argB,argC){if(typeof argA=="object"){var posAr=this.getPosition(argA);var left=posAr[0]+argA.offsetWidth+(argC||0);var top=posAr[1]+(argB||0)}this.parent.style.position="absolute";this.parent.style.top=(top||argA)+"px";this.parent.style.left=(left||argB)+"px";if(this.ifr!=undefined){this.ifr.style.left="0px";this.ifr.style.top="0px"}if(this.time)this.tp.setPosition(getAbsoluteLeft(this.parent)+30,getAbsoluteTop(this.parent)+160)};
dhtmlxCalendarObject.prototype.close=function(func){this.hide()};
dhtmlxCalendarObject.prototype.getPosition=function(oNode,pNode){if(!pNode)var pNode=document.body;var oCurrentNode=oNode;var iLeft=0;var iTop=0;while(oCurrentNode&&oCurrentNode!=pNode){iLeft+=oCurrentNode.offsetLeft-oCurrentNode.scrollLeft;iTop+=oCurrentNode.offsetTop-oCurrentNode.scrollTop;oCurrentNode=oCurrentNode.offsetParent}if(pNode==document.body)if(_isIE){if(document.documentElement.scrollTop)iTop+=document.documentElement.scrollTop;if(document.documentElement.scrollLeft)iLeft+=document.documentElement.scrollLeft}else if(!_isFF){iLeft+=
document.body.offsetLeft;iTop+=document.body.offsetTop}return new Array(iLeft,iTop)};dhtmlxCalendarObject.prototype.setSensitive=function(fromDate,toDate){if(fromDate)if(fromDate instanceof Date)this.sensitiveFrom=this.cutTime(fromDate);else this.sensitiveFrom=fromDate.toString().split(",");if(toDate)this.sensitiveTo=this.cutTime(toDate);if(this.isAutoDraw)this.draw()};dhtmlxCalendarObject.prototype.setHolidays=function(dates){this.holidays=dates.toString().split(",");if(this.isAutoDraw)this.draw()};
dhtmlxCalendarObject.prototype.onChangeMonth=function(func){this.attachEvent("onChangeMonth",func)};dhtmlxCalendarObject.prototype.setInsensitiveDates=function(dates){this.insensitiveDates=dates.toString().split(",");if(this.isAutoDraw)this.draw()};
dhtmlxCalendarObject.prototype.enableTime=function(mode){if(this.time=mode){this.tp=new dhtmlXTimePicker;this.tp.setPosition(getAbsoluteLeft(this.parent)+30,getAbsoluteTop(this.parent)+160);for(m in dhtmlXTimePicker.prototype)(function(m){if(!dhtmlxCalendarObject.prototype[m])dhtmlxCalendarObject.prototype[m]=function(){return this.tp[m].apply(this.tp,arguments)}})(m)}else{this.tp.entBox.parentNode.removeChild(this.tp.entBox);this.tp=null}this.setSkin(this.skinName)};
dhtmlxCalendarObject.prototype.setHeaderText=function(text){this.options.headerText=text;if(this.headerLabel){this.headerLabel.childNodes[0].nodeValue=text;this.headerLabel.setAttribute("title",text)}};dhtmlxCalendarObject.prototype.disableIESelectFix=function(mode){this.useIframe=!mode;if(this.ifr!=undefined){this.ifr.parentNode.removeChild(this.ifr);this.ifr=null}};
BrainstormJs.Controls.DataFilters.Input.TextBox=Class.create(BrainstormJs.Controls.DataFilters.Input.BaseDataFilterInput,{input:false,emptyText:false,validation:false,numbersOnly:false,dateOnly:false,calendar:false,errorMessages:["Nope","Keep Trying","Nadda","Sorry","Oops","Arg","Bummer","Whoops","Ouch","Shucks","Try Again","I'm Winning","Snafu","Really?"],correctValue:false,initialize:function($super,container,editor,options){$super(container,editor,options);this.input=this.container.down("input.textBox");
this.input.identify();this.validation=this.container.down("span.validation");this.emptyText=this.input.value;this.numbersOnly=this.input.hasClassName("numbersOnly");this.dateOnly=this.input.hasClassName("dateOnly");if(this.dateOnly){this.calendar=new dhtmlxCalendarObject(this.input.id);this.calendar.attachEvent("onClick",this.onCalendarClick.bind(this))}else{this.input.observe("keyup",function(e){this.onType(e)}.bind(this));this.input.observe("focus",this.onFocus.bind(this));this.input.observe("blur",
this.onBlur.bind(this))}this.input.observe("keypress",function(e){this.onKeyPress(e)}.bind(this))},onKeyPress:function(e){if(e.keyCode==Event.KEY_RETURN)e.stop()},onType:function(e){var value=this.input.value.strip();var valid=false;var validMessage=false;if(value.length>0)if(this.numbersOnly){var number=parseInt(value);if(!isNaN(number)){this.correctValue=number;validMessage="Looks good ...";valid=true}}else{this.correctValue=value;validMessage="Looks good ...";valid=true}if(valid)this.setMessage(validMessage,
true);else{var index=Math.min(Math.round(this.errorMessages.length*Math.random()),this.errorMessages.length-1);var message=this.errorMessages[index];this.setMessage(message.endsWith("?")?message:message+"...",false)}this.getEditor().toggleCreateButton(valid)},setMessage:function(text,isValid){this.validation.innerHTML=text;if(isValid){this.validation.removeClassName("invalidValue");this.validation.addClassName("validValue")}else{this.validation.removeClassName("validValue");this.validation.addClassName("invalidValue")}if(!this.validation.visible())this.validation.appear({duration:0.5})},
onFocus:function(e){if(this.input.value===this.emptyText)this.input.value=""},onBlur:function(e){if(this.input.value===""){this.input.value=this.emptyText;this.validation.hide();this.validation.innerHTML=""}},onCalendarClick:function(date){var dateObj=new Date(date);this.correctValue=dateObj;this.getEditor().toggleCreateButton(true)},getValue:function(){return this.correctValue},destroy:function(){this.input.stopObserving();this.input=false}});
BrainstormJs.Controls.DataFilters.Input.TagList=Class.create(BrainstormJs.Controls.DataFilters.Input.BaseDataFilterInput,{tagInput:false,initialize:function($super,container,editor,options){$super(container,editor,options);this.tagInput=new BrainstormJs.Forms.Fields.MultiSelect.TagSelect({});container.insert(this.tagInput.render());this.tagInput.afterRender();this.getEditor().toggleCreateButton(true)},getValue:function(){return this.tagInput.getValue()},destroy:function(){this.tagInput=false}});
BrainstormJs.Controls.DataFilters.DataFilterEditor=Class.create({container:false,baseGrid:false,options:false,gridType:false,parentProfileId:false,filterBox:false,noFiltersDiv:false,filtersDiv:false,addContainer:false,addIntroText:false,propertyListDiv:false,operatorListDiv:false,valueInputArea:false,createButton:false,cancelLink:false,propertySelect:false,operatorSelect:false,buttonsDiv:false,addFilterLink:false,clearAllLink:false,saveSetLink:false,saveFormContainer:false,saveSetForm:false,loadSetLink:false,
savedViewsMenu:false,fxOnPropertyChanged:false,fxOnOperatorChanged:false,selectedProperty:false,selectedOperatorIndex:false,selectedOperator:false,dataInput:false,filterCount:false,summaryDiv:false,savedViewMode:false,recordCount:0,initialize:function(container,baseGrid,options){this.container=container;this.baseGrid=baseGrid;this.options=options;this.filterBox=this.container.down("div.filterEditor");this.gridType=parseInt(this.container.down("input.gridType").value,10);this.parentProfileId=parseInt(this.container.down("input.parentProfileId").value,
10);this.savedViewMode=parseInt(this.container.down("input.isSavedSet").value,10);this.noFiltersDiv=this.filterBox.down("div.noFilters");this.filtersDiv=this.filterBox.down("div.filters");this.filterCount=0;this.addContainer=this.filterBox.down("div.addContainer");this.propertyListDiv=this.filterBox.down("div.propertyList");this.operatorListDiv=this.filterBox.down("div.operatorList");this.valueInputArea=this.filterBox.down("div.valuesArea");this.createButton=this.filterBox.down("input.createButton");
this.cancelLink=this.filterBox.down("a.cancelLink");this.buttonsDiv=this.filterBox.down("div.filterButtons");this.addFilterLink=this.buttonsDiv.down("a.addFilter");this.clearAllLink=this.buttonsDiv.down("a.clearAll");this.saveSetLink=this.buttonsDiv.down("a.saveSet");this.saveFormContainer=this.buttonsDiv.down("span.saveFormContainer");this.loadSetLink=this.buttonsDiv.down("a.loadSet");this.addFilterLink.observe("click",function(e){this.loadProperties();e.stop()}.bind(this));this.clearAllLink.observe("click",
function(e){this.startClearFilters(e);e.stop()}.bind(this));this.saveSetLink.observe("click",function(e){this.startSaveSet();e.stop()}.bind(this));this.loadSetLink.observe("click",function(e){this.showSavedViews(e.element());e.stop()}.bind(this));this.savedViewsMenu=new BrainstormJs.Controls.PopupMenu(this.buttonsDiv.down("div.savedViewsMenu"),{onSelectChoice:this.onChooseSavedView.bind(this),onDeleteChoice:this.onDeleteSavedView.bind(this)});this.cancelLink.observe("click",function(e){this.cancelFilter();
e.stop()}.bind(this));this.createButton.observe("click",function(e){this.createFilter();e.stop()}.bind(this));this.summaryDiv=this.baseGrid.headerPanel.down(".summary");var recordCountSpan=this.summaryDiv.down("span.recordCount");if(recordCountSpan)this.recordCount=parseInt(recordCountSpan.innerHTML,10);this.bindUnboundFilters();this.filtersVisible=this.filterCount>0;if(this.filtersVisible)this.container.blindDown();this.baseGrid.headerPanel.down(".gridFilterTab").observe("click",function(){this.filtersVisible?
this.container.blindUp():this.container.blindDown();this.filtersVisible=!this.filtersVisible}.bind(this))},loadProperties:function(){this.buttonsDiv.blindUp({duration:0.25});this.addContainer.blindDown({duration:0.5});Brainstorm.Web.Services.Ajax.GetGridFilterPropertyList(this.gridType,this.parentProfileId,this.onPropertiesLoaded.bind(this),bsCommon.ajaxCallError)},onPropertiesLoaded:function(domElement){this.unbindPropertySelect();this.unbindOperatorSelect();this.unbindValueInput();this.propertyListDiv.innerHTML=
domElement.HTML;window.setTimeout(function(){this.bindPropertySelect()}.bind(this),1)},onPropertyChanged:function(){var selectedPropertyId=this.propertySelect.options[this.propertySelect.selectedIndex].value;if(!selectedPropertyId||selectedPropertyId=="")return;this.selectedProperty=selectedPropertyId;Brainstorm.Web.Services.Ajax.GetGridFilterOperatorList(this.gridType,this.parentProfileId,selectedPropertyId,this.onOperatorsLoaded.bind(this),bsCommon.ajaxCallError)},onOperatorsLoaded:function(domElement){this.unbindOperatorSelect();
this.unbindValueInput();this.operatorListDiv.innerHTML=domElement.HTML;window.setTimeout(function(){this.bindOperatorSelect()}.bind(this),1)},onOperatorChanged:function(){var selectedIndex=this.operatorSelect.selectedIndex;var selectedOption=this.operatorSelect.options[selectedIndex];this.selectedOperatorIndex=selectedIndex;if(!selectedOption||selectedOption.value=="")return;var parts=selectedOption.value.split(":");var dataOperator=parseInt(parts[0],10);var viewType=parseInt(parts[1],10);var longHint=
parseInt(parts[2],10);this.selectedOperator={dataOperator:dataOperator,viewType:viewType,longHint:longHint};if(viewType==Brainstorm.Model.Enums.DataFilterView.None){this.toggleCreateButton(true);this.unbindValueInput();return}this.toggleCreateButton(false);Brainstorm.Web.Services.Ajax.GetGridFilterValueInput(this.gridType,this.parentProfileId,this.selectedProperty,this.selectedOperator.dataOperator,this.selectedOperator.viewType,this.selectedOperator.longHint,this.onValueInputLoaded.bind(this),bsCommon.ajaxCallError)},
onValueInputLoaded:function(domElement){this.valueInputArea.innerHTML=domElement.HTML;window.setTimeout(function(){this.bindValueInput()}.bind(this),1)},createFilter:function(){if(this.selectedOperator.viewType==Brainstorm.Model.Enums.DataFilterView.Tags)if(this.dataInput.getValue()==""){var warningElem=this.dataInput.tagInput.container.down(".warning");warningElem.update("No tags have been entered!");warningElem.setStyle({color:"red"});return}this.createButton.disabled=true;Brainstorm.Web.Services.Ajax.CreateDataFilterItem(this.gridType,
this.parentProfileId,this.selectedProperty,this.selectedOperator.dataOperator,this.selectedOperator.viewType,this.selectedOperator.longHint,this.dataInput?this.dataInput.getValue():false,this.afterFilterCreated.bind(this),bsCommon.ajaxCallError)},afterFilterCreated:function(jsonFilterSet){this.updateAll(jsonFilterSet)},cancelFilter:function(){if(this.addContainer.visible())this.addContainer.blindUp({duration:0.25,afterFinish:function(){this.unbindPropertySelect();this.unbindOperatorSelect();this.toggleCreateButton(false);
this.createButton.disabled=true}.bind(this)});if(!this.buttonsDiv.visible())this.buttonsDiv.blindDown({duration:0.5})},startRemoveFilter:function(triggerEvent){var linkClicked=triggerEvent.element();var filterDiv=linkClicked.up("div.filter");var filterId=parseInt(filterDiv.id.split("_")[1]);bsCommon.confirm({title:"Removal Confirmation",text:"Are you sure you want to remove this filter?",width:450,confirmText:"Yes, remove it!",cancelText:"No, keep it.",triggerEvent:triggerEvent,onConfirm:function(){this.commitRemoveFilter(filterId)}.bind(this)})},
commitRemoveFilter:function(filterId){Brainstorm.Web.Services.Ajax.RemoveDataFilterItem(this.gridType,this.parentProfileId,filterId,this.afterRemoveFilter.bind(this),bsCommon.ajaxCallError)},afterRemoveFilter:function(jsonFilterSet){this.updateAll(jsonFilterSet)},startClearFilters:function(triggerEvent){if(this.savedViewMode){this.commitClearFilters();return}bsCommon.confirm({title:"Removal Confirmation",text:"Are you sure you want to remove all filters from this grid?",width:450,triggerEvent:triggerEvent,
confirmText:"Yes, remove them all!",cancelText:"No, keep them.",onConfirm:this.commitClearFilters.bind(this)})},commitClearFilters:function(){Brainstorm.Web.Services.Ajax.ResetCurrentFilterSet(this.gridType,this.parentProfileId,this.afterFiltersCleared.bind(this),bsCommon.ajaxCallError)},afterFiltersCleared:function(jsonFilterSet){this.updateAll(jsonFilterSet)},startSaveSet:function(){if(!this.saveSetForm)this.saveSetForm=new BrainstormJs.Forms.Grid.SaveFilterSetForm({parentContainer:this.saveFormContainer,
openLinks:[this.saveSetLink],bindOpenLinks:false,gridType:this.gridType,parentProfileId:this.parentProfileId,afterSave:this.afterSaveSet.bind(this)});this.saveSetForm.showForm({linkClicked:this.saveSetLink})},afterSaveSet:function(jsonFilterSet){this.updateSummary(jsonFilterSet.SummaryHtml);this.savedViewMode=true;this.savedViewsMenu.addChoice(jsonFilterSet.Id,jsonFilterSet.Name);this.loadSetLink.show();this.clearAllLink.show();this.updateRecordCount(this.recordCount)},showSavedViews:function(linkClicked){this.savedViewsMenu.show(linkClicked,
this,{width:200,offset:{x:-108,y:0}})},onChooseSavedView:function(linkClicked,menuContext,choiceContext){var savedSetId=parseInt(linkClicked.rel,10);Brainstorm.Web.Services.Ajax.LoadSavedFilterSet(this.gridType,this.parentProfileId,savedSetId,this.switchToSavedView.bind(this),bsCommon.ajaxCallError)},switchToSavedView:function(jsonFilterSet){if(jsonFilterSet.IsArchived){this.savedViewsMenu.hide();this.savedViewsMenu.removeChoice(jsonFilterSet.Id);bsCommon.alert("Oops, it looks like the saved view you selected no longer exists. It might have been removed by another team member.");
return}this.savedViewMode=jsonFilterSet.IsSaved;this.updateFilterSet(jsonFilterSet);this.updateSummary(jsonFilterSet.SummaryHtml);this.savedViewsMenu.hide();this.clearAllLink.show();if(this.baseGrid)this.baseGrid.switchSortColumn(jsonFilterSet.SortColumnKey,jsonFilterSet.SortDirection);this.notifyFiltersChanged()},onDeleteSavedView:function(linkClicked,menuContext,choiceContext,menuChoice,event){var savedSetId=parseInt(linkClicked.rel,10);var savedSetName=menuChoice.text;bsCommon.confirm({title:"Removed Saved View",
text:"Are you sure you want to remove the &#8220"+savedSetName+"&#8221; saved view? Once removed, it will no longer be accessible to other team members.",width:450,triggerEvent:event,confirmText:"Yes, remove it!",cancelText:"No, keep it.",onConfirm:function(){this.commitDeleteSavedView(savedSetId)}.bind(this)})},commitDeleteSavedView:function(savedSetId){Brainstorm.Web.Services.Ajax.DeleteSavedFilterSet(this.gridType,this.parentProfileId,savedSetId,this.afterDeleteSavedView.bind(this),bsCommon.ajaxCallError,
savedSetId)},afterDeleteSavedView:function(jsonFilterSet,deletedSetId){this.savedViewsMenu.removeChoice(deletedSetId);if(jsonFilterSet){this.afterFiltersCleared(jsonFilterSet);this.savedViewsMenu.hide()}},updateFilterSet:function(jsonFilterSet){if(!jsonFilterSet||jsonFilterSet.FilterCount==0){this.filterCount=0;this.filtersDiv.innerHTML="";this.filtersDiv.hide();this.noFiltersDiv.show()}else{this.filtersDiv.innerHTML=jsonFilterSet.FiltersHtml;if(this.noFiltersDiv.visible())this.noFiltersDiv.fade({duration:0.5});
if(!this.filtersDiv.visible())this.filtersDiv.appear({duration:0.5});else this.filtersDiv.appear({duration:0.5,from:0.5,to:1});this.filterCount=0;this.bindUnboundFilters()}if(this.filterCount>0||this.savedViewMode)this.clearAllLink.show();else this.clearAllLink.hide()},updateSummary:function(newSummary){this.summaryDiv.innerHTML=newSummary;this.summaryDiv.appear({duration:0.5,from:0.5,to:1})},updateAll:function(jsonFilterSet){this.savedViewMode=false;this.updateSummary(jsonFilterSet.SummaryHtml);
this.updateFilterSet(jsonFilterSet);this.cancelFilter();this.notifyFiltersChanged()},toggleCreateButton:function(show){this.createButton.disabled=show?false:true},notifyFiltersChanged:function(){if(this.options&&this.options.onFiltersChanged)this.options.onFiltersChanged()},updateRecordCount:function(newCount){this.recordCount=newCount;this.updateCounts(this.summaryDiv.select("span.recordCount"),newCount)},updateCounts:function(spans,newCount){for(var i=0,j=spans.length;i<j;i++){var span=spans[i];
var oldNum=parseInt(span.innerHTML,10);if(!isNaN(oldNum)&&oldNum!=newCount){span.innerHTML=newCount;new Effect.Highlight(span)}}},bindUnboundFilters:function(){var filters=this.filtersDiv.select("div.unboundFilter");for(var i=0,j=filters.length;i<j;i++){var filter=filters[i];var closeButton=filter.down("a.remove");closeButton.observe("click",function(e){this.startRemoveFilter(e);e.stop()}.bind(this));filter.removeClassName("unboundFilter");this.filterCount++}},bindPropertySelect:function(){if(!this.propertySelect)this.propertySelect=
this.propertyListDiv.down("select");this.propertyListDiv.show();if(!this.fxOnPropertyChanged)this.fxOnPropertyChanged=this.onPropertyChanged.bind(this);this.propertySelect.observe("change",this.fxOnPropertyChanged)},unbindPropertySelect:function(){if(this.propertySelect){Element.remove(this.propertySelect);this.propertySelect=false;this.previousProperty=false}},bindOperatorSelect:function(){if(!this.operatorSelect)this.operatorSelect=this.operatorListDiv.down("select");this.operatorListDiv.show();
if(!this.fxOnOperatorChanged)this.fxOnOperatorChanged=this.onOperatorChanged.bind(this);this.operatorSelect.observe("change",this.fxOnOperatorChanged)},unbindOperatorSelect:function(){if(this.operatorSelect){Element.remove(this.operatorSelect);this.operatorSelect=false;this.previousOperator=false;this.operatorListDiv.hide()}},bindValueInput:function(){var viewType=this.selectedOperator.viewType;var viewEnum=Brainstorm.Model.Enums.DataFilterView;if(viewType==viewEnum.DropDown||viewType==viewEnum.StarSelect)this.dataInput=
new BrainstormJs.Controls.DataFilters.Input.DropDownList(this.valueInputArea,this);else if(viewType==viewEnum.FreeText||viewType==viewEnum.Integer||viewType==viewEnum.DateBox)this.dataInput=new BrainstormJs.Controls.DataFilters.Input.TextBox(this.valueInputArea,this);else if(viewType==viewEnum.Tags)this.dataInput=new BrainstormJs.Controls.DataFilters.Input.TagList(this.valueInputArea,this);else this.dataInput=false;this.valueInputArea.show()},unbindValueInput:function(){if(this.dataInput){this.dataInput.destroy();
delete this.dataInput;this.valueInputArea.innerHTML="";this.valueInputArea.hide()}}});
BrainstormJs.Forms.EvaluationIdeaTeamMessageForm=Class.create(BrainstormJs.Forms.BaseForm,{fieldMessage:false,parentType:false,parentId:false,ideaId:false,initialize:function($super,options){options=options||{};options.createTitle="Send email to this idea team";options.submitButtonTitle="Send";this.parentType=options.parentType;this.parentId=options.parentId;this.ideaId=options.ideaId;$super(null,options)},createFields:function($super){this.fieldMessage=new BrainstormJs.Forms.Fields.TextArea({title:"Message",
required:true,enableWysiwyg:false});this.registerField(this.fieldMessage)},createNewObject:function($super){$super();Brainstorm.Web.Services.Ajax.SendEmailToIdeaTeam(this.parentType,this.parentId,this.ideaId,this.fieldMessage.getValue(),this.onSuccess.bind(this),this.handleAjaxError.bind(this))},onSuccess:function(){this.closeForm({afterFinish:function(){bsCommon.showSuccess("Message successfully sent to the idea team.")}})},afterClose:function($super){if(this.options.destroyOnClose)this.container.remove()}});
BrainstormJs.Controls.Evaluation.BaseIdeaEvaluation=Class.create({options:false,container:false,ideaPreviewDiv:false,actionFormContainer:false,evaluationParentType:false,evaluationParentId:false,evaluationObjectId:false,ideaId:false,evaluationMode:false,lazyLoad:false,ajaxPane:false,initialize:function(container,options){this.options=options||{};if(this.options.trigger&&this.options.ajaxPane&&this.options.dataMethod){this.lazyLoad=true;this.ajaxPane=new BrainstormJs.Controls.AjaxContentPane(this.options.ajaxPane);
this.container=this.ajaxPane.getContentDiv();this.evaluationObjectId=parseInt(this.options.trigger.rel,10);this.options.trigger.observe("click",function(e){this.toggleContent();e.stop()}.bind(this))}else{this.container=$(container);this.wireContainer()}},toggleContent:function(){if(!this.ajaxPane.visible())this.ajaxPane.startLoading({dataMethod:this.onFetchContent.bind(this)});else this.ajaxPane.close({destroyContent:true})},onFetchContent:function(){this.options.dataMethod(this.evaluationObjectId,
this.afterFetchContent.bind(this),bsCommon.ajaxCallError)},afterFetchContent:function(newContent){this.ajaxPane.insertContent(newContent,{onContentReady:this.wireContainer.bind(this)})},wireContainer:function(container){if(!this.container){console.error("Could not find evaluation container.");return}this.evaluationParentType=$F(this.container.down("input.evaluationParentType"));this.evaluationParentId=parseInt($F(this.container.down("input.evaluationParentId")),10);this.ideaId=parseInt($F(this.container.down("input.evaluationIdeaId")),
10);if(isNaN(this.evaluationParentId)||isNaN(this.ideaId)){console.error("Could not determine evaluation context.");return}var evalObjectIdInput=this.container.down("input.evaluationObjectId");if(evalObjectIdInput){this.evaluationObjectId=parseInt(evalObjectIdInput.value,10);if(isNaN(this.evaluationObjectId)){console.error("Could not determine evaluation object.");return}this.evaluationMode=true}this.wireActionButtons();this.wireIdeaPreview();if(this.evaluationMode)this.wireCustomFields();if(this.lazyLoad)this.ajaxPane.showContent({scroll:true,
scrollOffset:-40});BrainstormJs.Controls.Comments.CommentUtils.wireComments()},wireActionButtons:function(){var customButtons=[];this.actionFormContainer=this.container.down("div.actionFormContainer");var actionButtons=this.container.select("div.topButtons a.actionButton");for(var i=0,j=actionButtons.length;i<j;i++){var button=actionButtons[i];button.identify();new Tip(button,"<b>"+button.title+"</b>",{style:"darkgrey",stem:"bottomRight",hook:{tip:"bottomRight",target:"topRight"},hideAfter:0.1,hideOn:{event:"click"},
offset:{x:-3,y:1},width:"auto",border:5,radius:5});button.title="";if(button.hasClassName("shareIdea"))button.observe("click",function(e){this.onShareIdea(e.element());e.stop()}.bind(this));else if(button.hasClassName("followIdea"))button.observe("click",function(e){this.onFollowIdea(e.element());e.stop()}.bind(this));else if(button.hasClassName("sendTeamEmail"))button.observe("click",function(e){this.onEmailIdeaTeam(e.element());e.stop()}.bind(this));else customButtons.push(button)}if(customButtons.length>
0)this.wireCustomActions(customButtons)},wireIdeaPreview:function(){this.ideaPreviewDiv=this.container.down("div.ideaPreview");if(!this.ideaPreviewDiv)return;var teamLink=this.ideaPreviewDiv.down("div.ideaSnapshot div.teamMemberList a.toggleAll");if(teamLink)teamLink.observe("click",function(e){this.onShowMoreTeamMembers(e.element());e.stop()}.bind(this))},wireCustomFields:function(){var fieldTables=this.container.select("div.evaluationSection div.fauxTable");for(var i=0,j=fieldTables.length;i<j;i++)BrainstormJs.Controls.CustomFields.CustomFieldHelper.wireFrontendFields(fieldTables[i])},
onShowMoreTeamMembers:function(linkClicked){var teamMembers=linkClicked.previous("div.restTeamMembers");if(teamMembers)if(teamMembers.visible()){teamMembers.blindUp();linkClicked.innerHTML="show all"}else{teamMembers.blindDown();linkClicked.innerHTML="show less"}},onShareIdea:function(linkClicked){var form=new BrainstormJs.Forms.ShareObjectForm(this.getIdeaProfile(),{parentContainer:this.actionFormContainer,openLinks:[linkClicked],destroyOnClose:true,hideCommentField:true});form.showForm({linkClicked:linkClicked})},
onFollowIdea:function(linkClicked){var profile=this.getIdeaProfile();var form=new BrainstormJs.Forms.SubscriptionForm(profile.objectType,profile.id,{parentContainer:this.actionFormContainer,openLinks:[linkClicked],destroyOnClose:true,createTitle:"Subscribe to this idea"});form.showForm({linkClicked:linkClicked})},onEmailIdeaTeam:function(linkClicked){var form=new BrainstormJs.Forms.EvaluationIdeaTeamMessageForm({parentType:this.evaluationParentType,parentId:this.evaluationParentId,ideaId:this.ideaId,
parentContainer:this.actionFormContainer,openLinks:[linkClicked],destroyOnClose:true});form.showForm({linkClicked:linkClicked})},getObjectId:function(){return this.evaluationObjectId},getParentId:function(){return this.evaluationParentId},getIdeaId:function(){return this.ideaId},getIdeaProfile:function(){return{objectType:"idea",id:this.getIdeaId()}},getContainer:function(){return this.container},removeIdeaContent:function(){var divToRemove=this.getContainer();if(divToRemove){var wrapper=new Element("div");
divToRemove.immediateDescendants().each(function(e){e.wrap(wrapper)});wrapper.blindUp({delay:0.6,duration:1,afterFinish:function(e){wrapper.remove()}});var removed=(new Element("div",{"class":"noData"})).update("This idea has been removed.");divToRemove.insert(removed)}},wireCustomActions:function(topButtons){}});
BrainstormJs.Controls.Evaluation.ChallengeIdeaEvaluation=Class.create(BrainstormJs.Controls.Evaluation.BaseIdeaEvaluation,{notWinnerSpan:false,isWinnerSpan:false,initialize:function($super,container,options){$super(container,options)},getChallengeId:function(){return this.getParentId()},getChallengeIdeaId:function(){return this.getObjectId()},wireCustomActions:function(topButtons){for(var i=0,j=topButtons.length;i<j;i++){var button=topButtons[i];if(button.hasClassName("removeIdea"))button.observe("click",
function(e){this.onRemoveIdea();e.stop()}.bind(this))}var evalMenu=this.getContainer().down("div.evaluationSection div.titleRight");this.notWinnerSpan=evalMenu.down("span.notWinner");this.isWinnerSpan=evalMenu.down("span.isWinner");if(this.notWinnerSpan&&this.isWinnerSpan){this.notWinnerSpan.down("a.selectWinner").observe("click",function(e){this.onSelectWinner();e.stop()}.bind(this));this.isWinnerSpan.down("a.unselectWinner").observe("click",function(e){this.onUnselectWinner();e.stop()}.bind(this))}},
onRemoveIdea:function(){bsCommon.confirm({title:"Removal Confirmation",text:"Are you sure you would like to remove this idea from this challenge?",width:450,confirmText:"Yes, remove it!",cancelText:"No, keep it.",onConfirm:this.onConfirmRemove.bind(this)})},onConfirmRemove:function(){Brainstorm.Web.Services.Ajax.RemoveIdeaFromChallenge(this.getChallengeIdeaId(),this.removeIdeaContent.bind(this),bsCommon.ajaxCallError)},onSelectWinner:function(){bsCommon.confirm({title:"Winner Selection",text:"Are you sure you would like to select this idea as a winner for this challenge?",
detailText:"This idea will be displayed throughout Brainstorm as a winner of your challenge, and an email notification will be sent to its team members.",width:450,confirmText:"Yes, make it a winner!",cancelText:"Cancel",onConfirm:this.onConfirmWinnerSelect.bind(this)})},onConfirmWinnerSelect:function(){Brainstorm.Web.Services.Ajax.SelectWinnerForChallenge(this.getChallengeIdeaId(),this.afterWinnerSelect.bind(this),bsCommon.ajaxCallError)},afterWinnerSelect:function(){bsCommon.showSuccess("You have successfully selected this idea as a winner!");
this.updateWinnersTab(true);this.notWinnerSpan.fade({duration:0.25});this.isWinnerSpan.appear({duration:0.5,queue:"top"})},onUnselectWinner:function(){bsCommon.confirm({title:"Winner Selection",text:"Are you sure you would like to unselect this idea as a winner for this challenge?",width:450,confirmText:"Yes, this idea should NOT be a winner.",cancelText:"Cancel",onConfirm:this.onConfirmWinnerUnselect.bind(this)})},onConfirmWinnerUnselect:function(){Brainstorm.Web.Services.Ajax.UnselectWinnerForChallenge(this.getChallengeIdeaId(),
this.afterWinnerUnselect.bind(this),bsCommon.ajaxCallError)},afterWinnerUnselect:function(){this.isWinnerSpan.fade({duration:0.25});this.notWinnerSpan.appear({duration:0.5,queue:"top"});this.updateWinnersTab(false);bsCommon.showSuccess("You have UNSELECTED this idea as a winner!")},updateWinnersTab:function(added){var ideaTabs=$("challengeIdeaTabs");if(ideaTabs){var winnersTab=ideaTabs.down("div#winnersTab");var winnersCount=ideaTabs.down("a#winnersTab_link");if(winnersTab&&winnersCount){bsCommon.updateTabCount(winnersCount.down("span.count"),
added?1:-1,0,1);Brainstorm.Web.Services.Ajax.GetChallengeWinnerContent(this.getChallengeId(),function(jsonDomElement){winnersTab.innerHTML=jsonDomElement.HTML},function(){})}}}});BrainstormJs.Controls.Evaluation.EvaluationList=Class.create({options:false,container:false,initialize:function(container,options){this.options=options;this.container=$(container);if(!this.container)return}});
BrainstormJs.Controls.Evaluation.PipelineIdeaEvaluation=Class.create(BrainstormJs.Controls.Evaluation.BaseIdeaEvaluation,{initialize:function($super,container,options){$super(container,options)},getPipelineIdeaId:function(){return this.getObjectId()},wireCustomActions:function(buttons){for(var i=0,j=buttons.length;i<j;i++){var button=buttons[i];if(button.hasClassName("removeIdea"))button.observe("click",function(e){this.onRemoveIdea();e.stop()}.bind(this))}},onRemoveIdea:function(){bsCommon.confirm({title:"Removal Confirmation",
text:"Are you sure you would like to remove this idea from the pipeline?",width:450,confirmText:"Yes, remove it!",cancelText:"No, keep it.",onConfirm:this.onConfirmRemove.bind(this)})},onConfirmRemove:function(){Brainstorm.Web.Services.Ajax.RemoveIdeaFromPipeline(this.getPipelineIdeaId(),this.removeIdeaContent.bind(this),bsCommon.ajaxCallError)}});
BrainstormJs.Controls.Messaging.BaseMessageControl=Class.create({container:false,options:false,gridType:false,parentObjectId:false,messageInput:false,messageError:false,closeLink:false,cancelLink:false,initialize:function(container,options){this.container=container;this.options=options;this.closeLink=this.container.down("div.editorTitle a.close");this.closeLink.observe("click",function(e){this.onCancel();e.stop()}.bind(this));if(this.container.down("div.noData")&&!this.container.down("input.gridType"))return;
this.gridType=parseInt(this.container.down("input.gridType").value,10);this.parentObjectId=parseInt(this.container.down("input.parentObjectId").value,10);this.messageInput=this.container.down("textarea#teamMessage");this.messageError=this.container.down("div.messageInput span.errorMessage");this.bindEmailToggles();this.submitButton=this.container.down("input.submitButton");this.submitButton.observe("click",this.onSend.bind(this));this.cancelLink=this.container.down("div.buttons a.cancelLink");this.cancelLink.observe("click",
function(e){this.onCancel();e.stop()}.bind(this))},bindEmailToggles:function(){var showEmailsLink=this.container.down("a.showEmails");showEmailsLink.observe("click",function(e){this.toggleEmailList(e.element());e.stop()}.bind(this))},toggleEmailList:function(linkClicked){var emails=this.container.down("div.emailsBox");if(linkClicked.hasClassName("open")){linkClicked.removeClassName("open");linkClicked.innerHTML="show email addresses";if(emails.visible())emails.blindUp({duration:0.25})}else{linkClicked.addClassName("open");
linkClicked.innerHTML="hide";if(!emails.visible())emails.blindDown({duration:0.5})}},getMessage:function(){return this.messageInput?this.messageInput.value.strip():""},onSend:function(){if(this.getMessage()==""){this.messageError.appear({duration:0.5});return}if(this.messageError.visible())this.messageError.fade({duration:0.25});this.toggleButtons(false);Brainstorm.Web.Services.Ajax.SendGridTeamMessage(this.gridType,this.parentObjectId,this.getMessage(),this.teamLeadersOnly(),this.afterSend.bind(this),
function(error){bsCommon.ajaxCallError(error,this.onSendError.bind(this))}.bind(this))},afterSend:function(message){bsCommon.showSuccess(message);this.onClose()},toggleButtons:function(enable){this.submitButton.disabled=!enable;this.messageInput.disabled=!enable;if(enable){this.submitButton.value="Try Again";this.cancelLink.show()}else{this.submitButton.value="Please Wait ...";this.cancelLink.hide()}},onSendError:function(){this.toggleButtons(true)},onCancel:function(){if(this.getMessage()=="")this.onClose();
else bsCommon.confirm({title:"Team Message",text:"Are you sure you would like to close the message editor?",detailText:"The text you entered in the message field will be lost.",width:450,confirmText:"Yes, close it.",cancelText:"No, keep it open",onConfirm:this.onClose.bind(this)})},onClose:function(){if(this.options.afterClose)this.options.afterClose()},teamLeadersOnly:function(){return false}});
BrainstormJs.Controls.Messaging.TeamMessageControl=Class.create(BrainstormJs.Controls.Messaging.BaseMessageControl,{radioLeaders:false,radioTeam:false,initialize:function($super,container,options){$super(container,options);this.radioLeaders=this.container.down("input#emailLeaders");this.radioTeam=this.container.down("input#emailTeam")},bindEmailToggles:function($super){var showEmailLinks=this.container.select("div.emailChoices a.showEmails");for(var i=0;i<showEmailLinks.length;i++)showEmailLinks[i].observe("click",
function(e){this.toggleEmailList(e.element());e.stop()}.bind(this))},teamLeadersOnly:function(){return this.radioLeaders.checked},toggleEmailList:function($super,linkClicked){var emails=linkClicked.next("div.emailsBox");if(linkClicked.hasClassName("open")){linkClicked.removeClassName("open");linkClicked.innerHTML="show email addresses";if(emails.visible())emails.blindUp({duration:0.25})}else{linkClicked.addClassName("open");linkClicked.innerHTML="hide";if(!emails.visible())emails.blindDown({duration:0.5})}},
toggleButtons:function($super,enable){$super();this.radioLeaders.disabled=!enable;this.radioTeam.disabled=!enable}});
BrainstormJs.Controls.Grid.BaseGrid=Class.create({container:false,blocker:false,table:false,tbody:false,tfoot:false,dataFilters:false,filterAreaEl:false,pager:false,pagerContainer:false,pageSize:false,pageSizeOptions:[10,25,50,100],gridId:false,fxFetchNewData:false,fxStartSendMessage:false,messageAjaxPane:false,columns:false,sortedColumn:false,sortQuery:"",fxTogglePreview:false,fxPreviewLoaded:false,fxOnGridRefresh:false,fxNextPageIdeaPreview:false,onTotalChange:false,lazyInitialize:false,ASC:Brainstorm.Model.Enums.SortDirection.Asc,
DESC:Brainstorm.Model.Enums.SortDirection.Desc,initialize:function(container,options){if(options){this.onTotalChange=options.onTotalChange||false;this.lazyInitialize=options.lazyInitialize||false;this.fxOnGridRefresh=options.onGridRefresh||false;this.filterAreaEl=options.filterAreaEl||false}this.container=$(container);if(!this.fxFetchNewData)this.fxFetchNewData=this._fetchNewData.bind(this);if(!this.lazyInitialize)this.wireGrid()},wireGrid:function(){this.table=this.container.down("table.grid");this.gridId=
this.table.up("div.sortableGrid").id;this.blocker=this.container.down("div.blocker");this.headerPanel=this.container.down("div.gridSuperHeader");if(this.container.down("input.pageSize"))this.pageSize=parseInt($F(this.container.down("input.pageSize")),10);if(this.headerPanel){var changePageSizeEl=this.headerPanel.down(".summaryBar").down("a.pageSizeModifier");this.wirePageSizeSelector(changePageSizeEl)}var gridWrapper=this.container.up("div.gridWrapper");var hasGridWrapper=gridWrapper!=null;var expander=
this.table.down("th.expander a.expander");var collapser=this.table.down("th.collapser a.collapser");if(expander&&collapser)this.gridWrapper=new BrainstormJs.Controls.Grid.GridWrapper(gridWrapper||this.container,{expandLink:expander,collapseLink:collapser,createStructure:!hasGridWrapper,gridObject:this});if(!this.filterAreaEl)this.filterAreaEl=this.container.down("div.dataFilterArea")||false;if(this.filterAreaEl!=false)this.dataFilters=new BrainstormJs.Controls.DataFilters.DataFilterEditor(this.filterAreaEl,
this,{onFiltersChanged:this.refreshGrid.bind(this)});if(this.table==null)return;this.tbody=this.table.down("tbody");this.tfoot=this.table.down("tfoot");this.pagerContainer=this.tfoot.down("td.pagerContainer");this.resetPagination();this.resetTeamMessageLink();this.wireColumns();this.fxTogglePreview=function(e){this.togglePreview(e.element());e.stop()}.bind(this);this.fxPreviewLoaded=this.previewLoaded.bind(this);this.bindEvents();this.refreshColumns(false)},wireColumns:function(){this.columns=new Hash;
var columnHeaders=this.table.select("thead th a.sortLink");for(var i=0,j=columnHeaders.length;i<j;i++){var link=columnHeaders[i];var cell=link.up("th");var key=link.rel;var sortable=!cell.hasClassName("static");var sortDir=!cell.hasClassName("startDesc")?this.ASC:this.DESC;var sorted=false;if(cell.hasClassName("sorted")){sorted=true;if(cell.hasClassName("sorted_asc"))sortDir=this.ASC;else if(cell.hasClassName("sorted_desc"))sortDir=this.DESC}var column={link:link,key:key,cell:cell,sorted:sorted,sortDir:sortDir,
sortable:sortable};if(column.sorted)this.sortedColumn=column;this.columns.set(key,column);if(column.sortable)link.observe("click",this.sortByColumn.bind(this))}},switchSortColumn:function(columnKey,sortDir){if(this.sortedColumn){this.sortedColumn.sorted=false;this.sortedColumn.cell.removeClassName("sorted");this.sortedColumn.cell.removeClassName("sorted_desc");this.sortedColumn.cell.removeClassName("sorted_asc")}var newSortColumn=this.columns.get(columnKey);if(newSortColumn){newSortColumn.sorted=
true;newSortColumn.sortDir=sortDir;newSortColumn.cell.addClassName("sorted");newSortColumn.cell.addClassName("sorted_"+(sortDir==this.ASC?"asc":"desc"));this.sortedColumn=newSortColumn}},sortByColumn:function(e){e.stop();var columnLink=e.element();if(columnLink.tagName.toLowerCase()!="a")columnLink=columnLink.up("a");if(!columnLink)return;var column=this.columns.get(columnLink.rel);this.updateFilters(column)},updateFilters:function(column){if(!column){console.error('"column" is not specified for updateFilters');
return}var alreadySorted=column.cell.hasClassName("sorted");if(alreadySorted)column.sortDir=column.sortDir==this.ASC?this.DESC:this.ASC;this.sortedColumn=column;this.refreshColumns(true)},refreshGrid:function(){if(this.fxOnGridRefresh)this.fxOnGridRefresh();this.changePage({pageNum:1,refreshPager:true})},refreshColumns:function(fetchData){this.columns.each(function(column){column.value.cell.removeClassName("sorted");column.value.cell.removeClassName("sorted_asc");column.value.cell.removeClassName("sorted_desc")});
if(this.sortedColumn&&this.sortedColumn.cell){this.sortedColumn.cell.addClassName("sorted");this.sortedColumn.cell.addClassName("sorted_"+(this.sortedColumn.sortDir==this.ASC?"asc":"desc"));this.sortQuery=this.sortedColumn.key+":"+(this.sortedColumn.sortDir==this.ASC?"asc":"desc")}if(!(this.sortQuery.indexOf("CustomField_")>=0||this.sortQuery.length>=32))bsCommon.setState(this.gridId+"_sortQuery",this.sortQuery);if(fetchData)this._fetchNewData({pageNum:1,refreshPager:true,sortColumn:this.sortedColumn.key,
sortDir:this.sortedColumn.sortDir})},updateView:function(gridData,options){if(this.lazyInitialize){this.lazyInitialize=false;this.container.innerHTML=gridData.GridHTML;this.wireGrid()}this.positionBlocker(false);if(Prototype.Browser.IE){var hiddenElements=$("hiddenElements");var tempTableDiv=$("tempGridTable");if(!tempTableDiv){tempTableDiv=new Element("div",{"id":"tempGridTable"});hiddenElements.insert(tempTableDiv)}tempTableDiv.innerHTML="<table><tbody>"+gridData.DataHTML+"</tbody></table>";var newTableBody=
tempTableDiv.firstChild.firstChild;this.tbody.remove();this.table.insert(newTableBody);this.tbody=$(newTableBody)}else this.tbody.innerHTML=gridData.DataHTML;this.bindEvents();Effect.Appear(this.tbody,{from:0.5,to:1,duration:0.5});if(options.refreshPager){this.pagerContainer.innerHTML=gridData.FooterHTML;this.resetPagination();this.resetTeamMessageLink();if(this.onTotalChange)this.onTotalChange(gridData.ObjectCount);else if(this.dataFilters)this.dataFilters.updateRecordCount(gridData.ObjectCount)}if(options.afterFinish)options.afterFinish()},
resetPagination:function(){var paginationList=this.pagerContainer.down("ul.pagination");if(paginationList)this.pager=new BrainstormJs.Controls.Pager(paginationList,this.gridId,{onChange:this.fxFetchNewData,pageSize:this.pageSize})},resetTeamMessageLink:function(){var messageLink=this.pagerContainer.down("div.gridFooter div.rightCol a.emailTeamLink");if(messageLink){if(!this.fxStartSendMessage)this.fxStartSendMessage=function(e){this.startSendMessage(e.element());e.stop()}.bind(this);messageLink.observe("click",
this.fxStartSendMessage);if(!this.messageAjaxPane){var paneDiv=this.container.down("div.teamMessagePane");this.messageAjaxPane=new BrainstormJs.Controls.AjaxContentPane(paneDiv)}}},startSendMessage:function(linkClicked){var countEl=this.container.up("div.gridWrapper").down("span.recordCount");if(countEl&&countEl.innerHTML)if(countEl.innerHTML>2500){bsCommon.alert("This list has more than 2,500 email addresses.  When a list is that big, it causes performance issues with the 'Send Message' feature."+
" Please use the <strong>'filters & views'</strong> feature to break your list into smaller groups.","Your list is too large to send");return}var gridType=parseInt(linkClicked.previous("input.gridType").value,10);var parentObjectId=parseInt(linkClicked.previous("input.parentObjectId").value,10);this.messageAjaxPane.startLoading({hideElements:[linkClicked.up("span.teamMessage")],dataMethod:function(){this.loadMessageControl(gridType,parentObjectId)}.bind(this)})},loadMessageControl:function(gridType,
parentObjectId){if(this.dataFilters)Brainstorm.Web.Services.Ajax.GetGridMessageControl(gridType,this.dataFilters.recordCount,parentObjectId,this.messageControlLoaded.bind(this),bsCommon.ajaxCallError)},messageControlLoaded:function(jsonDomElement){this.messageAjaxPane.insertContent(jsonDomElement.HTML,{onContentReady:this.bindMessageControl.bind(this)})},bindMessageControl:function(){var controlDiv=this.messageAjaxPane.getContentDiv().down("div.gridMessageControl");this.messageControl=new BrainstormJs.Controls.Messaging.TeamMessageControl(controlDiv,
{afterClose:function(){this.messageAjaxPane.close({destroyContent:true})}.bind(this)});this.messageAjaxPane.showContent()},getTableBody:function(){return this.tbody},positionBlocker:function(show){if(show){var tableSize=this.table.getDimensions();this.blocker.setStyle({width:tableSize.width+"px",height:tableSize.height+"px"});this.blocker.show()}else this.blocker.hide()},bindPreviewToggles:function(){var tbody=this.getTableBody();var toggles=tbody.select("a.showPreview");for(var i=0,j=toggles.length;i<
j;i++)toggles[i].observe("click",this.fxTogglePreview)},togglePreview:function(linkClicked,afterClose){var OPEN_CLASS_NAME="openPreview";var linkClicked=bsCommon.getLink(linkClicked);var ideaId=parseInt(linkClicked.rel,10);var previewArea=linkClicked.up("tr").next("tr.expand").down("td.expand").down("div.ajaxContentPane");var previewContent=previewArea.down("div.content");if(linkClicked.hasClassName(OPEN_CLASS_NAME)){linkClicked.removeClassName(OPEN_CLASS_NAME);previewArea.fade({duration:0.5,afterFinish:function(){if(afterClose)afterClose()}})}else{linkClicked.addClassName(OPEN_CLASS_NAME);
previewArea.show();previewContent.hide();previewContent.previous("div.loading").show();this._fetchIdeaPreview(ideaId,previewContent)}},previewLoaded:function(previewHTML,previewContent){var previewScrollOffset=-40;previewContent.previous("div.loading").blindUp({duration:0.5});previewContent.innerHTML=previewHTML;previewContent.blindDown({duration:0.5,afterFinish:function(){bsCommon.scrollTo(previewContent,{offset:previewScrollOffset});this.wireEvaluation(previewContent);ExposeInstances.fitAllToWindow()}.bind(this)});
previewContent.identify();var nextIdea=previewContent.down("a.nextIdea");if(nextIdea){var expandRow=nextIdea.up("tr.expand");var nextRow=expandRow.next("tr");var currentIdeaExpandLink=expandRow.previous("tr").down("td.gridCell a.showPreview");if(nextRow){var showPreviewLink=nextRow.down("td.gridCell a.showPreview");nextIdea.observe("click",function(e){e.stop();if(showPreviewLink.hasClassName("openPreview")){var previewContent=showPreviewLink.up("tr").next("tr.expand").down("div.ajaxContentPane div.content");
bsCommon.scrollTo(previewContent,{offset:previewScrollOffset})}else if(currentIdeaExpandLink)this.togglePreview(currentIdeaExpandLink,function(){this.togglePreview(showPreviewLink,true)}.bind(this));else this.togglePreview(showPreviewLink,true)}.bind(this))}else if(this.pager&&this.pager.currentPage<this.pager.lastPageNum){if(!this.fxNextPageIdeaPreview)this.fxNextPageIdeaPreview=function(e){e.stop();this.pager.nextPage({afterFinish:function(){var nextPagePreviewLink=this.tbody.down("tr td.ideaTitle a.showPreview");
if(nextPagePreviewLink)this.togglePreview(nextPagePreviewLink,true)}.bind(this)})}.bind(this);nextIdea.observe("click",this.fxNextPageIdeaPreview)}else nextIdea.fade()}},wirePageSizeSelector:function(changePageSizeEl){if(!changePageSizeEl)return;var changePageContent=new Element("div");for(var i=0,j=this.pageSizeOptions.length;i<j;i++){var sizeOption=this.pageSizeOptions[i];var optionLink=(new Element("a",{href:"javascript:void(0)"})).update(sizeOption);if(this.pageSize==sizeOption)optionLink.addClassName("currentPageSize");
optionLink.observe("click",function(e){changePageSizeEl.prototip.hide();this.changePageSize(e.element(),changePageSizeEl);e.stop()}.bind(this));changePageContent.insert(optionLink);if(i+1<j)changePageContent.insert((new Element("span")).update("&nbsp;&nbsp;|&nbsp;&nbsp;"))}new Tip(changePageSizeEl,changePageContent,{style:"default",closeButton:false,showOn:"click",hideOn:false,hideAfter:1,stem:"topRight",hook:{target:"topRight",tip:"topRight"},offset:{x:-8,y:11},width:"auto"})},changePageSize:function(pageSizeLink,
changePageSizeEl){if(this.fxFetchNewData){var currentPage=this.pager?this.pager.currentPage:1;var topRecord=this.pageSize*(currentPage-1);this.pageSize=parseInt(pageSizeLink.innerHTML,10);var newPageNum=Math.floor(topRecord/this.pageSize)+1;this.fxFetchNewData({pageSize:this.pageSize,pageNum:newPageNum,refreshPager:true});this.updateSizeSelector(pageSizeLink);changePageSizeEl.down("span.dataPageSize").update(this.pageSize);this.trackAction("page size adjusted to "+this.pageSize)}},updateSizeSelector:function(pageSizeLink){if(pageSizeLink.hasClassName("currentPageSize"))return;
var oldPageSizeLink=pageSizeLink.previous(".currentPageSize")||pageSizeLink.next(".currentPageSize");if(oldPageSizeLink!=null)oldPageSizeLink.removeClassName("currentPageSize");pageSizeLink.addClassName("currentPageSize")},updateSummary:function(newSummary){var summaryEl=this.headerPanel.down(".summary");summaryEl.update(newSummary)},trackAction:function(actionId){BrainstormJs.Analytics.scTrackAction(this.gridId,actionId)},_fetchNewData:function(options){this.positionBlocker(true);this.changePage(options)},
_fetchIdeaPreview:function(ideaId,previewContent){this.fetchIdeaPreview(ideaId,previewContent)},changePage:function(options){},fetchIdeaPreview:function(ideaId,previewArea){console.error("This functionality is not implemented")},updateObjectCount:function(count){},wireEvaluation:function(ideaPreviewContent){},bindEvents:function(){this.bindPreviewToggles()}});
BrainstormJs.Controls.Grid.ChallengeIdeasGrid=Class.create(BrainstormJs.Controls.Grid.BaseGrid,{challengeId:false,initialize:function($super,challengeId,container,options){this.challengeId=challengeId;$super(container,options)},changePage:function($super,options){Brainstorm.Web.Services.Ajax.GetGridPage(Brainstorm.Model.Enums.GridType.ChallengeIdeasGrid,this.challengeId,options.pageNum,options.refreshPager||false,options.sortColumn||null,options.sortDir||null,options.pageSize||null,this.updateView.bind(this),
bsCommon.ajaxCallError,options)},fetchIdeaPreview:function($super,ideaId,previewContent){Brainstorm.Web.Services.Ajax.GetChallengeGridEvaluation(ideaId,this.challengeId,this.fxPreviewLoaded,bsCommon.ajaxCallError,previewContent)},wireEvaluation:function(ideaPreviewContent){var workflowControl=new BrainstormJs.Controls.Evaluation.ChallengeIdeaEvaluation(ideaPreviewContent)}});
BrainstormJs.Controls.Grid.ChallengeGrid=Class.create(BrainstormJs.Controls.Grid.BaseGrid,{initialize:function($super,container,options){$super(container,options)},resetFilters:function(){this.changePage({pageNum:1,refreshPager:true})},changePage:function($super,options){Brainstorm.Web.Services.Ajax.GetChallengeGrid(options.pageNum,options.refreshPager||false,this.sortQuery,this.updateView.bind(this),bsCommon.ajaxCallError,options)}});
BrainstormJs.Controls.Grid.GenericGrid=Class.create(BrainstormJs.Controls.Grid.BaseGrid,{gridType:false,initialize:function($super,gridType,container,options){this.gridType=gridType;$super(container,options)},resetFilters:function(){this.changePage({pageNum:1,refreshPager:true})},changePage:function($super,options){Brainstorm.Web.Services.Ajax.GetGridPage(this.gridType,null,options.pageNum,options.refreshPager||false,options.sortColumn||null,options.sortDir||null,options.pageSize||null,this.updateView.bind(this),
bsCommon.ajaxCallError,options)},bindMessageControl:function(){var controlDiv=this.messageAjaxPane.getContentDiv().down("div.gridMessageControl");this.messageControl=new BrainstormJs.Controls.Messaging.BaseMessageControl(controlDiv,{afterClose:function(){this.messageAjaxPane.close({destroyContent:true})}.bind(this)});this.messageAjaxPane.showContent()}});
BrainstormJs.Controls.Grid.IdeaGrid=Class.create(BrainstormJs.Controls.Grid.BaseGrid,{dropBU:false,dropStatus:false,checkNeedsHelp:false,filterBusinessUnit:0,filterStatus:0,onlyClassifieds:false,initialize:function($super,container,options){$super(container,options);this.dropBU=$("bizUnit");this.dropStatus=$("status");this.checkNeedsHelp=$("checkHasClassifieds");var fxResetFilters=this.resetFilters.bind(this);this.dropBU.observe("change",fxResetFilters);this.dropStatus.observe("change",fxResetFilters);
this.checkNeedsHelp.observe("click",fxResetFilters);this.checkNeedsHelp.observe("keypress",function(e){if(e.keyCode==Event.KEY_SPACE)this.resetFilters()}.bind(this))},resetFilters:function(){this.filterBusinessUnit=this.dropBU.options[this.dropBU.selectedIndex].value;this.filterStatus=this.dropStatus.options[this.dropStatus.selectedIndex].value;this.onlyClassifieds=this.checkNeedsHelp.checked;if(!this.filterStatus||this.filterStatus=="")this.filterStatus=0;if(!this.filterBusinessUnit||this.filterBusinessUnit==
"")this.filterBusinessUnit=0;bsCommon.setState("ideaGrid_status",this.filterStatus);bsCommon.setState("ideaGrid_bizUnit",this.filterBusinessUnit);bsCommon.setState("ideaGrid_needHelp",this.onlyClassifieds);bsCommon.setState("ideaGrid_page",1);this.changePage({pageNum:1,refreshPager:true})},changePage:function($super,options){Brainstorm.Web.Services.IdeaTasks.GetIdeaTable(options.pageNum,this.onlyClassifieds,this.filterStatus,this.filterBusinessUnit,options.refreshPager||false,this.sortQuery,this.updateView.bind(this),
bsCommon.ajaxCallError,options)}});
BrainstormJs.Controls.Grid.PipelineCandidatesGrid=Class.create(BrainstormJs.Controls.Grid.BaseGrid,{pipelineProfile:false,pipelineId:false,fxApproveIdea:false,fxIgnoreIdea:false,fxShowPreview:false,initialize:function($super,pipelineProfile,container,options){this.pipelineProfile=pipelineProfile;this.pipelineId=pipelineProfile.id;this.fxShowPreview=function(e){this.showIdeaPreview(e.element());e.stop()}.bind(this);this.fxApproveIdea=function(e){this.addIdea(e.element());e.stop()}.bind(this);this.fxIgnoreIdea=
function(e){this.ignoreIdea(e.element());e.stop()}.bind(this);$super(container,options)},resetFilters:function(){this.changePage({pageNum:1,refreshPager:true})},changePage:function($super,options){Brainstorm.Web.Services.Ajax.GetPipelineCandidatesGrid(this.pipelineId,options.pageNum,options.refreshPager||false,this.sortQuery,this.updateView.bind(this),bsCommon.ajaxCallError,options)},bindEvents:function($super){var tableBody=this.getTableBody();var approveLinks=tableBody.select("td.Action div.actions a.addIdea");
for(var i=0,j=approveLinks.length;i<j;i++)approveLinks[i].observe("click",this.fxApproveIdea);var ignoreLinks=tableBody.select("td.Action div.actions a.ignoreIdea");for(var i=0,j=ignoreLinks.length;i<j;i++)ignoreLinks[i].observe("click",this.fxIgnoreIdea);$super()},showIdeaPreview:function(linkClicked){var ideaId=parseInt(linkClicked.rel,10);var row=linkClicked.up("tr");var previewRow=row.next("tr.expand");if(previewRow)previewRow.innerHTML=ideaId},addIdea:function(linkClicked){var ideaId=parseInt(linkClicked.rel,
10);Brainstorm.Web.Services.Ajax.ApprovePipelineIdea(this.pipelineId,ideaId,this.afterIdeaApproved.bind(this),bsCommon.ajaxCallError,linkClicked)},ignoreIdea:function(linkClicked){var ideaId=parseInt(linkClicked.rel,10);Brainstorm.Web.Services.Ajax.IgnorePipelineIdea(this.pipelineId,ideaId,this.afterIdeaIgnored.bind(this),bsCommon.ajaxCallError,linkClicked)},afterIdeaIgnored:function(jsonPipelineIdea,linkClicked){this.applyAction(linkClicked,false)},afterIdeaApproved:function(jsonPipelineIdea,linkClicked){this.applyAction(linkClicked,
true);this.pipelineProfile.afterIdeaApproved()},applyAction:function(linkClicked,added){var buttons=linkClicked.up("div.buttons");var statuses=buttons.next("div.statuses");var newStatus=added?statuses.down(".added"):statuses.down(".ignored");buttons.fade({duration:0.5,afterFinish:function(){newStatus.appear({duration:0.5})}})},fetchIdeaPreview:function($super,ideaId,previewContent){Brainstorm.Web.Services.Ajax.GetPipelineIdeaPreview(ideaId,this.pipelineId,false,this.fxPreviewLoaded,bsCommon.ajaxCallError,
previewContent)},wireEvaluation:function(ideaPreviewContent){var workflowControl=new BrainstormJs.Controls.Evaluation.PipelineIdeaEvaluation(ideaPreviewContent)}});
BrainstormJs.Controls.Grid.PipelineGrid=Class.create(BrainstormJs.Controls.Grid.BaseGrid,{initialize:function($super,container,options){$super(container,options)},resetFilters:function(){this.changePage({pageNum:1,refreshPager:true})},changePage:function($super,options){Brainstorm.Web.Services.Ajax.GetPipelineGrid(options.pageNum,options.refreshPager||false,this.sortQuery,this.updateView.bind(this),bsCommon.ajaxCallError,options)}});
BrainstormJs.Controls.Grid.PipelineIdeasGrid=Class.create(BrainstormJs.Controls.Grid.BaseGrid,{pipelineId:false,initialize:function($super,pipelineId,container,options){this.pipelineId=pipelineId;$super(container,options)},changePage:function($super,options){Brainstorm.Web.Services.Ajax.GetGridPage(Brainstorm.Model.Enums.GridType.PipelineIdeasGrid,this.pipelineId,options.pageNum,options.refreshPager||false,options.sortColumn||null,options.sortDir||null,options.pageSize||null,this.updateView.bind(this),
bsCommon.ajaxCallError,options)},fetchIdeaPreview:function($super,ideaId,previewContent){Brainstorm.Web.Services.Ajax.GetPipelineIdeaPreview(ideaId,this.pipelineId,true,this.fxPreviewLoaded,bsCommon.ajaxCallError,previewContent)},wireEvaluation:function(ideaPreviewContent){var workflowControl=new BrainstormJs.Controls.Evaluation.PipelineIdeaEvaluation(ideaPreviewContent)}});
BrainstormJs.Forms.Parts.NoteForm=Class.create(BrainstormJs.Forms.BaseForm,{bodyEditor:false,fieldTitle:false,fieldBody:false,initialize:function($super,profile,options){options=options||{};options.createTitle="Add a new note";options.editTitle="Edit note";$super(profile,options);this.editObjectType="NotePart";this.friendlyObjectName="note"},createFields:function($super){this.fieldTitle=new BrainstormJs.Forms.Fields.TextBox({title:"Title",required:true,maxLength:100,dataSelector:".data-Title",hideOnEdit:true});
this.fieldBody=new BrainstormJs.Forms.Fields.TextArea({title:"Body",required:true,enableWysiwyg:true,dataSelector:".data-Body"});this.registerField(this.fieldTitle);this.registerField(this.fieldBody)},beforeShow:function($super){$super();this.fieldBody.createWysiwyg()},afterClose:function($super){$super();this.fieldBody.destroyWysiwyg()},createNewObject:function($super){Brainstorm.Web.Services.Parts.CreateNote(this.profile.partContainer.activeTab.id,this.fieldTitle.getValue(),this.fieldBody.getValue(),
this.noteCreated.bind(this),this.handleAjaxError.bind(this))},noteCreated:function(domElement){this.profile.partContainer.activeTab.registerNewPart(domElement,this)},startEditing:function(notePart){this.editingExisting=true;this.editingNote=notePart;this.showForm({afterFinish:function(){this.loadObjectValues(this.editingNote.container)}.bind(this),editMode:true})},saveEditedObject:function(){if(this.editingExisting&&this.editingNote)Brainstorm.Web.Services.Parts.UpdateNoteBody(this.editingNote.partId,
this.fieldBody.getValue(),this.noteSaved.bind(this),bsCommon.ajaxCallError)},noteSaved:function(jsonNote){var noteBody=this.editingNote.container.down("div.noteBody");noteBody.innerHTML=jsonNote.Body;this.closeForm({afterFinish:function(){new Effect.Highlight(noteBody)}});this.editingNote=false;this.stopEditingObject()}});if(Object.isUndefined(Effect))throw"dragdrop.js requires including script.aculo.us' effects.js library";
var Droppables={drops:[],remove:function(element){this.drops=this.drops.reject(function(d){return d.element==$(element)})},add:function(element){element=$(element);var options=Object.extend({greedy:true,hoverclass:null,tree:false},arguments[1]||{});if(options.containment){options._containers=[];var containment=options.containment;if(Object.isArray(containment))containment.each(function(c){options._containers.push($(c))});else options._containers.push($(containment))}if(options.accept)options.accept=
[options.accept].flatten();Element.makePositioned(element);options.element=element;this.drops.push(options)},findDeepestChild:function(drops){deepest=drops[0];for(i=1;i<drops.length;++i)if(Element.isParent(drops[i].element,deepest.element))deepest=drops[i];return deepest},isContained:function(element,drop){var containmentNode;if(drop.tree)containmentNode=element.treeNode;else containmentNode=element.parentNode;return drop._containers.detect(function(c){return containmentNode==c})},isAffected:function(point,
element,drop){return drop.element!=element&&(!drop._containers||this.isContained(element,drop))&&(!drop.accept||Element.classNames(element).detect(function(v){return drop.accept.include(v)}))&&Position.within(drop.element,point[0],point[1])},deactivate:function(drop){if(drop.hoverclass)Element.removeClassName(drop.element,drop.hoverclass);this.last_active=null},activate:function(drop){if(drop.hoverclass)Element.addClassName(drop.element,drop.hoverclass);this.last_active=drop},show:function(point,
element){if(!this.drops.length)return;var drop,affected=[];this.drops.each(function(drop){if(Droppables.isAffected(point,element,drop))affected.push(drop)});if(affected.length>0)drop=Droppables.findDeepestChild(affected);if(this.last_active&&this.last_active!=drop)this.deactivate(this.last_active);if(drop){Position.within(drop.element,point[0],point[1]);if(drop.onHover)drop.onHover(element,drop.element,Position.overlap(drop.overlap,drop.element));if(drop!=this.last_active)Droppables.activate(drop)}},
fire:function(event,element){if(!this.last_active)return;Position.prepare();if(this.isAffected([Event.pointerX(event),Event.pointerY(event)],element,this.last_active))if(this.last_active.onDrop){this.last_active.onDrop(element,this.last_active.element,event);return true}},reset:function(){if(this.last_active)this.deactivate(this.last_active)}};
var Draggables={drags:[],observers:[],register:function(draggable){if(this.drags.length==0){this.eventMouseUp=this.endDrag.bindAsEventListener(this);this.eventMouseMove=this.updateDrag.bindAsEventListener(this);this.eventKeypress=this.keyPress.bindAsEventListener(this);Event.observe(document,"mouseup",this.eventMouseUp);Event.observe(document,"mousemove",this.eventMouseMove);Event.observe(document,"keypress",this.eventKeypress)}this.drags.push(draggable)},unregister:function(draggable){this.drags=
this.drags.reject(function(d){return d==draggable});if(this.drags.length==0){Event.stopObserving(document,"mouseup",this.eventMouseUp);Event.stopObserving(document,"mousemove",this.eventMouseMove);Event.stopObserving(document,"keypress",this.eventKeypress)}},activate:function(draggable){if(draggable.options.delay)this._timeout=setTimeout(function(){Draggables._timeout=null;window.focus();Draggables.activeDraggable=draggable}.bind(this),draggable.options.delay);else{window.focus();this.activeDraggable=
draggable}},deactivate:function(){this.activeDraggable=null},updateDrag:function(event){if(!this.activeDraggable)return;var pointer=[Event.pointerX(event),Event.pointerY(event)];if(this._lastPointer&&this._lastPointer.inspect()==pointer.inspect())return;this._lastPointer=pointer;this.activeDraggable.updateDrag(event,pointer)},endDrag:function(event){if(this._timeout){clearTimeout(this._timeout);this._timeout=null}if(!this.activeDraggable)return;this._lastPointer=null;this.activeDraggable.endDrag(event);
this.activeDraggable=null},keyPress:function(event){if(this.activeDraggable)this.activeDraggable.keyPress(event)},addObserver:function(observer){this.observers.push(observer);this._cacheObserverCallbacks()},removeObserver:function(element){this.observers=this.observers.reject(function(o){return o.element==element});this._cacheObserverCallbacks()},notify:function(eventName,draggable,event){if(this[eventName+"Count"]>0)this.observers.each(function(o){if(o[eventName])o[eventName](eventName,draggable,
event)});if(draggable.options[eventName])draggable.options[eventName](draggable,event)},_cacheObserverCallbacks:function(){["onStart","onEnd","onDrag"].each(function(eventName){Draggables[eventName+"Count"]=Draggables.observers.select(function(o){return o[eventName]}).length})}};
var Draggable=Class.create({initialize:function(element){var defaults={handle:false,reverteffect:function(element,top_offset,left_offset){var dur=Math.sqrt(Math.abs(top_offset^2)+Math.abs(left_offset^2))*0.02;new Effect.Move(element,{x:-left_offset,y:-top_offset,duration:dur,queue:{scope:"_draggable",position:"end"}})},endeffect:function(element){var toOpacity=Object.isNumber(element._opacity)?element._opacity:1;new Effect.Opacity(element,{duration:0.2,from:0.7,to:toOpacity,queue:{scope:"_draggable",
position:"end"},afterFinish:function(){Draggable._dragging[element]=false}})},zindex:1E3,revert:false,quiet:false,scroll:false,scrollSensitivity:20,scrollSpeed:15,snap:false,delay:0};if(!arguments[1]||Object.isUndefined(arguments[1].endeffect))Object.extend(defaults,{starteffect:function(element){element._opacity=Element.getOpacity(element);Draggable._dragging[element]=true;new Effect.Opacity(element,{duration:0.2,from:element._opacity,to:0.7})}});var options=Object.extend(defaults,arguments[1]||
{});this.element=$(element);if(options.handle&&Object.isString(options.handle))this.handle=this.element.down("."+options.handle,0);if(!this.handle)this.handle=$(options.handle);if(!this.handle)this.handle=this.element;if(options.scroll&&!options.scroll.scrollTo&&!options.scroll.outerHTML){options.scroll=$(options.scroll);this._isScrollChild=Element.childOf(this.element,options.scroll)}Element.makePositioned(this.element);this.options=options;this.dragging=false;this.eventMouseDown=this.initDrag.bindAsEventListener(this);
Event.observe(this.handle,"mousedown",this.eventMouseDown);Draggables.register(this)},destroy:function(){Event.stopObserving(this.handle,"mousedown",this.eventMouseDown);Draggables.unregister(this)},currentDelta:function(){return[parseInt(Element.getStyle(this.element,"left")||"0"),parseInt(Element.getStyle(this.element,"top")||"0")]},initDrag:function(event){if(!Object.isUndefined(Draggable._dragging[this.element])&&Draggable._dragging[this.element])return;if(Event.isLeftClick(event)){var src=Event.element(event);
if((tag_name=src.tagName.toUpperCase())&&(tag_name=="INPUT"||tag_name=="SELECT"||tag_name=="OPTION"||tag_name=="BUTTON"||tag_name=="TEXTAREA"))return;var pointer=[Event.pointerX(event),Event.pointerY(event)];var pos=this.element.cumulativeOffset();this.offset=[0,1].map(function(i){return pointer[i]-pos[i]});Draggables.activate(this);Event.stop(event)}},startDrag:function(event){this.dragging=true;if(!this.delta)this.delta=this.currentDelta();if(this.options.zindex){this.originalZ=parseInt(Element.getStyle(this.element,
"z-index")||0);this.element.style.zIndex=this.options.zindex}if(this.options.ghosting){this._clone=this.element.cloneNode(true);this._originallyAbsolute=this.element.getStyle("position")=="absolute";if(!this._originallyAbsolute)Position.absolutize(this.element);this.element.parentNode.insertBefore(this._clone,this.element)}if(this.options.scroll)if(this.options.scroll==window){var where=this._getWindowScroll(this.options.scroll);this.originalScrollLeft=where.left;this.originalScrollTop=where.top}else{this.originalScrollLeft=
this.options.scroll.scrollLeft;this.originalScrollTop=this.options.scroll.scrollTop}Draggables.notify("onStart",this,event);if(this.options.starteffect)this.options.starteffect(this.element)},updateDrag:function(event,pointer){if(!this.dragging)this.startDrag(event);if(!this.options.quiet){Position.prepare();Droppables.show(pointer,this.element)}Draggables.notify("onDrag",this,event);this.draw(pointer);if(this.options.change)this.options.change(this);if(this.options.scroll){this.stopScrolling();var p;
if(this.options.scroll==window)with(this._getWindowScroll(this.options.scroll))p=[left,top,left+width,top+height];else{p=Position.page(this.options.scroll).toArray();p[0]+=this.options.scroll.scrollLeft+Position.deltaX;p[1]+=this.options.scroll.scrollTop+Position.deltaY;p.push(p[0]+this.options.scroll.offsetWidth);p.push(p[1]+this.options.scroll.offsetHeight)}var speed=[0,0];if(pointer[0]<p[0]+this.options.scrollSensitivity)speed[0]=pointer[0]-(p[0]+this.options.scrollSensitivity);if(pointer[1]<p[1]+
this.options.scrollSensitivity)speed[1]=pointer[1]-(p[1]+this.options.scrollSensitivity);if(pointer[0]>p[2]-this.options.scrollSensitivity)speed[0]=pointer[0]-(p[2]-this.options.scrollSensitivity);if(pointer[1]>p[3]-this.options.scrollSensitivity)speed[1]=pointer[1]-(p[3]-this.options.scrollSensitivity);this.startScrolling(speed)}if(Prototype.Browser.WebKit)window.scrollBy(0,0);Event.stop(event)},finishDrag:function(event,success){this.dragging=false;if(this.options.quiet){Position.prepare();var pointer=
[Event.pointerX(event),Event.pointerY(event)];Droppables.show(pointer,this.element)}if(this.options.ghosting){if(!this._originallyAbsolute)Position.relativize(this.element);delete this._originallyAbsolute;Element.remove(this._clone);this._clone=null}var dropped=false;if(success){dropped=Droppables.fire(event,this.element);if(!dropped)dropped=false}if(dropped&&this.options.onDropped)this.options.onDropped(this.element);Draggables.notify("onEnd",this,event);var revert=this.options.revert;if(revert&&
Object.isFunction(revert))revert=revert(this.element);var d=this.currentDelta();if(revert&&this.options.reverteffect){if(dropped==0||revert!="failure")this.options.reverteffect(this.element,d[1]-this.delta[1],d[0]-this.delta[0])}else this.delta=d;if(this.options.zindex)this.element.style.zIndex=this.originalZ;if(this.options.endeffect)this.options.endeffect(this.element);Draggables.deactivate(this);Droppables.reset()},keyPress:function(event){if(event.keyCode!=Event.KEY_ESC)return;this.finishDrag(event,
false);Event.stop(event)},endDrag:function(event){if(!this.dragging)return;this.stopScrolling();this.finishDrag(event,true);Event.stop(event)},draw:function(point){var pos=this.element.cumulativeOffset();if(this.options.ghosting){var r=Position.realOffset(this.element);pos[0]+=r[0]-Position.deltaX;pos[1]+=r[1]-Position.deltaY}var d=this.currentDelta();pos[0]-=d[0];pos[1]-=d[1];if(this.options.scroll&&this.options.scroll!=window&&this._isScrollChild){pos[0]-=this.options.scroll.scrollLeft-this.originalScrollLeft;
pos[1]-=this.options.scroll.scrollTop-this.originalScrollTop}var p=[0,1].map(function(i){return point[i]-pos[i]-this.offset[i]}.bind(this));if(this.options.snap)if(Object.isFunction(this.options.snap))p=this.options.snap(p[0],p[1],this);else if(Object.isArray(this.options.snap))p=p.map(function(v,i){return(v/this.options.snap[i]).round()*this.options.snap[i]}.bind(this));else p=p.map(function(v){return(v/this.options.snap).round()*this.options.snap}.bind(this));var style=this.element.style;if(!this.options.constraint||
this.options.constraint=="horizontal")style.left=p[0]+"px";if(!this.options.constraint||this.options.constraint=="vertical")style.top=p[1]+"px";if(style.visibility=="hidden")style.visibility=""},stopScrolling:function(){if(this.scrollInterval){clearInterval(this.scrollInterval);this.scrollInterval=null;Draggables._lastScrollPointer=null}},startScrolling:function(speed){if(!(speed[0]||speed[1]))return;this.scrollSpeed=[speed[0]*this.options.scrollSpeed,speed[1]*this.options.scrollSpeed];this.lastScrolled=
new Date;this.scrollInterval=setInterval(this.scroll.bind(this),10)},scroll:function(){var current=new Date;var delta=current-this.lastScrolled;this.lastScrolled=current;if(this.options.scroll==window)with(this._getWindowScroll(this.options.scroll)){if(this.scrollSpeed[0]||this.scrollSpeed[1]){var d=delta/1E3;this.options.scroll.scrollTo(left+d*this.scrollSpeed[0],top+d*this.scrollSpeed[1])}}else{this.options.scroll.scrollLeft+=this.scrollSpeed[0]*delta/1E3;this.options.scroll.scrollTop+=this.scrollSpeed[1]*
delta/1E3}Position.prepare();Droppables.show(Draggables._lastPointer,this.element);Draggables.notify("onDrag",this);if(this._isScrollChild){Draggables._lastScrollPointer=Draggables._lastScrollPointer||$A(Draggables._lastPointer);Draggables._lastScrollPointer[0]+=this.scrollSpeed[0]*delta/1E3;Draggables._lastScrollPointer[1]+=this.scrollSpeed[1]*delta/1E3;if(Draggables._lastScrollPointer[0]<0)Draggables._lastScrollPointer[0]=0;if(Draggables._lastScrollPointer[1]<0)Draggables._lastScrollPointer[1]=
0;this.draw(Draggables._lastScrollPointer)}if(this.options.change)this.options.change(this)},_getWindowScroll:function(w){var T,L,W,H;with(w.document){if(w.document.documentElement&&documentElement.scrollTop){T=documentElement.scrollTop;L=documentElement.scrollLeft}else if(w.document.body){T=body.scrollTop;L=body.scrollLeft}if(w.innerWidth){W=w.innerWidth;H=w.innerHeight}else if(w.document.documentElement&&documentElement.clientWidth){W=documentElement.clientWidth;H=documentElement.clientHeight}else{W=
body.offsetWidth;H=body.offsetHeight}}return{top:T,left:L,width:W,height:H}}});Draggable._dragging={};var SortableObserver=Class.create({initialize:function(element,observer){this.element=$(element);this.observer=observer;this.lastValue=Sortable.serialize(this.element)},onStart:function(){this.lastValue=Sortable.serialize(this.element)},onEnd:function(){Sortable.unmark();if(this.lastValue!=Sortable.serialize(this.element))this.observer(this.element)}});
var Sortable={SERIALIZE_RULE:/^[^_\-](?:[A-Za-z0-9\-\_]*)[_](.*)$/,sortables:{},_findRootElement:function(element){while(element.tagName.toUpperCase()!="BODY"){if(element.id&&Sortable.sortables[element.id])return element;element=element.parentNode}},options:function(element){element=Sortable._findRootElement($(element));if(!element)return;return Sortable.sortables[element.id]},destroy:function(element){element=$(element);var s=Sortable.sortables[element.id];if(s){Draggables.removeObserver(s.element);
s.droppables.each(function(d){Droppables.remove(d)});s.draggables.invoke("destroy");delete Sortable.sortables[s.element.id]}},create:function(element){element=$(element);var options=Object.extend({element:element,tag:"li",dropOnEmpty:false,tree:false,treeTag:"ul",overlap:"vertical",constraint:"vertical",containment:element,handle:false,only:false,delay:0,hoverclass:null,ghosting:false,quiet:false,scroll:false,scrollSensitivity:20,scrollSpeed:15,format:this.SERIALIZE_RULE,elements:false,handles:false,
onChange:Prototype.emptyFunction,onUpdate:Prototype.emptyFunction},arguments[1]||{});this.destroy(element);var options_for_draggable={revert:true,quiet:options.quiet,scroll:options.scroll,scrollSpeed:options.scrollSpeed,scrollSensitivity:options.scrollSensitivity,delay:options.delay,ghosting:options.ghosting,constraint:options.constraint,handle:options.handle};if(options.starteffect)options_for_draggable.starteffect=options.starteffect;if(options.reverteffect)options_for_draggable.reverteffect=options.reverteffect;
else if(options.ghosting)options_for_draggable.reverteffect=function(element){element.style.top=0;element.style.left=0};if(options.endeffect)options_for_draggable.endeffect=options.endeffect;if(options.zindex)options_for_draggable.zindex=options.zindex;var options_for_droppable={overlap:options.overlap,containment:options.containment,tree:options.tree,hoverclass:options.hoverclass,onHover:Sortable.onHover};var options_for_tree={onHover:Sortable.onEmptyHover,overlap:options.overlap,containment:options.containment,
hoverclass:options.hoverclass};Element.cleanWhitespace(element);options.draggables=[];options.droppables=[];if(options.dropOnEmpty||options.tree){Droppables.add(element,options_for_tree);options.droppables.push(element)}(options.elements||this.findElements(element,options)||[]).each(function(e,i){var handle=options.handles?$(options.handles[i]):options.handle?$(e).select("."+options.handle)[0]:e;options.draggables.push(new Draggable(e,Object.extend(options_for_draggable,{handle:handle})));Droppables.add(e,
options_for_droppable);if(options.tree)e.treeNode=element;options.droppables.push(e)});if(options.tree)(Sortable.findTreeElements(element,options)||[]).each(function(e){Droppables.add(e,options_for_tree);e.treeNode=element;options.droppables.push(e)});this.sortables[element.identify()]=options;Draggables.addObserver(new SortableObserver(element,options.onUpdate))},findElements:function(element,options){return Element.findChildren(element,options.only,options.tree?true:false,options.tag)},findTreeElements:function(element,
options){return Element.findChildren(element,options.only,options.tree?true:false,options.treeTag)},onHover:function(element,dropon,overlap){if(Element.isParent(dropon,element))return;if(overlap>0.33&&overlap<0.66&&Sortable.options(dropon).tree)return;else if(overlap>0.5){Sortable.mark(dropon,"before");if(dropon.previousSibling!=element){var oldParentNode=element.parentNode;element.style.visibility="hidden";dropon.parentNode.insertBefore(element,dropon);if(dropon.parentNode!=oldParentNode)Sortable.options(oldParentNode).onChange(element);
Sortable.options(dropon.parentNode).onChange(element)}}else{Sortable.mark(dropon,"after");var nextElement=dropon.nextSibling||null;if(nextElement!=element){var oldParentNode=element.parentNode;element.style.visibility="hidden";dropon.parentNode.insertBefore(element,nextElement);if(dropon.parentNode!=oldParentNode)Sortable.options(oldParentNode).onChange(element);Sortable.options(dropon.parentNode).onChange(element)}}},onEmptyHover:function(element,dropon,overlap){var oldParentNode=element.parentNode;
var droponOptions=Sortable.options(dropon);if(!Element.isParent(dropon,element)){var index;var children=Sortable.findElements(dropon,{tag:droponOptions.tag,only:droponOptions.only});var child=null;if(children){var offset=Element.offsetSize(dropon,droponOptions.overlap)*(1-overlap);for(index=0;index<children.length;index+=1)if(offset-Element.offsetSize(children[index],droponOptions.overlap)>=0)offset-=Element.offsetSize(children[index],droponOptions.overlap);else if(offset-Element.offsetSize(children[index],
droponOptions.overlap)/2>=0){child=index+1<children.length?children[index+1]:null;break}else{child=children[index];break}}dropon.insertBefore(element,child);Sortable.options(oldParentNode).onChange(element);droponOptions.onChange(element)}},unmark:function(){if(Sortable._marker)Sortable._marker.hide()},mark:function(dropon,position){var sortable=Sortable.options(dropon.parentNode);if(sortable&&!sortable.ghosting)return;if(!Sortable._marker){Sortable._marker=($("dropmarker")||Element.extend(document.createElement("DIV"))).hide().addClassName("dropmarker").setStyle({position:"absolute"});
document.getElementsByTagName("body").item(0).appendChild(Sortable._marker)}var offsets=dropon.cumulativeOffset();Sortable._marker.setStyle({left:offsets[0]+"px",top:offsets[1]+"px"});if(position=="after")if(sortable.overlap=="horizontal")Sortable._marker.setStyle({left:offsets[0]+dropon.clientWidth+"px"});else Sortable._marker.setStyle({top:offsets[1]+dropon.clientHeight+"px"});Sortable._marker.show()},_tree:function(element,options,parent){var children=Sortable.findElements(element,options)||[];
for(var i=0;i<children.length;++i){var match=children[i].id.match(options.format);if(!match)continue;var child={id:encodeURIComponent(match?match[1]:null),element:element,parent:parent,children:[],position:parent.children.length,container:$(children[i]).down(options.treeTag)};if(child.container)this._tree(child.container,options,child);parent.children.push(child)}return parent},tree:function(element){element=$(element);var sortableOptions=this.options(element);var options=Object.extend({tag:sortableOptions.tag,
treeTag:sortableOptions.treeTag,only:sortableOptions.only,name:element.id,format:sortableOptions.format},arguments[1]||{});var root={id:null,parent:null,children:[],container:element,position:0};return Sortable._tree(element,options,root)},_constructIndex:function(node){var index="";do if(node.id)index="["+node.position+"]"+index;while((node=node.parent)!=null);return index},sequence:function(element){element=$(element);var options=Object.extend(this.options(element),arguments[1]||{});return $(this.findElements(element,
options)||[]).map(function(item){return item.id.match(options.format)?item.id.match(options.format)[1]:""})},setSequence:function(element,new_sequence){element=$(element);var options=Object.extend(this.options(element),arguments[2]||{});var nodeMap={};this.findElements(element,options).each(function(n){if(n.id.match(options.format))nodeMap[n.id.match(options.format)[1]]=[n,n.parentNode];n.parentNode.removeChild(n)});new_sequence.each(function(ident){var n=nodeMap[ident];if(n){n[1].appendChild(n[0]);
delete nodeMap[ident]}})},serialize:function(element){element=$(element);var options=Object.extend(Sortable.options(element),arguments[1]||{});var name=encodeURIComponent(arguments[1]&&arguments[1].name?arguments[1].name:element.id);if(options.tree)return Sortable.tree(element,arguments[1]).children.map(function(item){return[name+Sortable._constructIndex(item)+"[id]="+encodeURIComponent(item.id)].concat(item.children.map(arguments.callee))}).flatten().join("&");else return Sortable.sequence(element,
arguments[1]).map(function(item){return name+"[]="+encodeURIComponent(item)}).join("&")}};Element.isParent=function(child,element){if(!child.parentNode||child==element)return false;if(child.parentNode==element)return true;return Element.isParent(child.parentNode,element)};
Element.findChildren=function(element,only,recursive,tagName){if(!element.hasChildNodes())return null;tagName=tagName.toUpperCase();if(only)only=[only].flatten();var elements=[];$A(element.childNodes).each(function(e){if(e.tagName&&e.tagName.toUpperCase()==tagName&&(!only||Element.classNames(e).detect(function(v){return only.include(v)})))elements.push(e);if(recursive){var grandchildren=Element.findChildren(e,only,recursive,tagName);if(grandchildren)elements.push(grandchildren)}});return elements.length>
0?elements.flatten():[]};Element.offsetSize=function(element,type){return element["offset"+(type=="vertical"||type=="height"?"Height":"Width")]};
BrainstormJs.Forms.BaseListForm=Class.create(BrainstormJs.Forms.BaseForm,{isListForm:true,list:false,editMode:false,editingObject:false,behavior:false,editHelp:false,toolbar:false,toolbarButtons:false,eventsCached:false,fxOnItemMouseEnter:false,fxOnItemMouseLeave:false,fxOnItemDelete:false,listClass:"editableList",itemClass:"editableItem",editingListClass:"editingList",editingItemClass:"editingItem",deletingItemClass:"deletingItem",hoverItemClass:"hoverItem",activeEditPanelClass:"activeEditPanel",
deleteConfirmText:false,hoverDelay:0,hoverTimer:false,initialize:function($super,profile,options){$super(profile,options);this.list=$(options.list);this.hoverDelay=options.hoverDelay||this.hoverDelay;var listContainer=this.list.up();this.deleteConfirmText=options.deleteConfirmText||false;this.toolbar=listContainer.down("div.toolbar");if(this.toolbar){this.toolbarButtons=this.toolbar.down("div.buttons");var addItemLink=this.toolbarButtons.down("a.addListItem");if(addItemLink)addItemLink.observe("click",
function(e){this.showForm();e.stop()}.bind(this));var editListLink=this.toolbarButtons.down("a.editList");if(editListLink)editListLink.observe("click",function(e){this.toggleListEditing(true);e.stop()}.bind(this));this.editHelp=this.toolbar.down("div.editHelp");if(this.editHelp){var uneditLink=this.editHelp.down("a.unedit");if(uneditLink)uneditLink.observe("click",function(e){this.toggleListEditing(false);e.stop()}.bind(this))}}var listItems=this.list.select("div."+this.itemClass);for(var i=0,j=listItems.length;i<
j;i++){var listItem=listItems[i];this.wireListItemEvents(listItem)}this.checkForEmptyList();this.refreshSortable()},wireListItemEvents:function(listItem){if(!this.eventsCached){this.fxOnItemMouseEnter=this.onItemMouseEnter.bindAsEventListener(this);this.fxOnItemMouseLeave=this.onItemMouseLeave.bindAsEventListener(this);this.fxOnItemEdit=function(e){this.onItemEdit(e.element());e.stop()}.bindAsEventListener(this);this.fxOnItemDelete=function(e){this.onItemDelete(e.element());e.stop()}.bindAsEventListener(this);
this.eventsCached=true}listItem.observe("mouseenter",this.fxOnItemMouseEnter);listItem.observe("mouseleave",this.fxOnItemMouseLeave);var editPanel=listItem.down("div.editPanel");if(editPanel){var deleteLink=editPanel.down("a.delete");if(deleteLink)deleteLink.observe("click",this.fxOnItemDelete);var editLink=editPanel.down("a.edit");if(editLink)editLink.observe("click",this.fxOnItemEdit)}},showForm:function($super,options){$super(options);this.toggleToolbar(false)},closeForm:function($super,options){$super(options);
if(this.editingObject){this.editingObject=false;var editContainer=this.container.up("div."+this.editingItemClass);if(editContainer){editContainer.removeClassName(this.editingItemClass);editContainer.removeClassName(this.hoverItemClass);editContainer.down("div.editPanel").removeClassName(this.activeEditPanelClass)}}this.toggleToolbar(true)},toggleListEditing:function(enable){this.editMode=enable;if(enable){var editHelp=this.editHelp;this.toggleToolbarButtons(false,function(){Effect.Appear(editHelp,
{duration:0.5})})}else Effect.Fade(this.editHelp,{duration:0.5,afterFinish:function(){this.toggleToolbarButtons(true)}.bind(this)});this.list[enable?"addClassName":"removeClassName"](this.editingListClass)},toggleToolbar:function(show){if(!this.toolbar)return;Effect[show?"BlindDown":"BlindUp"](this.toolbar,{duration:0.5})},toggleToolbarButtons:function(show,afterFinish){if(!this.toolbarButtons)return;Effect[show?"Appear":"Fade"](this.toolbarButtons,{duration:0.5,afterFinish:afterFinish?afterFinish:
function(){}})},newObjectCreated:function(domElement){var newListItems=[];if(domElement&&domElement.length&&domElement.length>0)domElement.each(function(el){newListItems.push(el)});else if(domElement&&typeof domElement.length=="undefined")newListItems.push(domElement);var newListElement=null;for(var i=0;i<newListItems.length;i++){var newListItem=newListItems[i];if(!newListItem)continue;this.list.insert(newListItem.HTML);newListElement=$(newListItem.Id);this.wireListItemEvents(newListElement)}this.closeForm({afterFinish:function(){this.checkForEmptyList();
for(var i=0;i<newListItems.length;i++){var newListItem=$(newListItems[i].Id);new Effect.BlindDown(newListItem,{duration:0.5});new Effect.Highlight(newListItem,{delay:0.5})}}.bind(this)});this.refreshSortable();return newListElement},reorderList:function(orderableList){var serializedOrder=bsCommon.serializeSortable(orderableList);var aftersave=this.reorderComplete.bind(this);this.saveNewOrder(this.profile.id,serializedOrder,aftersave)},saveNewOrder:function(profileId,serializedOrder,afterSave){Brainstorm.Web.Services.IdeaTasks.ReorderObjects(profileId,
this.editObjectType,serializedOrder,afterSave,bsCommon.ajaxCallError)},reorderComplete:function(){bsCommon.showSuccess("New "+this.friendlyObjectName+" order has been saved.")},editObject:function(listItem){listItem.addClassName(this.editingItemClass);this.editingObject=true;this.showForm({editMode:true,insertInto:listItem});this.loadObjectValues(listItem)},loadObjectValues:function($super,objectLi){var idParts=objectLi.id.split("_");this.editObjectId=parseInt(idParts[1],10);this.editObjectElement=
objectLi},deleteObject:function(objectLi){bsCommon.confirm({title:"Removal Confirmation",text:this.deleteConfirmText||"Are you sure you want to remove this "+this.friendlyObjectName+"?",width:450,confirmText:"Yes!",cancelText:"Cancel",onConfirm:function(){this.onDeleteConfirmed(objectLi)}.bind(this)})},onDeleteConfirmed:function(objectLi,context){var idParts=objectLi.id.split("_");var objectType=idParts[0];var objectId=parseInt(idParts[1],10);objectLi.addClassName(this.deletingItemClass);objectLi.insert({top:'<div class="deleteMsg">Removing - please wait...</div>'});
this.callDeleteObject(objectLi,objectType,objectId,context)},callDeleteObject:function(objectLi,objectType,objectId){Brainstorm.Web.Services.IdeaTasks.DeleteObject(this.profile.id,objectType,objectId,this.objectDeleted.bind(this),bsCommon.ajaxCallError,objectLi)},objectDeleted:function(returnval,objectLi){Effect.BlindUp(objectLi,{delay:0.5,duration:1,afterFinish:function(){objectLi.remove();this.checkForEmptyList()}.bind(this)})},checkForEmptyList:function(){var emptyListMessage=this.list.previous();
if(emptyListMessage&&emptyListMessage.hasClassName("emptyList"));else emptyListMessage=false;if(!this.list.firstDescendant()){if(emptyListMessage)emptyListMessage.show();else{var emptyMsg=(new Element("div",{"class":"emptyList"})).update(this.emptyMessage);if(this.options.emptyMessageCssClass)emptyMsg.addClassName(this.options.emptyMessageCssClass);this.list.insert({before:emptyMsg})}if(this.listEditButton)this.listEditButton.hide();if(this.listUneditButton)this.listUneditButton.hide()}else if(emptyListMessage){emptyListMessage.hide();
if(this.listEditButton)this.listEditButton.show()}},onItemMouseEnter:function(e){var item=e.element();if(!this.hoverDelay||this.hoverDelay<=0)this.displayEditPanel(true,item,false,false);else this.hoverTimer=setTimeout(function(){this.displayEditPanel(true,item,false,true)}.bind(this),this.hoverDelay*1E3)},onItemMouseLeave:function(e){if(this.hoverTimer)clearTimeout(this.hoverTimer);var item=e.element();this.displayEditPanel(false,item,true,false)},onItemDelete:function(listItem){var listItem=this.getListItem(listItem);
this.deleteObject(listItem)},onItemEdit:function(listItem){var listItem=this.getListItem(listItem);this.editObject(listItem)},displayEditPanel:function(display,item,mouseleave,animate){if(this.editingExisting===true||!this.editMode)return;var listItem=this.getListItem(item);var hoverItems=this.list.select("div."+this.hoverItemClass);for(var i=0,j=hoverItems.length;i<j;i++)hoverItems[i].removeClassName(this.hoverItemClass);listItem[display?"addClassName":"removeClassName"](this.hoverItemClass);var editPanel=
listItem.down("div.editPanel");var isDragging=Draggable._dragging[listItem];if(!isDragging&&!listItem.hasClassName(this.deletingItemClass))if(display){editPanel.addClassName(this.activeEditPanelClass);if(animate)editPanel.appear({duration:0.5});else editPanel.show()}else{editPanel.removeClassName(this.activeEditPanelClass);editPanel.hide()}},refreshSortable:function(){Sortable.create(this.list,{dropOnEmpty:false,tag:"div",only:this.itemClass,handle:"reorder",constraint:"vertical",scroll:window,onUpdate:function(list){this.reorderList(list)}.bind(this)})},
getListItem:function(element){var listItem=element;if(listItem.tagName.toLowerCase()!="div"||!listItem.hasClassName(this.itemClass))listItem=listItem.up("div."+this.itemClass);return listItem}});
BrainstormJs.Forms.Parts.TodoItemForm=Class.create(BrainstormJs.Forms.BaseListForm,{part:false,fieldTitle:false,initialize:function($super,part,options){options=options||{};options.createTitle="Add a new list item";options.editTitle="Edit list item";options.emptyMessage="This list does not have any items.";options.hoverDelay=1;this.part=part;var profile=part.tab.partContainer.profile;$super(profile,options);this.toggleListEditing(true);this.editObjectType="TodoListItem";this.friendlyObjectName="list item"},
createFields:function($super){this.fieldTitle=new BrainstormJs.Forms.Fields.TextBox({title:"Title",required:true,maxLength:180,submitOnEnter:true});this.registerField(this.fieldTitle)},createNewObject:function($super){$super();Brainstorm.Web.Services.Parts.AddTodoItem(this.part.partId,this.fieldTitle.getValue(),this.newObjectCreated.bind(this),bsCommon.ajaxCallError,this)},loadObjectValues:function($super,objectLi){$super(objectLi);var data=objectLi.down(".data");this.fieldTitle.setValue(data.down(".text").value)},
saveEditedObject:function($super){$super();Brainstorm.Web.Services.Parts.UpdateTodoItem(this.editObjectId,this.fieldTitle.getValue(),this.todoItemSaved.bind(this),bsCommon.ajaxCallError)},callDeleteObject:function($super,listItem,objectType,objectId){Brainstorm.Web.Services.Parts.DeleteTodoItem(objectId,this.objectDeleted.bind(this),bsCommon.ajaxCallError,listItem)},todoItemSaved:function(editedTodoItem){var text=this.editObjectElement.down("span");text.innerHTML=editedTodoItem.Text;var data=this.editObjectElement.down(".data");
data.down(".text").value=editedTodoItem.Text;this.closeForm({highlight:text})},reorderList:function($super,orderableList){Brainstorm.Web.Services.Parts.ReorderTodoItems(this.part.partId,bsCommon.serializeSortable(orderableList),this.reorderComplete.bind(this),bsCommon.ajaxCallError)}});
BrainstormJs.Forms.Parts.TodoListForm=Class.create(BrainstormJs.Forms.BaseForm,{fieldTitle:false,fieldItems:false,initialize:function($super,profile,options){options=options||{};options.createTitle="Add a new to-do list";options.editTitle="Edit list";$super(profile,options);this.editObjectType="ListPart";this.friendlyObjectName="list"},createFields:function($super){this.fieldTitle=new BrainstormJs.Forms.Fields.TextBox({title:"Title",required:true,maxLength:100,submitOnEnter:true,dataSelector:".data-Title"});
this.fieldItems=new BrainstormJs.Forms.Fields.TextArea({title:"Initial Items (one per line)",enableWysiwyg:false,required:true});this.registerField(this.fieldTitle);this.registerField(this.fieldItems)},createNewObject:function($super){$super();Brainstorm.Web.Services.Parts.CreateTodoList(this.profile.partContainer.activeTab.id,this.fieldTitle.getValue(),this.fieldItems.getValue(),this.newListCreated.bind(this),this.handleAjaxError.bind(this),this)},newListCreated:function(domElement){this.profile.partContainer.activeTab.registerNewPart(domElement,
this)}});
BrainstormJs.Forms.Parts.DocumentPartForm=Class.create(BrainstormJs.Forms.BaseForm,{fieldTitle:false,initialize:function($super,profile,options){options=options||{};options.createTitle="Add a new document section";$super(profile,options);this.friendlyObjectName="document section"},createFields:function($super){this.fieldTitle=new BrainstormJs.Forms.Fields.TextBox({title:"Section Name",required:true,maxLength:100,submitOnEnter:true});this.registerField(this.fieldTitle)},createNewObject:function($super){Brainstorm.Web.Services.Parts.CreateDocumentPart(this.profile.partContainer.activeTab.id,this.fieldTitle.getValue(),
this.partCreated.bind(this),this.handleAjaxError.bind(this))},partCreated:function(domElement){this.profile.partContainer.activeTab.registerNewPart(domElement,this)}});
BrainstormJs.Forms.Parts.LinkPartForm=Class.create(BrainstormJs.Forms.BaseForm,{fieldTitle:false,initialize:function($super,profile,options){options=options||{};options.createTitle="Add a new links section";$super(profile,options);this.friendlyObjectName="links section"},createFields:function($super){this.fieldTitle=new BrainstormJs.Forms.Fields.TextBox({title:"Section Name",required:true,maxLength:100,submitOnEnter:true});this.registerField(this.fieldTitle)},createNewObject:function($super){Brainstorm.Web.Services.Parts.CreateLinkPart(this.profile.partContainer.activeTab.id,
this.fieldTitle.getValue(),this.partCreated.bind(this),this.handleAjaxError.bind(this))},partCreated:function(domElement){this.profile.partContainer.activeTab.registerNewPart(domElement,this)}});
BrainstormJs.Controls.Parts.AddPartsBar=Class.create({container:false,div:false,formContainer:false,forms:false,addLinks:false,isFormOpen:false,initialize:function(div,container){this.div=div;this.container=container;this.formContainer=this.div.previous("div.addPartFormContainer");this.forms=new Hash;this.addLinks=this.div.select("a.addPart");for(var i=0,j=this.addLinks.length;i<j;i++)this.addLinks[i].observe("click",function(e){this.onAddPart(e.element());e.stop()}.bind(this))},onAddPart:function(linkClicked){if(linkClicked.tagName.toLowerCase()!=
"a")linkClicked=linkClicked.up("a");if(this.isFormOpen){Effect.Shake(this.div,{distance:3,duration:0.75});return}this.div.fade({to:0.6});var formName=linkClicked.rel;var form=this.forms.get(formName);if(!form){form=new BrainstormJs.Forms.Parts[formName](this.container.profile,{parentContainer:this.formContainer,afterClose:this.afterFormClose.bind(this)});this.forms.set(formName,form)}form.showForm({linkClicked:linkClicked});this.isFormOpen=true},afterFormClose:function(){this.div.appear();this.isFormOpen=
false}});
BrainstormJs.Controls.Parts.BasePart=Class.create({container:false,tab:false,partId:false,menu:false,menuInitialized:false,mousingOver:false,fadeInEffects:false,fadeOutEffects:false,titleEditLink:false,titleEditor:false,editLink:false,moveLink:false,archiveLink:false,baseForm:false,fxShowMoveMenu:false,initialize:function(container,tab){this.container=container;this.partId=parseInt(this.container.id.split("_")[1],10);this.tab=tab;this.menu=this.container.down("div.partTitle div.partMenu");this.titleEditLink=
this.container.down("a.editTitle");this.fadeInEffects=[];this.fadeOutEffects=[];if(this.titleEditLink)this.titleEditor=new BrainstormJs.Controls.InLineEditor({contentEl:this.titleEditLink.previous("span.text"),editLink:this.titleEditLink,container:this.titleEditLink.previous("div.inlineEditor"),hideElements:[this.menu],restoreColor:"#ECECEC",serviceMethod:Brainstorm.Web.Services.Parts.UpdateTitle,serviceParams:[this.partId]});if(this.menu){this.container.observe("mouseenter",this.onMouseEnter.bind(this));
this.container.observe("mouseleave",this.onMouseLeave.bind(this));this.editLink=this.menu.down("a.editPart");this.moveLink=this.menu.down("a.movePart");this.archiveLink=this.menu.down("a.archivePart");if(this.archiveLink)this.archiveLink.observe("click",function(e){this.tab.startArchivePart(this);e.stop()}.bind(this));if(this.editLink)this.editLink.observe("click",function(e){this.onEdit(e.element());e.stop()}.bind(this));this.fxShowMoveMenu=function(e){this.showMoveMenu(e.element());e.stop()}.bind(this)}},
onMouseEnter:function(){this.fadeOutEffects.each(function(effect){effect.cancel()});this.fadeOutEffects=[];if(this.titleEditor&&this.titleEditor.visible())return;this.showMenu()},onMouseLeave:function(){this.fadeInEffects.each(function(effect){effect.cancel()});this.fadeInEffects=[];if(this.titleEditor&&this.titleEditor.visible())return;this.hideMenu()},showMenu:function(){if(this.menu&&!this.menuInitialized){var toggles=this.menu.select("a");for(var i=0,j=toggles.length;i<j;i++){var toggle=toggles[i];
toggle.identify();new Tip(toggle,"<b>"+toggle.rel+"</b>",{style:"darkgrey",stem:"bottomRight",hook:{tip:"bottomRight",target:"topRight"},hideAfter:0.1,hideOn:{event:"click"},offset:{x:-5,y:7},width:"auto",border:5,radius:5});if(toggle.hasClassName("movePart"))toggle.observe("click",this.fxShowMoveMenu)}this.menuInitialized=true}if(!this.editingTitle){this.fadeInEffects.push(Effect.Appear(this.menu,{duration:0.5}));this.fadeInEffects.push(Effect.Appear(this.titleEditLink,{duration:0.5}))}},hideMenu:function(){if(!this.editingTitle){if(this.menu)this.fadeOutEffects.push(Effect.Fade(this.menu,
{duration:0.25}));if(this.titleEditLink)this.fadeOutEffects.push(Effect.Fade(this.titleEditLink,{duration:0.25}))}},showMoveMenu:function(linkClicked){this.tab.partContainer.showMoveTabMenu(linkClicked,this,this.tab.id)},onEdit:function(linkClicked){console.info("No concrete edit functionality defined for: %o",this)}});
var FlashDetect=new function(){var self=this;self.installed=false;self.raw="";self.major=-1;self.minor=-1;self.revision=-1;self.revisionStr="";var activeXDetectRules=[{"name":"ShockwaveFlash.ShockwaveFlash.7","version":function(obj){return getActiveXVersion(obj)}},{"name":"ShockwaveFlash.ShockwaveFlash.6","version":function(obj){var version="6,0,21";try{obj.AllowScriptAccess="always";version=getActiveXVersion(obj)}catch(err){}return version}},{"name":"ShockwaveFlash.ShockwaveFlash","version":function(obj){return getActiveXVersion(obj)}}];
var getActiveXVersion=function(activeXObj){var version=-1;try{version=activeXObj.GetVariable("$version")}catch(err){}return version};var getActiveXObject=function(name){var obj=-1;try{obj=new ActiveXObject(name)}catch(err){}return obj};var parseActiveXVersion=function(str){var versionArray=str.split(",");return{"raw":str,"major":parseInt(versionArray[0].split(" ")[1],10),"minor":parseInt(versionArray[1],10),"revision":parseInt(versionArray[2],10),"revisionStr":versionArray[2]}};var parseStandardVersion=
function(str){var descParts=str.split(/ +/);var majorMinor=descParts[2].split(/\./);var revisionStr=descParts[3];return{"raw":str,"major":parseInt(majorMinor[0],10),"minor":parseInt(majorMinor[1],10),"revisionStr":revisionStr,"revision":parseRevisionStrToInt(revisionStr)}};var parseRevisionStrToInt=function(str){return parseInt(str.replace(/[a-zA-Z]/g,""),10)||self.revision};self.majorAtLeast=function(version){return self.major>=version};self.FlashDetect=function(){if(navigator.plugins&&navigator.plugins.length>
0){var type="application/x-shockwave-flash";var mimeTypes=navigator.mimeTypes;if(mimeTypes&&mimeTypes[type]&&mimeTypes[type].enabledPlugin&&mimeTypes[type].enabledPlugin.description){var version=mimeTypes[type].enabledPlugin.description;var versionObj=parseStandardVersion(version);self.raw=versionObj.raw;self.major=versionObj.major;self.minor=versionObj.minor;self.revisionStr=versionObj.revisionStr;self.revision=versionObj.revision;self.installed=true}}else if(navigator.appVersion.indexOf("Mac")==
-1&&window.execScript){var version=-1;for(var i=0;i<activeXDetectRules.length&&version==-1;i++){var obj=getActiveXObject(activeXDetectRules[i].name);if(typeof obj=="object"){self.installed=true;version=activeXDetectRules[i].version(obj);if(version!=-1){var versionObj=parseActiveXVersion(version);self.raw=versionObj.raw;self.major=versionObj.major;self.minor=versionObj.minor;self.revision=versionObj.revision;self.revisionStr=versionObj.revisionStr}}}}}()};FlashDetect.release="1.0.3";var SWFUpload;
var swfobject;if(SWFUpload==undefined)SWFUpload=function(settings){this.initSWFUpload(settings)};
SWFUpload.prototype.initSWFUpload=function(userSettings){try{this.customSettings={};this.settings={};this.eventQueue=[];this.movieName="SWFUpload_"+SWFUpload.movieCount++;this.movieElement=null;SWFUpload.instances[this.movieName]=this;this.initSettings(userSettings);this.loadSupport();if(this.swfuploadPreload())this.loadFlash();this.displayDebugInfo()}catch(ex){delete SWFUpload.instances[this.movieName];throw ex;}};SWFUpload.instances={};SWFUpload.movieCount=0;SWFUpload.version="2.5.0 2010-01-15 Beta 2";
SWFUpload.QUEUE_ERROR={QUEUE_LIMIT_EXCEEDED:-100,FILE_EXCEEDS_SIZE_LIMIT:-110,ZERO_BYTE_FILE:-120,INVALID_FILETYPE:-130};SWFUpload.UPLOAD_ERROR={HTTP_ERROR:-200,MISSING_UPLOAD_URL:-210,IO_ERROR:-220,SECURITY_ERROR:-230,UPLOAD_LIMIT_EXCEEDED:-240,UPLOAD_FAILED:-250,SPECIFIED_FILE_ID_NOT_FOUND:-260,FILE_VALIDATION_FAILED:-270,FILE_CANCELLED:-280,UPLOAD_STOPPED:-290,RESIZE:-300};SWFUpload.FILE_STATUS={QUEUED:-1,IN_PROGRESS:-2,ERROR:-3,COMPLETE:-4,CANCELLED:-5};SWFUpload.UPLOAD_TYPE={NORMAL:-1,RESIZED:-2};
SWFUpload.BUTTON_ACTION={SELECT_FILE:-100,SELECT_FILES:-110,START_UPLOAD:-120,JAVASCRIPT:-130,NONE:-130};SWFUpload.CURSOR={ARROW:-1,HAND:-2};SWFUpload.WINDOW_MODE={WINDOW:"window",TRANSPARENT:"transparent",OPAQUE:"opaque"};SWFUpload.RESIZE_ENCODING={JPEG:-1,PNG:-2};
SWFUpload.completeURL=function(url){try{var path="",indexSlash=-1;if(typeof url!=="string"||url.match(/^https?:\/\//i)||url.match(/^\//)||url==="")return url;indexSlash=window.location.pathname.lastIndexOf("/");if(indexSlash<=0)path="/";else path=window.location.pathname.substr(0,indexSlash)+"/";return path+url}catch(ex){return url}};SWFUpload.onload=function(){};
SWFUpload.prototype.initSettings=function(userSettings){this.ensureDefault=function(settingName,defaultValue){var setting=userSettings[settingName];if(setting!=undefined)this.settings[settingName]=setting;else this.settings[settingName]=defaultValue};this.ensureDefault("upload_url","");this.ensureDefault("preserve_relative_urls",false);this.ensureDefault("file_post_name","Filedata");this.ensureDefault("post_params",{});this.ensureDefault("use_query_string",false);this.ensureDefault("requeue_on_error",
false);this.ensureDefault("http_success",[]);this.ensureDefault("assume_success_timeout",0);this.ensureDefault("file_types","*.*");this.ensureDefault("file_types_description","All Files");this.ensureDefault("file_size_limit",0);this.ensureDefault("file_upload_limit",0);this.ensureDefault("file_queue_limit",0);this.ensureDefault("flash_url","swfupload.swf");this.ensureDefault("flash9_url","swfupload_fp9.swf");this.ensureDefault("prevent_swf_caching",true);this.ensureDefault("button_image_url","");
this.ensureDefault("button_width",1);this.ensureDefault("button_height",1);this.ensureDefault("button_text","");this.ensureDefault("button_text_style","color: #000000; font-size: 16pt;");this.ensureDefault("button_text_top_padding",0);this.ensureDefault("button_text_left_padding",0);this.ensureDefault("button_action",SWFUpload.BUTTON_ACTION.SELECT_FILES);this.ensureDefault("button_disabled",false);this.ensureDefault("button_placeholder_id","");this.ensureDefault("button_placeholder",null);this.ensureDefault("button_cursor",
SWFUpload.CURSOR.ARROW);this.ensureDefault("button_window_mode",SWFUpload.WINDOW_MODE.WINDOW);this.ensureDefault("debug",false);this.settings.debug_enabled=this.settings.debug;this.settings.return_upload_start_handler=this.returnUploadStart;this.ensureDefault("swfupload_preload_handler",null);this.ensureDefault("swfupload_load_failed_handler",null);this.ensureDefault("swfupload_loaded_handler",null);this.ensureDefault("file_dialog_start_handler",null);this.ensureDefault("file_queued_handler",null);
this.ensureDefault("file_queue_error_handler",null);this.ensureDefault("file_dialog_complete_handler",null);this.ensureDefault("upload_resize_start_handler",null);this.ensureDefault("upload_start_handler",null);this.ensureDefault("upload_progress_handler",null);this.ensureDefault("upload_error_handler",null);this.ensureDefault("upload_success_handler",null);this.ensureDefault("upload_complete_handler",null);this.ensureDefault("mouse_click_handler",null);this.ensureDefault("mouse_out_handler",null);
this.ensureDefault("mouse_over_handler",null);this.ensureDefault("debug_handler",this.debugMessage);this.ensureDefault("custom_settings",{});this.customSettings=this.settings.custom_settings;if(!!this.settings.prevent_swf_caching){this.settings.flash_url=this.settings.flash_url+(this.settings.flash_url.indexOf("?")<0?"?":"&")+"preventswfcaching="+(new Date).getTime();this.settings.flash9_url=this.settings.flash9_url+(this.settings.flash9_url.indexOf("?")<0?"?":"&")+"preventswfcaching="+(new Date).getTime()}if(!this.settings.preserve_relative_urls){this.settings.upload_url=
SWFUpload.completeURL(this.settings.upload_url);this.settings.button_image_url=SWFUpload.completeURL(this.settings.button_image_url)}delete this.ensureDefault};SWFUpload.prototype.loadSupport=function(){this.support={loading:swfobject.hasFlashPlayerVersion("9.0.28"),imageResize:swfobject.hasFlashPlayerVersion("10.0.0")}};
SWFUpload.prototype.loadFlash=function(){var targetElement,tempParent,wrapperType,flashHTML,els;if(!this.support.loading){this.queueEvent("swfupload_load_failed_handler",["Flash Player doesn't support SWFUpload"]);return}if(document.getElementById(this.movieName)!==null){this.support.loading=false;this.queueEvent("swfupload_load_failed_handler",["Element ID already in use"]);return}targetElement=document.getElementById(this.settings.button_placeholder_id)||this.settings.button_placeholder;if(targetElement==
undefined){this.support.loading=false;this.queueEvent("swfupload_load_failed_handler",["button place holder not found"]);return}wrapperType=(targetElement.currentStyle&&targetElement.currentStyle["display"]||window.getComputedStyle&&document.defaultView.getComputedStyle(targetElement,null).getPropertyValue("display"))!=="block"?"span":"div";tempParent=document.createElement(wrapperType);flashHTML=this.getFlashHTML();try{tempParent.innerHTML=flashHTML}catch(ex){this.support.loading=false;this.queueEvent("swfupload_load_failed_handler",
["Exception loading Flash HTML into placeholder"]);return}els=tempParent.getElementsByTagName("object");if(!els||els.length>1||els.length===0){this.support.loading=false;this.queueEvent("swfupload_load_failed_handler",["Unable to find movie after adding to DOM"]);return}else if(els.length===1)this.movieElement=els[0];targetElement.parentNode.replaceChild(tempParent.firstChild,targetElement);if(window[this.movieName]==undefined)window[this.movieName]=this.getMovieElement()};
SWFUpload.prototype.getFlashHTML=function(flashVersion){return['<object id="',this.movieName,'" type="application/x-shockwave-flash" data="',this.support.imageResize?this.settings.flash_url:this.settings.flash9_url,'" width="',this.settings.button_width,'" height="',this.settings.button_height,'" class="swfupload">','<param name="wmode" value="',this.settings.button_window_mode,'" />','<param name="movie" value="',this.support.imageResize?this.settings.flash_url:this.settings.flash9_url,'" />','<param name="quality" value="high" />',
'<param name="allowScriptAccess" value="always" />','<param name="flashvars" value="'+this.getFlashVars()+'" />',"</object>"].join("")};
SWFUpload.prototype.getFlashVars=function(){var httpSuccessString,paramString;paramString=this.buildParamString();httpSuccessString=this.settings.http_success.join(",");return["movieName=",encodeURIComponent(this.movieName),"&amp;uploadURL=",encodeURIComponent(this.settings.upload_url),"&amp;useQueryString=",encodeURIComponent(this.settings.use_query_string),"&amp;requeueOnError=",encodeURIComponent(this.settings.requeue_on_error),"&amp;httpSuccess=",encodeURIComponent(httpSuccessString),"&amp;assumeSuccessTimeout=",
encodeURIComponent(this.settings.assume_success_timeout),"&amp;params=",encodeURIComponent(paramString),"&amp;filePostName=",encodeURIComponent(this.settings.file_post_name),"&amp;fileTypes=",encodeURIComponent(this.settings.file_types),"&amp;fileTypesDescription=",encodeURIComponent(this.settings.file_types_description),"&amp;fileSizeLimit=",encodeURIComponent(this.settings.file_size_limit),"&amp;fileUploadLimit=",encodeURIComponent(this.settings.file_upload_limit),"&amp;fileQueueLimit=",encodeURIComponent(this.settings.file_queue_limit),
"&amp;debugEnabled=",encodeURIComponent(this.settings.debug_enabled),"&amp;buttonImageURL=",encodeURIComponent(this.settings.button_image_url),"&amp;buttonWidth=",encodeURIComponent(this.settings.button_width),"&amp;buttonHeight=",encodeURIComponent(this.settings.button_height),"&amp;buttonText=",encodeURIComponent(this.settings.button_text),"&amp;buttonTextTopPadding=",encodeURIComponent(this.settings.button_text_top_padding),"&amp;buttonTextLeftPadding=",encodeURIComponent(this.settings.button_text_left_padding),
"&amp;buttonTextStyle=",encodeURIComponent(this.settings.button_text_style),"&amp;buttonAction=",encodeURIComponent(this.settings.button_action),"&amp;buttonDisabled=",encodeURIComponent(this.settings.button_disabled),"&amp;buttonCursor=",encodeURIComponent(this.settings.button_cursor)].join("")};SWFUpload.prototype.getMovieElement=function(){if(this.movieElement==undefined)this.movieElement=document.getElementById(this.movieName);if(this.movieElement===null)throw"Could not find Flash element";return this.movieElement};
SWFUpload.prototype.buildParamString=function(){var name,postParams,paramStringPairs=[];postParams=this.settings.post_params;if(typeof postParams==="object")for(name in postParams)if(postParams.hasOwnProperty(name))paramStringPairs.push(encodeURIComponent(name.toString())+"="+encodeURIComponent(postParams[name].toString()));return paramStringPairs.join("&amp;")};
SWFUpload.prototype.destroy=function(){var movieElement;try{this.cancelUpload(null,false);movieElement=this.cleanUp();if(movieElement)try{movieElement.parentNode.removeChild(movieElement)}catch(ex){}window[this.movieName]=null;SWFUpload.instances[this.movieName]=null;delete SWFUpload.instances[this.movieName];this.movieElement=null;this.settings=null;this.customSettings=null;this.eventQueue=null;this.movieName=null;return true}catch(ex2){return false}};
SWFUpload.prototype.displayDebugInfo=function(){this.debug(["---SWFUpload Instance Info---\n","Version: ",SWFUpload.version,"\n","Movie Name: ",this.movieName,"\n","Settings:\n","\t","upload_url:               ",this.settings.upload_url,"\n","\t","flash_url:                ",this.settings.flash_url,"\n","\t","flash9_url:                ",this.settings.flash9_url,"\n","\t","use_query_string:         ",this.settings.use_query_string.toString(),"\n","\t","requeue_on_error:         ",this.settings.requeue_on_error.toString(),
"\n","\t","http_success:             ",this.settings.http_success.join(", "),"\n","\t","assume_success_timeout:   ",this.settings.assume_success_timeout,"\n","\t","file_post_name:           ",this.settings.file_post_name,"\n","\t","post_params:              ",this.settings.post_params.toString(),"\n","\t","file_types:               ",this.settings.file_types,"\n","\t","file_types_description:   ",this.settings.file_types_description,"\n","\t","file_size_limit:          ",this.settings.file_size_limit,
"\n","\t","file_upload_limit:        ",this.settings.file_upload_limit,"\n","\t","file_queue_limit:         ",this.settings.file_queue_limit,"\n","\t","debug:                    ",this.settings.debug.toString(),"\n","\t","prevent_swf_caching:      ",this.settings.prevent_swf_caching.toString(),"\n","\t","button_placeholder_id:    ",this.settings.button_placeholder_id.toString(),"\n","\t","button_placeholder:       ",this.settings.button_placeholder?"Set":"Not Set","\n","\t","button_image_url:         ",
this.settings.button_image_url.toString(),"\n","\t","button_width:             ",this.settings.button_width.toString(),"\n","\t","button_height:            ",this.settings.button_height.toString(),"\n","\t","button_text:              ",this.settings.button_text.toString(),"\n","\t","button_text_style:        ",this.settings.button_text_style.toString(),"\n","\t","button_text_top_padding:  ",this.settings.button_text_top_padding.toString(),"\n","\t","button_text_left_padding: ",this.settings.button_text_left_padding.toString(),
"\n","\t","button_action:            ",this.settings.button_action.toString(),"\n","\t","button_cursor:            ",this.settings.button_cursor.toString(),"\n","\t","button_disabled:          ",this.settings.button_disabled.toString(),"\n","\t","custom_settings:          ",this.settings.custom_settings.toString(),"\n","Event Handlers:\n","\t","swfupload_preload_handler assigned:  ",(typeof this.settings.swfupload_preload_handler==="function").toString(),"\n","\t","swfupload_load_failed_handler assigned:  ",
(typeof this.settings.swfupload_load_failed_handler==="function").toString(),"\n","\t","swfupload_loaded_handler assigned:  ",(typeof this.settings.swfupload_loaded_handler==="function").toString(),"\n","\t","mouse_click_handler assigned:       ",(typeof this.settings.mouse_click_handler==="function").toString(),"\n","\t","mouse_over_handler assigned:        ",(typeof this.settings.mouse_over_handler==="function").toString(),"\n","\t","mouse_out_handler assigned:         ",(typeof this.settings.mouse_out_handler===
"function").toString(),"\n","\t","file_dialog_start_handler assigned: ",(typeof this.settings.file_dialog_start_handler==="function").toString(),"\n","\t","file_queued_handler assigned:       ",(typeof this.settings.file_queued_handler==="function").toString(),"\n","\t","file_queue_error_handler assigned:  ",(typeof this.settings.file_queue_error_handler==="function").toString(),"\n","\t","upload_resize_start_handler assigned:      ",(typeof this.settings.upload_resize_start_handler==="function").toString(),
"\n","\t","upload_start_handler assigned:      ",(typeof this.settings.upload_start_handler==="function").toString(),"\n","\t","upload_progress_handler assigned:   ",(typeof this.settings.upload_progress_handler==="function").toString(),"\n","\t","upload_error_handler assigned:      ",(typeof this.settings.upload_error_handler==="function").toString(),"\n","\t","upload_success_handler assigned:    ",(typeof this.settings.upload_success_handler==="function").toString(),"\n","\t","upload_complete_handler assigned:   ",
(typeof this.settings.upload_complete_handler==="function").toString(),"\n","\t","debug_handler assigned:             ",(typeof this.settings.debug_handler==="function").toString(),"\n","Support:\n","\t","Load:                     ",this.support.loading?"Yes":"No","\n","\t","Image Resize:             ",this.support.imageResize?"Yes":"No","\n"].join(""))};
SWFUpload.prototype.addSetting=function(name,value,default_value){if(value==undefined)return this.settings[name]=default_value;else return this.settings[name]=value};SWFUpload.prototype.getSetting=function(name){if(this.settings[name]!=undefined)return this.settings[name];return""};
SWFUpload.prototype.callFlash=function(functionName,argumentArray){var movieElement,returnValue,returnString;argumentArray=argumentArray||[];movieElement=this.getMovieElement();try{if(movieElement!=undefined){returnString=movieElement.CallFunction('<invoke name="'+functionName+'" returntype="javascript">'+__flash__argumentsToXML(argumentArray,0)+"</invoke>");returnValue=eval(returnString)}else this.debug("Can't call flash because the movie wasn't found.")}catch(ex){this.debug("Exception calling flash function '"+
functionName+"': "+ex.message)}if(returnValue!=undefined&&typeof returnValue.post==="object")returnValue=this.unescapeFilePostParams(returnValue);return returnValue};SWFUpload.prototype.selectFile=function(){this.callFlash("SelectFile")};SWFUpload.prototype.selectFiles=function(){this.callFlash("SelectFiles")};SWFUpload.prototype.startUpload=function(fileID){this.callFlash("StartUpload",[fileID])};
SWFUpload.prototype.startResizedUpload=function(fileID,width,height,encoding,quality,allowEnlarging){this.callFlash("StartUpload",[fileID,{"width":width,"height":height,"encoding":encoding,"quality":quality,"allowEnlarging":allowEnlarging}])};SWFUpload.prototype.cancelUpload=function(fileID,triggerErrorEvent){if(triggerErrorEvent!==false)triggerErrorEvent=true;this.callFlash("CancelUpload",[fileID,triggerErrorEvent])};SWFUpload.prototype.stopUpload=function(){this.callFlash("StopUpload")};
SWFUpload.prototype.requeueUpload=function(indexOrFileID){return this.callFlash("RequeueUpload",[indexOrFileID])};SWFUpload.prototype.getStats=function(){return this.callFlash("GetStats")};SWFUpload.prototype.setStats=function(statsObject){this.callFlash("SetStats",[statsObject])};SWFUpload.prototype.getFile=function(fileID){if(typeof fileID==="number")return this.callFlash("GetFileByIndex",[fileID]);else return this.callFlash("GetFile",[fileID])};
SWFUpload.prototype.getQueueFile=function(fileID){if(typeof fileID==="number")return this.callFlash("GetFileByQueueIndex",[fileID]);else return this.callFlash("GetFile",[fileID])};SWFUpload.prototype.addFileParam=function(fileID,name,value){return this.callFlash("AddFileParam",[fileID,name,value])};SWFUpload.prototype.removeFileParam=function(fileID,name){this.callFlash("RemoveFileParam",[fileID,name])};
SWFUpload.prototype.setUploadURL=function(url){this.settings.upload_url=url.toString();this.callFlash("SetUploadURL",[url])};SWFUpload.prototype.setPostParams=function(paramsObject){this.settings.post_params=paramsObject;this.callFlash("SetPostParams",[paramsObject])};SWFUpload.prototype.addPostParam=function(name,value){this.settings.post_params[name]=value;this.callFlash("SetPostParams",[this.settings.post_params])};
SWFUpload.prototype.removePostParam=function(name){delete this.settings.post_params[name];this.callFlash("SetPostParams",[this.settings.post_params])};SWFUpload.prototype.setFileTypes=function(types,description){this.settings.file_types=types;this.settings.file_types_description=description;this.callFlash("SetFileTypes",[types,description])};SWFUpload.prototype.setFileSizeLimit=function(fileSizeLimit){this.settings.file_size_limit=fileSizeLimit;this.callFlash("SetFileSizeLimit",[fileSizeLimit])};
SWFUpload.prototype.setFileUploadLimit=function(fileUploadLimit){this.settings.file_upload_limit=fileUploadLimit;this.callFlash("SetFileUploadLimit",[fileUploadLimit])};SWFUpload.prototype.setFileQueueLimit=function(fileQueueLimit){this.settings.file_queue_limit=fileQueueLimit;this.callFlash("SetFileQueueLimit",[fileQueueLimit])};SWFUpload.prototype.setFilePostName=function(filePostName){this.settings.file_post_name=filePostName;this.callFlash("SetFilePostName",[filePostName])};
SWFUpload.prototype.setUseQueryString=function(useQueryString){this.settings.use_query_string=useQueryString;this.callFlash("SetUseQueryString",[useQueryString])};SWFUpload.prototype.setRequeueOnError=function(requeueOnError){this.settings.requeue_on_error=requeueOnError;this.callFlash("SetRequeueOnError",[requeueOnError])};
SWFUpload.prototype.setHTTPSuccess=function(http_status_codes){if(typeof http_status_codes==="string")http_status_codes=http_status_codes.replace(" ","").split(",");this.settings.http_success=http_status_codes;this.callFlash("SetHTTPSuccess",[http_status_codes])};SWFUpload.prototype.setAssumeSuccessTimeout=function(timeout_seconds){this.settings.assume_success_timeout=timeout_seconds;this.callFlash("SetAssumeSuccessTimeout",[timeout_seconds])};
SWFUpload.prototype.setDebugEnabled=function(debugEnabled){this.settings.debug_enabled=debugEnabled;this.callFlash("SetDebugEnabled",[debugEnabled])};SWFUpload.prototype.setButtonImageURL=function(buttonImageURL){if(buttonImageURL==undefined)buttonImageURL="";this.settings.button_image_url=buttonImageURL;this.callFlash("SetButtonImageURL",[buttonImageURL])};
SWFUpload.prototype.setButtonDimensions=function(width,height){this.settings.button_width=width;this.settings.button_height=height;var movie=this.getMovieElement();if(movie!=undefined){movie.style.width=width+"px";movie.style.height=height+"px"}this.callFlash("SetButtonDimensions",[width,height])};SWFUpload.prototype.setButtonText=function(html){this.settings.button_text=html;this.callFlash("SetButtonText",[html])};
SWFUpload.prototype.setButtonTextPadding=function(left,top){this.settings.button_text_top_padding=top;this.settings.button_text_left_padding=left;this.callFlash("SetButtonTextPadding",[left,top])};SWFUpload.prototype.setButtonTextStyle=function(css){this.settings.button_text_style=css;this.callFlash("SetButtonTextStyle",[css])};SWFUpload.prototype.setButtonDisabled=function(isDisabled){this.settings.button_disabled=isDisabled;this.callFlash("SetButtonDisabled",[isDisabled])};
SWFUpload.prototype.setButtonAction=function(buttonAction){this.settings.button_action=buttonAction;this.callFlash("SetButtonAction",[buttonAction])};SWFUpload.prototype.setButtonCursor=function(cursor){this.settings.button_cursor=cursor;this.callFlash("SetButtonCursor",[cursor])};
SWFUpload.prototype.queueEvent=function(handlerName,argumentArray){var self=this;if(argumentArray==undefined)argumentArray=[];else if(!(argumentArray instanceof Array))argumentArray=[argumentArray];if(typeof this.settings[handlerName]==="function"){this.eventQueue.push(function(){this.settings[handlerName].apply(this,argumentArray)});setTimeout(function(){self.executeNextEvent()},0)}else if(this.settings[handlerName]!==null)throw"Event handler "+handlerName+" is unknown or is not a function";};
SWFUpload.prototype.executeNextEvent=function(){var f=this.eventQueue?this.eventQueue.shift():null;if(typeof f==="function")f.apply(this)};SWFUpload.prototype.unescapeFilePostParams=function(file){var reg=/[$]([0-9a-f]{4})/i,unescapedPost={},uk,k,match;if(file!=undefined){for(k in file.post)if(file.post.hasOwnProperty(k)){uk=k;while((match=reg.exec(uk))!==null)uk=uk.replace(match[0],String.fromCharCode(parseInt("0x"+match[1],16)));unescapedPost[uk]=file.post[k]}file.post=unescapedPost}return file};
SWFUpload.prototype.swfuploadPreload=function(){var returnValue;if(typeof this.settings.swfupload_preload_handler==="function")returnValue=this.settings.swfupload_preload_handler.call(this);else if(this.settings.swfupload_preload_handler!=undefined)throw"upload_start_handler must be a function";if(returnValue===undefined)returnValue=true;return!!returnValue};
SWFUpload.prototype.flashReady=function(){var movieElement=this.cleanUp();if(!movieElement){this.debug("Flash called back ready but the flash movie can't be found.");return}this.queueEvent("swfupload_loaded_handler")};
SWFUpload.prototype.cleanUp=function(){var key,movieElement=this.getMovieElement();try{if(movieElement&&typeof movieElement.CallFunction==="unknown"){this.debug("Removing Flash functions hooks (this should only run in IE and should prevent memory leaks)");for(key in movieElement)try{if(typeof movieElement[key]==="function")movieElement[key]=null}catch(ex){}}}catch(ex1){}window["__flash__removeCallback"]=function(instance,name){try{if(instance)instance[name]=null}catch(flashEx){}};return movieElement};
SWFUpload.prototype.mouseClick=function(){this.queueEvent("mouse_click_handler")};SWFUpload.prototype.mouseOver=function(){this.queueEvent("mouse_over_handler")};SWFUpload.prototype.mouseOut=function(){this.queueEvent("mouse_out_handler")};SWFUpload.prototype.fileDialogStart=function(){this.queueEvent("file_dialog_start_handler")};SWFUpload.prototype.fileQueued=function(file){file=this.unescapeFilePostParams(file);this.queueEvent("file_queued_handler",file)};
SWFUpload.prototype.fileQueueError=function(file,errorCode,message){file=this.unescapeFilePostParams(file);this.queueEvent("file_queue_error_handler",[file,errorCode,message])};SWFUpload.prototype.fileDialogComplete=function(numFilesSelected,numFilesQueued,numFilesInQueue){this.queueEvent("file_dialog_complete_handler",[numFilesSelected,numFilesQueued,numFilesInQueue])};
SWFUpload.prototype.uploadResizeStart=function(file,resizeSettings){file=this.unescapeFilePostParams(file);this.queueEvent("upload_resize_start_handler",[file,resizeSettings.width,resizeSettings.height,resizeSettings.encoding,resizeSettings.quality])};SWFUpload.prototype.uploadStart=function(file){file=this.unescapeFilePostParams(file);this.queueEvent("return_upload_start_handler",file)};
SWFUpload.prototype.returnUploadStart=function(file){var returnValue;if(typeof this.settings.upload_start_handler==="function"){file=this.unescapeFilePostParams(file);returnValue=this.settings.upload_start_handler.call(this,file)}else if(this.settings.upload_start_handler!=undefined)throw"upload_start_handler must be a function";if(returnValue===undefined)returnValue=true;returnValue=!!returnValue;this.callFlash("ReturnUploadStart",[returnValue])};
SWFUpload.prototype.uploadProgress=function(file,bytesComplete,bytesTotal){file=this.unescapeFilePostParams(file);this.queueEvent("upload_progress_handler",[file,bytesComplete,bytesTotal])};SWFUpload.prototype.uploadError=function(file,errorCode,message){file=this.unescapeFilePostParams(file);this.queueEvent("upload_error_handler",[file,errorCode,message])};
SWFUpload.prototype.uploadSuccess=function(file,serverData,responseReceived){file=this.unescapeFilePostParams(file);this.queueEvent("upload_success_handler",[file,serverData,responseReceived])};SWFUpload.prototype.uploadComplete=function(file){file=this.unescapeFilePostParams(file);this.queueEvent("upload_complete_handler",file)};SWFUpload.prototype.debug=function(message){this.queueEvent("debug_handler",message)};
SWFUpload.prototype.debugMessage=function(message){var exceptionMessage,exceptionValues,key;if(this.settings.debug){exceptionValues=[];if(typeof message==="object"&&typeof message.name==="string"&&typeof message.message==="string"){for(key in message)if(message.hasOwnProperty(key))exceptionValues.push(key+": "+message[key]);exceptionMessage=exceptionValues.join("\n")||"";exceptionValues=exceptionMessage.split("\n");exceptionMessage="EXCEPTION: "+exceptionValues.join("\nEXCEPTION: ");SWFUpload.Console.writeLine(exceptionMessage)}else SWFUpload.Console.writeLine(message)}};
SWFUpload.Console={};
SWFUpload.Console.writeLine=function(message){var console,documentForm;try{console=document.getElementById("SWFUpload_Console");if(!console){documentForm=document.createElement("form");document.getElementsByTagName("body")[0].appendChild(documentForm);console=document.createElement("textarea");console.id="SWFUpload_Console";console.style.fontFamily="monospace";console.setAttribute("wrap","off");console.wrap="off";console.style.overflow="auto";console.style.width="700px";console.style.height="350px";
console.style.margin="5px";documentForm.appendChild(console)}console.value+=message+"\n";console.scrollTop=console.scrollHeight-console.clientHeight}catch(ex){alert("Exception: "+ex.name+" Message: "+ex.message)}};
swfobject=function(){var D="undefined",r="object",S="Shockwave Flash",W="ShockwaveFlash.ShockwaveFlash",q="application/x-shockwave-flash",R="SWFObjectExprInst",x="onreadystatechange",O=window,j=document,t=navigator,T=false,U=[h],o=[],N=[],I=[],l,Q,E,B,J=false,a=false,n,G,m=true,M=function(){var aa=typeof j.getElementById!=D&&typeof j.getElementsByTagName!=D&&typeof j.createElement!=D,ah=t.userAgent.toLowerCase(),Y=t.platform.toLowerCase(),ae=Y?/win/.test(Y):/win/.test(ah),ac=Y?/mac/.test(Y):/mac/.test(ah),
af=/webkit/.test(ah)?parseFloat(ah.replace(/^.*webkit\/(\d+(\.\d+)?).*$/,"$1")):false,X=!+"\u000b1",ag=[0,0,0],ab=null;if(typeof t.plugins!=D&&typeof t.plugins[S]==r){ab=t.plugins[S].description;if(ab&&!(typeof t.mimeTypes!=D&&t.mimeTypes[q]&&!t.mimeTypes[q].enabledPlugin)){T=true;X=false;ab=ab.replace(/^.*\s+(\S+\s+\S+$)/,"$1");ag[0]=parseInt(ab.replace(/^(.*)\..*$/,"$1"),10);ag[1]=parseInt(ab.replace(/^.*\.(.*)\s.*$/,"$1"),10);ag[2]=/[a-zA-Z]/.test(ab)?parseInt(ab.replace(/^.*[a-zA-Z]+(.*)$/,"$1"),
10):0}}else if(typeof O.ActiveXObject!=D)try{var ad=new ActiveXObject(W);if(ad){ab=ad.GetVariable("$version");if(ab){X=true;ab=ab.split(" ")[1].split(",");ag=[parseInt(ab[0],10),parseInt(ab[1],10),parseInt(ab[2],10)]}}}catch(Z){}return{w3:aa,pv:ag,wk:af,ie:X,win:ae,mac:ac}}(),k=function(){if(!M.w3)return;if(typeof j.readyState!=D&&j.readyState=="complete"||typeof j.readyState==D&&(j.getElementsByTagName("body")[0]||j.body))f();if(!J){if(typeof j.addEventListener!=D)j.addEventListener("DOMContentLoaded",
f,false);if(M.ie&&M.win){j.attachEvent(x,function(){if(j.readyState=="complete"){j.detachEvent(x,arguments.callee);f()}});if(O==top)(function(){if(J)return;try{j.documentElement.doScroll("left")}catch(X){setTimeout(arguments.callee,0);return}f()})()}if(M.wk)(function(){if(J)return;if(!/loaded|complete/.test(j.readyState)){setTimeout(arguments.callee,0);return}f()})();s(f)}}();function f(){if(J)return;try{var Z=j.getElementsByTagName("body")[0].appendChild(C("span"));Z.parentNode.removeChild(Z)}catch(aa){return}J=
true;var X=U.length;for(var Y=0;Y<X;Y++)U[Y]()}function K(X){if(J)X();else U[U.length]=X}function s(Y){if(typeof O.addEventListener!=D)O.addEventListener("load",Y,false);else if(typeof j.addEventListener!=D)j.addEventListener("load",Y,false);else if(typeof O.attachEvent!=D)i(O,"onload",Y);else if(typeof O.onload=="function"){var X=O.onload;O.onload=function(){X();Y()}}else O.onload=Y}function h(){if(T)V();else H()}function V(){var X=j.getElementsByTagName("body")[0];var aa=C(r);aa.setAttribute("type",
q);var Z=X.appendChild(aa);if(Z){var Y=0;(function(){if(typeof Z.GetVariable!=D){var ab=Z.GetVariable("$version");if(ab){ab=ab.split(" ")[1].split(",");M.pv=[parseInt(ab[0],10),parseInt(ab[1],10),parseInt(ab[2],10)]}}else if(Y<10){Y++;setTimeout(arguments.callee,10);return}X.removeChild(aa);Z=null;H()})()}else H()}function H(){var ag=o.length;if(ag>0)for(var af=0;af<ag;af++){var Y=o[af].id;var ab=o[af].callbackFn;var aa={success:false,id:Y};if(M.pv[0]>0){var ae=c(Y);if(ae)if(F(o[af].swfVersion)&&
!(M.wk&&M.wk<312)){w(Y,true);if(ab){aa.success=true;aa.ref=z(Y);ab(aa)}}else if(o[af].expressInstall&&A()){var ai={};ai.data=o[af].expressInstall;ai.width=ae.getAttribute("width")||"0";ai.height=ae.getAttribute("height")||"0";if(ae.getAttribute("class"))ai.styleclass=ae.getAttribute("class");if(ae.getAttribute("align"))ai.align=ae.getAttribute("align");var ah={};var X=ae.getElementsByTagName("param");var ac=X.length;for(var ad=0;ad<ac;ad++)if(X[ad].getAttribute("name").toLowerCase()!="movie")ah[X[ad].getAttribute("name")]=
X[ad].getAttribute("value");P(ai,ah,Y,ab)}else{p(ae);if(ab)ab(aa)}}else{w(Y,true);if(ab){var Z=z(Y);if(Z&&typeof Z.SetVariable!=D){aa.success=true;aa.ref=Z}ab(aa)}}}}function z(aa){var X=null;var Y=c(aa);if(Y&&Y.nodeName=="OBJECT")if(typeof Y.SetVariable!=D)X=Y;else{var Z=Y.getElementsByTagName(r)[0];if(Z)X=Z}return X}function A(){return!a&&F("6.0.65")&&(M.win||M.mac)&&!(M.wk&&M.wk<312)}function P(aa,ab,X,Z){a=true;E=Z||null;B={success:false,id:X};var ae=c(X);if(ae){if(ae.nodeName=="OBJECT"){l=g(ae);
Q=null}else{l=ae;Q=X}aa.id=R;if(typeof aa.width==D||!/%$/.test(aa.width)&&parseInt(aa.width,10)<310)aa.width="310";if(typeof aa.height==D||!/%$/.test(aa.height)&&parseInt(aa.height,10)<137)aa.height="137";j.title=j.title.slice(0,47)+" - Flash Player Installation";var ad=M.ie&&M.win?"ActiveX":"PlugIn",ac="MMredirectURL="+O.location.toString().replace(/&/g,"%26")+"&MMplayerType="+ad+"&MMdoctitle="+j.title;if(typeof ab.flashvars!=D)ab.flashvars+="&"+ac;else ab.flashvars=ac;if(M.ie&&M.win&&ae.readyState!=
4){var Y=C("div");X+="SWFObjectNew";Y.setAttribute("id",X);ae.parentNode.insertBefore(Y,ae);ae.style.display="none";(function(){if(ae.readyState==4)ae.parentNode.removeChild(ae);else setTimeout(arguments.callee,10)})()}u(aa,ab,X)}}function p(Y){if(M.ie&&M.win&&Y.readyState!=4){var X=C("div");Y.parentNode.insertBefore(X,Y);X.parentNode.replaceChild(g(Y),X);Y.style.display="none";(function(){if(Y.readyState==4)Y.parentNode.removeChild(Y);else setTimeout(arguments.callee,10)})()}else Y.parentNode.replaceChild(g(Y),
Y)}function g(ab){var aa=C("div");if(M.win&&M.ie)aa.innerHTML=ab.innerHTML;else{var Y=ab.getElementsByTagName(r)[0];if(Y){var ad=Y.childNodes;if(ad){var X=ad.length;for(var Z=0;Z<X;Z++)if(!(ad[Z].nodeType==1&&ad[Z].nodeName=="PARAM")&&!(ad[Z].nodeType==8))aa.appendChild(ad[Z].cloneNode(true))}}}return aa}function u(ai,ag,Y){var X,aa=c(Y);if(M.wk&&M.wk<312)return X;if(aa){if(typeof ai.id==D)ai.id=Y;if(M.ie&&M.win){var ah="";for(var ae in ai)if(ai[ae]!=Object.prototype[ae])if(ae.toLowerCase()=="data")ag.movie=
ai[ae];else if(ae.toLowerCase()=="styleclass")ah+=' class="'+ai[ae]+'"';else if(ae.toLowerCase()!="classid")ah+=" "+ae+'="'+ai[ae]+'"';var af="";for(var ad in ag)if(ag[ad]!=Object.prototype[ad])af+='<param name="'+ad+'" value="'+ag[ad]+'" />';aa.outerHTML='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'+ah+">"+af+"</object>";N[N.length]=ai.id;X=c(ai.id)}else{var Z=C(r);Z.setAttribute("type",q);for(var ac in ai)if(ai[ac]!=Object.prototype[ac])if(ac.toLowerCase()=="styleclass")Z.setAttribute("class",
ai[ac]);else if(ac.toLowerCase()!="classid")Z.setAttribute(ac,ai[ac]);for(var ab in ag)if(ag[ab]!=Object.prototype[ab]&&ab.toLowerCase()!="movie")e(Z,ab,ag[ab]);aa.parentNode.replaceChild(Z,aa);X=Z}}return X}function e(Z,X,Y){var aa=C("param");aa.setAttribute("name",X);aa.setAttribute("value",Y);Z.appendChild(aa)}function y(Y){var X=c(Y);if(X&&X.nodeName=="OBJECT")if(M.ie&&M.win){X.style.display="none";(function(){if(X.readyState==4)b(Y);else setTimeout(arguments.callee,10)})()}else X.parentNode.removeChild(X)}
function b(Z){var Y=c(Z);if(Y){for(var X in Y)if(typeof Y[X]=="function")Y[X]=null;Y.parentNode.removeChild(Y)}}function c(Z){var X=null;try{X=j.getElementById(Z)}catch(Y){}return X}function C(X){return j.createElement(X)}function i(Z,X,Y){Z.attachEvent(X,Y);I[I.length]=[Z,X,Y]}function F(Z){var Y=M.pv,X=Z.split(".");X[0]=parseInt(X[0],10);X[1]=parseInt(X[1],10)||0;X[2]=parseInt(X[2],10)||0;return Y[0]>X[0]||Y[0]==X[0]&&Y[1]>X[1]||Y[0]==X[0]&&Y[1]==X[1]&&Y[2]>=X[2]?true:false}function v(ac,Y,ad,ab){if(M.ie&&
M.mac)return;var aa=j.getElementsByTagName("head")[0];if(!aa)return;var X=ad&&typeof ad=="string"?ad:"screen";if(ab){n=null;G=null}if(!n||G!=X){var Z=C("style");Z.setAttribute("type","text/css");Z.setAttribute("media",X);n=aa.appendChild(Z);if(M.ie&&M.win&&typeof j.styleSheets!=D&&j.styleSheets.length>0)n=j.styleSheets[j.styleSheets.length-1];G=X}if(M.ie&&M.win){if(n&&typeof n.addRule==r)n.addRule(ac,Y)}else if(n&&typeof j.createTextNode!=D)n.appendChild(j.createTextNode(ac+" {"+Y+"}"))}function w(Z,
X){if(!m)return;var Y=X?"visible":"hidden";if(J&&c(Z))c(Z).style.visibility=Y;else v("#"+Z,"visibility:"+Y)}function L(Y){var Z=/[\\\"<>\.;]/;var X=Z.exec(Y)!=null;return X&&typeof encodeURIComponent!=D?encodeURIComponent(Y):Y}var d=function(){if(M.ie&&M.win)window.attachEvent("onunload",function(){var ac=I.length;for(var ab=0;ab<ac;ab++)I[ab][0].detachEvent(I[ab][1],I[ab][2]);var Z=N.length;for(var aa=0;aa<Z;aa++)y(N[aa]);for(var Y in M)M[Y]=null;M=null;for(var X in swfobject)swfobject[X]=null;swfobject=
null})}();return{registerObject:function(ab,X,aa,Z){if(M.w3&&ab&&X){var Y={};Y.id=ab;Y.swfVersion=X;Y.expressInstall=aa;Y.callbackFn=Z;o[o.length]=Y;w(ab,false)}else if(Z)Z({success:false,id:ab})},getObjectById:function(X){if(M.w3)return z(X)},embedSWF:function(ab,ah,ae,ag,Y,aa,Z,ad,af,ac){var X={success:false,id:ah};if(M.w3&&!(M.wk&&M.wk<312)&&ab&&ah&&ae&&ag&&Y){w(ah,false);K(function(){ae+="";ag+="";var aj={};if(af&&typeof af===r)for(var al in af)aj[al]=af[al];aj.data=ab;aj.width=ae;aj.height=ag;
var am={};if(ad&&typeof ad===r)for(var ak in ad)am[ak]=ad[ak];if(Z&&typeof Z===r)for(var ai in Z)if(typeof am.flashvars!=D)am.flashvars+="&"+ai+"="+Z[ai];else am.flashvars=ai+"="+Z[ai];if(F(Y)){var an=u(aj,am,ah);if(aj.id==ah)w(ah,true);X.success=true;X.ref=an}else if(aa&&A()){aj.data=aa;P(aj,am,ah,ac);return}else w(ah,true);if(ac)ac(X)})}else if(ac)ac(X)},switchOffAutoHideShow:function(){m=false},ua:M,getFlashPlayerVersion:function(){return{major:M.pv[0],minor:M.pv[1],release:M.pv[2]}},hasFlashPlayerVersion:F,
createSWF:function(Z,Y,X){if(M.w3)return u(Z,Y,X);else return undefined},showExpressInstall:function(Z,aa,X,Y){if(M.w3&&A())P(Z,aa,X,Y)},removeSWF:function(X){if(M.w3)y(X)},createCSS:function(aa,Z,Y,X){if(M.w3)v(aa,Z,Y,X)},addDomLoadEvent:K,addLoadEvent:s,getQueryParamValue:function(aa){var Z=j.location.search||j.location.hash;if(Z){if(/\?/.test(Z))Z=Z.split("?")[1];if(aa==null)return L(Z);var Y=Z.split("&");for(var X=0;X<Y.length;X++)if(Y[X].substring(0,Y[X].indexOf("="))==aa)return L(Y[X].substring(Y[X].indexOf("=")+
1))}return""},expressInstallCallback:function(){if(a){var X=c(R);if(X&&l){X.parentNode.replaceChild(l,X);if(Q){w(Q,true);if(M.ie&&M.win)l.style.display="block"}if(E)E(B)}a=false}}}}();swfobject.addDomLoadEvent(function(){if(typeof SWFUpload.onload==="function")SWFUpload.onload.call(window)});if(typeof Prototype=="undefined")throw"Control.ProgressBar requires Prototype to be loaded.";if(typeof Object.Event=="undefined")throw"Control.ProgressBar requires Object.Event to be loaded.";
Control.ProgressBar=Class.create({initialize:function(container,options){this.progress=0;this.executer=false;this.active=false;this.poller=false;this.container=$(container);this.containerWidth=this.container.getDimensions().width-(parseInt(this.container.getStyle("border-right-width").replace(/px/,""),10)+parseInt(this.container.getStyle("border-left-width").replace(/px/,""),10));this.progressContainer=$(document.createElement("div"));this.progressContainer.setStyle({width:this.containerWidth+"px",
height:"100%",position:"absolute",top:"0px",right:"0px"});this.container.appendChild(this.progressContainer);this.options={afterChange:Prototype.emptyFunction,interval:0.25,step:1,classNames:{active:"progress_bar_active",inactive:"progress_bar_inactive"}};Object.extend(this.options,options||{});this.container.addClassName(this.options.classNames.inactive);this.active=false},setProgress:function(value){this.progress=value;this.draw();if(this.progress>=100)this.stop(false);this.notify("afterChange",
this.progress,this.active)},poll:function(url,interval,ajaxOptions){ajaxOptions=ajaxOptions||{};var success=ajaxOptions.onSuccess||Prototype.emptyFunction;ajaxOptions.onSuccess=success.wrap(function(callOriginal,request){this.setProgress(parseInt(request.responseText,10));if(!this.active)this.poller.stop();callOriginal(request)}).bind(this);this.active=true;this.poller=new PeriodicalExecuter(function(){var a=new Ajax.Request(url,ajaxOptions)}.bind(this),interval||3)},start:function(){this.active=
true;this.container.removeClassName(this.options.classNames.inactive);this.container.addClassName(this.options.classNames.active);this.executer=new PeriodicalExecuter(this.step.bind(this,this.options.step),this.options.interval)},stop:function(reset){this.active=false;if(this.executer)this.executer.stop();this.container.removeClassName(this.options.classNames.active);this.container.addClassName(this.options.classNames.inactive);if(typeof reset==="undefined"||reset===true)this.reset()},step:function(amount){this.active=
true;this.setProgress(Math.min(100,this.progress+amount))},reset:function(){this.active=false;this.setProgress(0)},draw:function(){this.progressContainer.setStyle({width:this.containerWidth-Math.floor(parseInt(this.progress,10)/100*this.containerWidth)+"px"})},notify:function(event_name){if(this.options[event_name])return[this.options[event_name].apply(this.options[event_name],$A(arguments).slice(1))]}});Object.Event.extend(Control.ProgressBar);
BrainstormJs.Forms.Fields.FileUpload=Class.create(BrainstormJs.Forms.Fields.BaseField,{uploader:false,requiredFlashVersion:9,fileSizeLimit:"15 MB",fileTypes:"*.*",fileTypesDescription:"All Files",fileUploadLimit:0,fileQueueLimit:1,showProgress:true,progressBarDiv:false,progressBar:false,defaultText:'Click "Browse..." to select a file...',fieldContainer:false,flashContainer:false,input:false,browseButton:false,submitOnEnter:false,lazyInit:false,uploadFinishedCallback:function(){alert("No upload callback supplied.")},
initialize:function($super,options){options=options||{};options.cssClass="fileUpload";this.maxLength=options.maxLength||this.maxLength;this.validateUrl=options.validateUrl||this.validateUrl;this.submitOnEnter=options.submitOnEnter||this.submitOnEnter;this.fileSizeLimit=options.fileSizeLimit||this.fileSizeLimit;this.fileTypes=options.fileTypes||this.fileTypes;this.fileTypesDescription=options.fileTypesDescription||this.fileTypesDescription;this.lazyInit=options.lazyInit||this.lazyInit;$super(options)},
render:function($super){this.fieldContainer=new Element("div",{"class":"fileWrapper"});this.flashContainer=new Element("div",{"class":"clearfix flashContainer"});this.input=new Element("input",{"type":"text","class":"file","tabindex":this.tabIndex,"disabled":"disabled","placeholder":this.defaultText});this.input.identify();this.browseButton=new Element("a",{"href":"#","class":"btnBrowse"});this.browseButton.identify();if(!FlashDetect.majorAtLeast(this.requiredFlashVersion))this.warning='<a href="http://get.adobe.com/flashplayer" target="_blank">Flash '+
this.requiredFlashVersion+"</a> or above is required";if(this.required)this.input.addClassName("required");this.flashContainer.insert(this.input);this.flashContainer.insert(this.browseButton);this.fieldContainer.insert(this.flashContainer);this.input.disabled=true;if(this.showProgress){this.progressBarDiv=new Element("div",{"class":"progressBar"});this.progressBarDiv.hide();this.fieldContainer.insert(this.progressBarDiv)}return $super([this.fieldContainer])},afterRender:function(){if(!this.lazyInit)this.initializeUploader()},
initializeUploader:function(){var settings=bsCommon.fileUploadSettings();settings.file_types=this.fileTypes;settings.file_types_description=this.fileTypesDescription;settings.file_size_limit=this.fileSizeLimit;settings.file_upload_limit=this.fileUploadLimit;settings.file_queue_limit=this.fileQueueLimit;settings.button_placeholder_id=this.browseButton.id;settings.button_width=71;settings.button_width=22;settings.file_dialog_start_handler=bsCommon.onDialogStart.bind(this);settings.file_queued_handler=
bsCommon.onFileQueued.bind(this);settings.file_queue_error_handler=bsCommon.onFileQueueError.bind(this);settings.file_dialog_complete_handler=bsCommon.onDialogComplete.bind(this);settings.upload_progress_handler=bsCommon.onUpdateProgress.bind(this);settings.upload_success_handler=bsCommon.onUploadSuccess.bind(this);settings.upload_error_handler=bsCommon.onUploadError.bind(this);this.uploader=new SWFUpload(settings)},hasValue:function(){return this.getValue()!=""},getValue:function(){return this.input.value.strip()},
setValue:function(value){this.input.value=value},clear:function(){this.setValue("");if(this.uploader&&!Prototype.Browser.IE6)this.uploader.cancelUpload();else window.setTimeout(function(){if(this.uploader)this.uploader.cancelUpload()}.bind(this),1);if(this.showProgress){this.progressBarDiv.hide();if(this.progressBar)this.progressBar.reset()}},focus:function(){},disableUpload:function(){},enable:function($super){},disable:function($super){},destroy:function(){this.uploader.destroy()},startUpload:function(callback){this.uploadFinishedCallback=
callback;if(this.showProgress){if(!this.progressBar)this.progressBar=new Control.ProgressBar(this.progressBarDiv,{});Effect.BlindDown(this.progressBarDiv,{duration:0.5})}window.setTimeout(function(){this.uploader.startUpload()}.bind(this),1)}});
BrainstormJs.Forms.Parts.DocumentForm=Class.create(BrainstormJs.Forms.BaseListForm,{part:false,fieldFileName:false,fieldTitle:false,fieldTags:false,initialize:function($super,part,options){options=options||{};options.createTitle="Add a new document";options.editTitle="Edit document";options.emptyMessage="There are no documents here yet";options.hoverDelay=1;this.part=part;var profile=part.tab.partContainer.profile;$super(profile,options);this.toggleListEditing(true);this.editObjectType="Document";
this.friendlyObjectName="document"},createFields:function($super){this.fieldFileName=new BrainstormJs.Forms.Fields.FileUpload({title:"Choose File",required:true,hideOnEdit:true});this.fieldTitle=new BrainstormJs.Forms.Fields.TextBox({title:"Title / Description",required:true,maxLength:100,submitOnEnter:true});this.registerField(this.fieldFileName);this.registerField(this.fieldTitle)},createNewObject:function($super){$super();this.fieldFileName.startUpload(this.createDocument.bind(this))},createDocument:function(documentId,
mimeType,fileSize){Brainstorm.Web.Services.Parts.CreateDocument(this.part.partId,documentId,this.fieldFileName.getValue(),mimeType,fileSize,this.fieldTitle.getValue(),this.newObjectCreated.bind(this),this.handleAjaxError.bind(this))},loadObjectValues:function($super,objectLi){$super(objectLi);var data=objectLi.down(".data");this.fieldFileName.setValue(data.down(".filename").value);this.fieldTitle.setValue(data.down(".title").value)},saveEditedObject:function($super){$super();Brainstorm.Web.Services.Parts.UpdateDocument(this.editObjectId,
this.fieldTitle.getValue(),this.documentSaved.bind(this),bsCommon.ajaxCallError)},documentSaved:function(editedDocument){var docLink=this.editObjectElement.down("a.resourceLink");docLink.innerHTML=editedDocument.Title;var data=this.editObjectElement.down(".data");data.down(".title").value=editedDocument.Url;this.closeForm({highlight:docLink})},callDeleteObject:function($super,listItem,objectType,objectId){Brainstorm.Web.Services.Parts.DeleteDocument(objectId,this.objectDeleted.bind(this),bsCommon.ajaxCallError,
listItem)},reorderList:function($super,orderableList){Brainstorm.Web.Services.Parts.ReorderDocuments(this.part.partId,bsCommon.serializeSortable(orderableList),this.reorderComplete.bind(this),bsCommon.ajaxCallError)}});
BrainstormJs.Controls.Parts.DocumentPart=Class.create(BrainstormJs.Controls.Parts.BasePart,{docForm:false,initialize:function($super,container,tab){$super(container,tab);var editableList=this.container.down("div.editableList");var formContainer=this.container.down("div.documentForm-container");var addDocLink=this.container.down("a.addDocument");if(editableList&&formContainer&&addDocLink)this.docForm=new BrainstormJs.Forms.Parts.DocumentForm(this,{list:editableList,parentContainer:formContainer,openLinks:[addDocLink]})},
onEdit:function(linkClicked){}});
BrainstormJs.Forms.Parts.LinkForm=Class.create(BrainstormJs.Forms.BaseListForm,{part:false,fieldUrl:false,fieldTitle:false,initialize:function($super,part,options){options=options||{};options.createTitle="Create a new link";options.editTitle="Edit link";options.emptyMessage="There are no links here yet.";options.hoverDelay=1;this.part=part;var profile=part.tab.partContainer.profile;$super(profile,options);this.toggleListEditing(true);this.editObjectType="Link";this.friendlyObjectName="link"},createFields:function($super){this.fieldUrl=
new BrainstormJs.Forms.Fields.TextBox({title:"URL",required:true,maxLength:1024,validateUrl:false});this.fieldTitle=new BrainstormJs.Forms.Fields.TextBox({title:"Title",required:true,maxLength:100,submitOnEnter:true});this.registerField(this.fieldUrl);this.registerField(this.fieldTitle)},createNewObject:function($super){$super();Brainstorm.Web.Services.Parts.CreateLink(this.part.partId,this.fieldTitle.getValue(),this.fieldUrl.getValue(),this.newObjectCreated.bind(this),this.handleAjaxError.bind(this))},
loadObjectValues:function($super,objectLi){$super(objectLi);var data=objectLi.down(".data");this.fieldUrl.setValue(data.down(".url").value);this.fieldTitle.setValue(data.down(".title").value)},saveEditedObject:function($super){$super();Brainstorm.Web.Services.Parts.UpdateLink(this.editObjectId,this.fieldTitle.getValue(),this.fieldUrl.getValue(),this.linkSaved.bind(this),bsCommon.ajaxCallError)},linkSaved:function(editedLink){var link=this.editObjectElement.down("a.link");link.innerHTML=editedLink.Title;
link.href=editedLink.Url;var url=this.editObjectElement.down("span.url");url.innerHTML=editedLink.Url;var data=this.editObjectElement.down(".data");data.down(".url").value=editedLink.Url;data.down(".title").value=editedLink.Title;this.closeForm({highlight:this.editObjectElement})},callDeleteObject:function($super,listItem,objectType,objectId){Brainstorm.Web.Services.Parts.DeleteLink(objectId,this.objectDeleted.bind(this),bsCommon.ajaxCallError,listItem)},reorderList:function($super,orderableList){Brainstorm.Web.Services.Parts.ReorderLinks(this.part.partId,
bsCommon.serializeSortable(orderableList),this.reorderComplete.bind(this),bsCommon.ajaxCallError)}});
BrainstormJs.Controls.Parts.LinkPart=Class.create(BrainstormJs.Controls.Parts.BasePart,{linkForm:false,initialize:function($super,container,tab){$super(container,tab);var editableList=this.container.down("div.editableList");var formContainer=this.container.down("div.linkForm-container");var addLinkLink=this.container.down("a.addLink");if(editableList&&formContainer&&addLinkLink)this.linkForm=new BrainstormJs.Forms.Parts.LinkForm(this,{list:editableList,parentContainer:formContainer,openLinks:[addLinkLink]})},
onEdit:function(linkClicked){}});
BrainstormJs.Controls.Parts.NotePart=Class.create(BrainstormJs.Controls.Parts.BasePart,{initialize:function($super,container,tab){$super(container,tab)},onEdit:function($super,linkClicked){var formContainer=this.container.down("div.editNoteForm-container");var noteBody=this.container.down("div.noteBody");var editNoteForm=new BrainstormJs.Forms.Parts.NoteForm(this.tab.partContainer.profile,{parentContainer:formContainer,replaceElement:noteBody,destroyOnClose:true,openLinks:[linkClicked],bindOpenLinks:false,
editTitle:"Edit note"});editNoteForm.startEditing(this)}});
BrainstormJs.Controls.Parts.TodoListPart=Class.create(BrainstormJs.Controls.Parts.BasePart,{itemForm:false,initialize:function($super,container,tab){$super(container,tab);var editableList=this.container.down("div.todoItems");var itemFormContainer=this.container.down("div.todoItemForm-container");var addTodoItemLink=this.container.down("a.addTodoItem");if(editableList&&itemFormContainer&&addTodoItemLink){this.itemForm=new BrainstormJs.Forms.Parts.TodoItemForm(this,{list:editableList,parentContainer:itemFormContainer,
openLinks:[addTodoItemLink]});var fxItemChecked=this.itemChecked.bind(this);editableList.on(Prototype.Browser.IE?"click":"change","input.checkbox",fxItemChecked);var checkBoxes=editableList.select("input.checkbox");for(var i=0,j=checkBoxes.length;i<j;i++){var checkbox=checkBoxes[i];checkbox.checked=checkbox.hasClassName("checked")}}},itemChecked:function(e){var checkbox=e.element();var todoItemDiv=checkbox.up("div.editableItem");var textDiv=todoItemDiv.down("div.todoItem");var itemId=bsCommon.parseObjectGuid(todoItemDiv).id;
Brainstorm.Web.Services.Parts.UpdateTodoItemStatus(itemId,checkbox.checked,this.todoItemStatusSet.bind(this),bsCommon.ajaxCallError,textDiv)},todoItemStatusSet:function(completed,todoItemDiv){todoItemDiv[completed?"addClassName":"removeClassName"]("checked");new Effect.Highlight(todoItemDiv)},onEdit:function(linkClicked){}});
BrainstormJs.Controls.Parts.PartTab=Class.create({id:false,parts:false,partCount:0,partCountSpan:false,partContainer:false,link:false,listItem:false,name:false,nameSpan:false,pane:false,active:false,empty:false,editTooltop:false,dragHandle:false,moveMenuItem:false,editRights:false,activeClass:"activeTab",editDelay:1,hideDelay:0.15,lazyPane:false,loaded:false,initialize:function(tabLink,editRights,partContainer){tabLink.identify();this.partContainer=partContainer;this.listItem=tabLink.up("li.tab");
this.link=tabLink;this.id=parseInt(this.listItem.readAttribute("data-id"),10);this.partCount=parseInt(this.listItem.readAttribute("data-numparts"),10);this.empty=this.partCount==0;this.pane=$(this.listItem.readAttribute("data-paneid"));this.nameSpan=this.link.down("span.text");this.name=this.nameSpan.innerHTML;this.active=this.listItem.hasClassName(this.activeClass);this.editRights=editRights;var lazyPaneDiv=this.pane.down("> div.ajaxContentPane");if(lazyPaneDiv)this.lazyPane=new BrainstormJs.Controls.AjaxContentPane(lazyPaneDiv);
else{this.initializeParts();this.loaded=true}if(this.editRights){var editMenu=new Element("ul");var editListItem=new Element("li");var editLink=(new Element("a",{"href":"#","class":"edit"})).update("Edit tab title");editLink.observe("click",function(e){this.onEdit();e.stop()}.bind(this));editListItem.insert(editLink);editMenu.insert(editListItem);var deleteListItem=new Element("li");var deleteLink=(new Element("a",{"href":"#","class":"delete"})).update("Delete tab");deleteLink.observe("click",function(e){this.onDelete();
e.stop()}.bind(this));deleteListItem.insert(deleteLink);editMenu.insert(deleteListItem);this.editTooltip=new Tip(this.link,editMenu,{style:"darkgrey",className:"tabEditTip",hideOn:{element:"tip",event:"keypress"},hideAfter:this.hideDelay,delay:this.editDelay,stem:"bottomLeft",hook:{target:"topLeft",tip:"bottomLeft"},offset:{x:7,y:5},width:"auto"});this.dragHandle=this.link.down("span.handle")}},initializeParts:function(){this.parts=[];this.partCount=0;var partDivs=this.pane.select("div.part");for(var i=
0,j=partDivs.length;i<j;i++)this.registerPart(partDivs[i],false);BrainstormJs.Controls.Comments.CommentUtils.wireComments();this.refreshSortable()},registerPart:function(partDiv,refreshSortable){var part=false;if(partDiv.hasClassName("NotePart"))part=new BrainstormJs.Controls.Parts.NotePart(partDiv,this);else if(partDiv.hasClassName("TodoListPart"))part=new BrainstormJs.Controls.Parts.TodoListPart(partDiv,this);else if(partDiv.hasClassName("DocumentPart"))part=new BrainstormJs.Controls.Parts.DocumentPart(partDiv,
this);else if(partDiv.hasClassName("LinkPart"))part=new BrainstormJs.Controls.Parts.LinkPart(partDiv,this);this.addPart(part,refreshSortable)},addPart:function(part,refreshSortable,moving){if(!part){console.error("Could not find part to add!");return}if(this.loaded){this.parts.push(part);part.tab=this;var emptyPaneDiv=this.pane.down("div.emptyTabPane");if(emptyPaneDiv)emptyPaneDiv.remove()}this.partCount++;this.empty=false;this.updatePartCount();if(moving)if(this.loaded){this.pane.insert(part.container);
part.container.show()}else part.container.remove();if(this.loaded&&refreshSortable)this.refreshSortable()},registerNewPart:function(newDomElement,partForm){this.getPartListDiv().insert(newDomElement.HTML);var newPartDiv=$(newDomElement.Id);this.registerPart(newPartDiv,true);partForm.closeForm({afterFinish:function(){Effect.BlindDown(newPartDiv,{duration:0.5,afterFinish:function(){bsCommon.scrollIfBelowFold(newPartDiv,10)}})}});BrainstormJs.Controls.Comments.CommentUtils.wireComments()},removePart:function(part){this.parts=
this.parts.without(part);this.partCount--;this.empty=this.partCount==0;this.updatePartCount();if(this.empty)this.pane.innerHTML='<div class="emptyTabPane">There doesn\'t seem to be anything here.</div>'},show:function(activeClassName){this.listItem.addClassName(activeClassName);if(this.lazyPane&&!this.lazyPane.isLoaded()){this.pane.show();this.lazyPane.startLoading({dataMethod:this.loadParts.bind(this)})}else Effect.Appear(this.pane,{duration:0.5,from:0,to:1})},hide:function(activeClassName){this.listItem.removeClassName(activeClassName);
this.pane.hide()},loadParts:function(){Brainstorm.Web.Services.Ajax.GetPartTabContent(this.id,this.editRights,this.onPartsLoaded.bind(this),this.onLoadError.bind(this))},onLoadError:function(error){bsCommon.alert("Oops, there was an issue trying to load this tab. Please refresh the page and try again.");BrainstormJs.LogScriptError(error)},onPartsLoaded:function(jsonPartTab){this.lazyPane.insertContent(jsonPartTab.PaneContent,{onContentReady:this.onPartsReady.bind(this)});this.updatePartCount(jsonPartTab.PartCount)},
onPartsReady:function(){this.loaded=true;this.lazyPane.showContent({fadeTransition:true});this.initializeParts(false)},updatePartCount:function(newCount){if(newCount)this.partCount=newCount},getPartListDiv:function(){return this.lazyPane?this.lazyPane.getContentDiv():this.pane},refreshSortable:function(){if(!this.pane||!this.pane.hasClassName("sortable"))return;Sortable.create(this.getPartListDiv(),{dropOnEmpty:false,tag:"div",only:"part",handle:"partTitle",constraint:"vertical",scroll:window,onUpdate:function(sortableContainer){this.saveNewPartOrder(sortableContainer)}.bind(this)})},
saveNewPartOrder:function(sortableContainer){var serialized=bsCommon.serializeSortable(sortableContainer);Brainstorm.Web.Services.Parts.SavePartOrder(this.id,bsCommon.serializeSortable(sortableContainer),this.partOrderSaved.bind(this),bsCommon.ajaxCallError)},partOrderSaved:function(){bsCommon.showSuccess("New section order successfully saved.")},onMouseEnter:function(){var dragHandle=this.dragHandle;window.setTimeout(function(){dragHandle.show()},this.editDelay*1E3)},onMouseLeave:function(){var dragHandle=
this.dragHandle;window.setTimeout(function(){dragHandle.hide()},this.hideDelay*1E3)},onEdit:function(){bsCommon.prompt({title:"Edit tab name",text:"Enter the new tab name:",width:450,currentValue:this.name,maxLength:30,confirmText:"OK",cancelText:"Cancel",onConfirm:this.commitNameEdit.bind(this)})},commitNameEdit:function(newName){Brainstorm.Web.Services.Parts.RenameTab(this.id,newName,this.nameEdited.bind(this),bsCommon.ajaxCallError)},nameEdited:function(jsonTab){this.name=jsonTab.Name;this.nameSpan.innerHTML=
this.name;new Effect.Highlight(this.nameSpan,{delay:0.5});if(this.moveMenuItem)this.moveMenuItem.down("a").innerHTML=this.name},onDelete:function(){if(this.empty)bsCommon.confirm({title:"Tab Removal Confirmation",text:'Are you sure you would like to remove the tab "'+this.name+'"?',width:450,confirmText:"Yes, remove it!",cancelText:"No, keep it.",onConfirm:this.commitDelete.bind(this)});else bsCommon.alert('The tab "'+this.name+'" contains sections and cannot be removed until it is empty.')},commitDelete:function(){Brainstorm.Web.Services.Parts.DeleteTab(this.id,
this.afterDelete.bind(this),bsCommon.ajaxCallError)},afterDelete:function(){this.partContainer.removeTab(this)},getLink:function(link){if(link.tagName.toLowerCase()!="a")return link.up("a");return link},startArchivePart:function(part){bsCommon.confirm({title:"Removal Confirmation",text:"Are you sure you would like to remove this section?",width:450,confirmText:"Yes, remove it!",cancelText:"No, keep it.",onConfirm:function(){this.commitArchivePart(part)}.bind(this)})},commitArchivePart:function(part){Brainstorm.Web.Services.Parts.ArchivePart(part.partId,
this.afterArchivePart.bind(this),bsCommon.ajaxCallError,part)},afterArchivePart:function(retvalue,part){Effect.BlindUp(part.container,{duration:0.5,afterFinish:function(){part.container.remove();this.removePart(part)}.bind(this)})}});
BrainstormJs.Controls.Parts.PartContainer=Class.create({container:false,profileType:false,profileId:false,profile:false,tabMenu:false,tabPanes:false,tabs:false,activeTab:false,activeClass:"activeTab",editRights:false,tabsPopupMenu:false,addTabLink:false,tabSortable:false,addPartsBarDiv:false,addPartsBar:false,fxOnSwitchTabs:false,fxOnMovePartToTab:false,initialize:function(container){this.container=container;if(!this.container){console.error("Could not detect parts container.");return}this.profileType=
container.readAttribute("data-profile-type");this.profileId=parseInt(container.readAttribute("data-profile-id"),10);this.profile={type:this.profileType,id:this.profileId};this.tabMenu=$("partTabs");this.tabPanes=$("partTabPanes");this.tabs=[];this.addPartsBarDiv=this.container.down("div.addPartsBar")||false;this.editRights=this.addPartsBarDiv!=false;this.profile.partContainer=this;this.tabsPopupMenu=new BrainstormJs.Controls.PopupMenu($("moveToTabMenu"),{onSelectChoice:this.movePartToTab.bind(this)});
var tabLinks=this.tabMenu.select("a.tab");for(var i=0,j=tabLinks.length;i<j;i++)this.registerTab(tabLinks[i]);this.refreshTabSortable();this.addTabLink=$("addTabLink");if(this.addTabLink){this.tabEditor=new BrainstormJs.Controls.InLineEditor({editLink:this.addTabLink,container:this.addTabLink.previous("div.inlineEditor"),serviceMethod:Brainstorm.Web.Services.Parts.CreateTab,serviceParams:[bsCommon.getRequestToken(),this.profileType,this.profileId],afterSave:this.insertNewTab.bind(this)});this.addTabLink.appear()}if(this.addPartsBarDiv)this.addPartsBar=
new BrainstormJs.Controls.Parts.AddPartsBar(this.addPartsBarDiv,this)},registerTab:function(tabLink){if(tabLink.tagName.toLowerCase()=="li")tabLink=tabLink.down("a");var tab=new BrainstormJs.Controls.Parts.PartTab(tabLink,this.editRights,this);this.tabs.push(tab);tabLink.tab=tab;if(tab.active)this.activeTab=tab;this.tabsPopupMenu.addChoice(tab.id,tab.name,{tab:tab});if(!this.fxOnSwitchTabs)this.fxOnSwitchTabs=function(e){this.switchTabs(e.element());e.stop()}.bindAsEventListener(this);tabLink.observe("click",
this.fxOnSwitchTabs)},removeTab:function(tab){this.tabs=this.tabs.without(tab);tab.listItem.remove();tab.pane.remove();this.tabsPopupMenu.removeChoice(tab.id)},refreshTabSortable:function(){if(this.tabMenu.hasClassName("sortable"))Sortable.create(this.tabMenu,{dropOnEmpty:false,tag:"li",only:"tab",handle:"handle",constraint:"horizontal",onUpdate:function(sortableContainer){this.saveNewTabOrder(sortableContainer)}.bind(this)})},saveNewTabOrder:function(sortableContainer){Brainstorm.Web.Services.Parts.SaveTabOrder(this.profileType,
this.profileId,bsCommon.serializeSortable(sortableContainer),this.tabOrderSaved.bind(this),bsCommon.ajaxCallError)},tabOrderSaved:function(){bsCommon.showSuccess("New tab order successfully saved.")},insertNewTab:function(jsonTab){var addListItem=$("addTab");addListItem.insert({before:jsonTab.TabHtml});this.tabPanes.insert(jsonTab.PaneHtml);window.setTimeout(function(){var newTab=addListItem.previous();this.registerTab(newTab);this.refreshTabSortable()}.bind(this),10)},switchTabs:function(linkClicked){if(linkClicked.tagName.toLowerCase()!=
"a")linkClicked=linkClicked.up("a");var clickedTab=linkClicked.tab;if(Draggable._dragging[clickedTab.listItem])return;if(clickedTab.listItem.hasClassName(this.activeClass))return;if(this.activeTab)this.activeTab.hide(this.activeClass);clickedTab.show(this.activeClass);this.activeTab=clickedTab},showMoveTabMenu:function(linkClicked,part,selectedTabId){this.tabsPopupMenu.show(linkClicked,part,{hideChoiceWithId:selectedTabId,width:150,offset:{x:-127,y:5}})},movePartToTab:function(linkClicked,menuContext,
choiceContext){var part=menuContext;var moveToTab=choiceContext.tab;var context={part:part,moveFromTab:part.tab,moveToTab:moveToTab};Brainstorm.Web.Services.Parts.MovePartToTab(part.partId,moveToTab.id,this.afterPartMoved.bind(this),bsCommon.ajaxCallError,context)},afterPartMoved:function(result,context){var part=context.part;Effect.BlindUp(part.container,{duration:0.5,afterFinish:function(){context.moveFromTab.removePart(part);context.moveToTab.addPart(part,true,true)}});this.tabsPopupMenu.hide()}});
BrainstormJs.Forms.AccessKeyForm=Class.create(BrainstormJs.Forms.BaseListForm,{appName:false,active:false,initialize:function($super,profile,options){options=options||{};options.editTitle="Edit linked applications";options.deleteConfirmText="Are you sure you want to remove this linked application?";$super(profile,options);this.editObjectType="accesstoken";this.friendlyObjectName="token"},deleteObject:function($super,objectLi){bsCommon.confirm({title:"Removal Confirmation",text:"Are you sure you would like to remove this linked application? You will no longer be able to use "+
objectLi.down(".appname").innerHTML,width:500,confirmText:"Remove",cancelText:"Cancel",onConfirm:function(context){this.onDeleteConfirmed(objectLi,context)}.bind(this)})},callDeleteObject:function(objectLi,objectType,objectId,context){Brainstorm.Web.Services.Ajax.DeleteAccessToken(bsCommon.getRequestToken(),objectId,this.objectDeleted.bind(this),bsCommon.ajaxCallError,{objectLi:objectLi,deletedId:objectId})},objectDeleted:function($super,returnval,context){$super(returnval,context.objectLi)}});
BrainstormJs.Forms.AddToPipelineForm=Class.create(BrainstormJs.Forms.BaseForm,{fieldPipeline:false,ideaId:false,initialize:function($super,profile,options){options=options||{};this.ideaId=profile.id;options.createTitle=options.createTitle||"Add idea to your pipeline";options.parentContainer="joinPipelineForm-container";$super(null,options)},createFields:function($super){this.fieldPipeline=new BrainstormJs.Forms.Fields.DropDownList({title:"Select pipeline you want this idea to be added to.",required:true,
choices:choices_User_Idea_NonMemberPipelines,addBlank:true});this.registerField(this.fieldPipeline)},createNewObject:function($super){$super();Brainstorm.Web.Services.Ajax.ApprovePipelineIdea(this.fieldPipeline.getValue(),this.ideaId,this.onSuccess.bind(this),bsCommon.ajaxCallError)},onSuccess:function(jsonPipelineIdea){var pipelineCount=$("pipelineSnapshotCount");this.closeForm({dontFadeOpenLink:true,afterFinish:function(){bsCommon.incrementDomInt(pipelineCount,true)}})}});
BrainstormJs.Forms.AdminRequestForm=Class.create(BrainstormJs.Forms.BaseForm,{requestType:false,requestObjectName:false,initialize:function($super,options){options=options||{};this.requestType=options.requestType;var requestObjectName;if(this.requestType==Brainstorm.Model.Enums.AdminRequestType.ChallengeCreation)requestObjectName="challenge";else if(this.requestType==Brainstorm.Model.Enums.AdminRequestType.PipelineCreation)requestObjectName="pipeline";options.createTitle="Request the creation of a new "+
requestObjectName;options.introText="Only admins for your Brainstorm network can create new "+requestObjectName+"s. Enter a request below if you would like a network admin to create a specific "+requestObjectName+" on your behalf.";options.submitButtonTitle="Send";this.requestObjectName=requestObjectName;if(options.destroyOnClose)this.destroyOnClose=options.destroyOnClose;$super(null,options)},createFields:function($super){this.fieldMessage=new BrainstormJs.Forms.Fields.TextArea({title:"Request Message",
help:"Describe the "+this.requestObjectName+" you would like to have created and your reasoning behind it.",required:true});this.registerField(this.fieldMessage)},createNewObject:function($super){$super();Brainstorm.Web.Services.Ajax.SendNetworkAdminRequest(this.requestType,this.fieldMessage.getValue(),this.messageSent.bind(this),bsCommon.ajaxCallError)},messageSent:function(){this.closeForm({successMessage:"Request Sent!"})}});
BrainstormJs.Forms.BaseImageUploadForm=Class.create(BrainstormJs.Forms.BaseForm,{fieldLabel:false,fieldFileName:false,initialize:function($super,options){options=options||{};this.fieldLabel=options.fieldLabel;this.onImageUploaded=options.onImageUploaded;var profile=null;$super(profile,options)},createFields:function($super){this.fieldFileName=new BrainstormJs.Forms.Fields.FileUpload({title:this.fieldLabel,required:true,fileSizeLimit:"10 MB",fileTypes:"*.jpg;*.jpeg;*.png;*.gif;*.bmp",fileTypesDescription:"Image Files",
help:"<p>If the image is on your computer or a network location, press the Browse/Find button on the right side, and select the image to upload.</p><p>If the image is too wide, it will be automatically resized before being inserted. Clicking on the smaller image will show the original image in a popup window.</p>",lazyInit:true});this.registerField(this.fieldFileName)},createNewObject:function($super){$super();this.fieldFileName.startUpload(this.onImageUploaded)},beforeShow:function($super){$super();
this.fieldFileName.disable()},afterShow:function($super){$super();this.fieldFileName.initializeUploader()},afterClose:function($super){$super();if(this.destroyOnClose){this.container.remove();this.fieldFileName.destroy()}}});
BrainstormJs.Forms.BusinessUnitForm=Class.create(BrainstormJs.Forms.BaseForm,{fieldBU:false,trialMessage:false,currentUnitId:false,initialize:function($super,profile,options){options=options||{};options.createTitle="Edit "+$F("BS_Config_AreaName").toLowerCase();options.editTitle=options.createTitle;this.currentUnitId=$("currentBusinessUnitId");this.editObjectType="idea";this.friendlyObjectName="idea";$super(profile,options)},createFields:function($super){this.fieldBU=new BrainstormJs.Forms.Fields.DropDownList({title:"Which "+
$F("BS_Config_AreaName").toLowerCase()+" will this idea help?",required:true,choices:choices_Brainstorm_Model_Data_Ideas_IdeaBusinessUnit,selectedValue:this.currentUnitId.value});if($F("BS_TrialMode")!=false)this.trialMessage=new BrainstormJs.Forms.Fields.MessageBox({message:"<strong>To customize the choices for "+$F("BS_Config_AreaName")+',</strong><br /><a href="/Upgrade.aspx" target="_blank">upgrade now</a> or <a href="mailto:support@intuitbrainstorm.com">contact us</a>.',hasIcon:false,cssClass:"upgradeMessage"});
this.registerField(this.fieldBU);if(this.trialMessage!=false)this.registerField(this.trialMessage)},createNewObject:function($super){$super();Brainstorm.Web.Services.IdeaTasks.EditBusinessUnit(this.profile.id,this.fieldBU.getValue(),this.unitUpdated.bind(this),bsCommon.ajaxCallError);this.currentUnitId.value=this.fieldBU.getValue();this.fieldBU.options.selectedValue=this.currentUnitId.value},unitUpdated:function(newUnit){var unit=$("lblIdeaBusinessUnit");if(unit){unit.update(newUnit);this.closeForm({highlight:unit})}}});
BrainstormJs.Forms.Fields.DatePicker=Class.create(BrainstormJs.Forms.Fields.BaseField,{input:false,calendar:false,clearLink:false,dateValue:false,initialize:function($super,options){options=options||{};options.cssClass="datepicker";$super(options)},render:function($super){this.input=new Element("input",{"type":"text","class":"textbox","tabindex":this.tabIndex,"maxlength":20,"readonly":"true"});this.input.identify();if(this.required)this.input.addClassName("required");else{this.clearLink=(new Element("a",
{"href":"#","class":"clear"})).update("clear");this.clearLink.observe("click",function(e){this.onClear();e.stop()}.bind(this));this.clearLink.hide()}this.input.observe("focus",this.onFocus.bind(this));this.input.observe("blur",this.onBlur.bind(this));return $super([this.input,this.clearLink])},beforeShowForm:function(){if(!this.calendar){this.calendar=new dhtmlxCalendarObject(this.input.id);this.calendar.attachEvent("onClick",this.onCalendarClick.bind(this))}},onCalendarClick:function(date){var dateObj=
new Date(date);this.dateValue=dateObj;this.hideCalendar();if(!this.required)this.clearLink.show()},onFocus:function(e){},onBlur:function(e){},onClear:function(){this.clear();if(!this.required)this.clearLink.hide()},showCalendar:function(e){this.calendar.show()},hideCalendar:function(e){this.calendar.hide()},hasValue:function(){return this.getValue()!=""},getValue:function(){return this.dateValue||null},setValue:function(textValue,dateValue){this.input.value=textValue;this.dateValue=dateValue;if(this.dateValue&&
!this.required)this.clearLink.show()},clear:function(){this.setValue("",false)},focus:function(){this.input.focus()},enable:function(){this.input.disabled=false;this.input.removeClassName("disabled")},disable:function(){this.input.disabled=true;this.input.addClassName("disabled")},setError:function(message){this.input.removeClassName("validation-passed");this.input.addClassName("validation-failed");var messageElem=(new Element("span",{"class":"validation-advice submit-error","style":"color: red; display: none"})).update(" * "+
message);this.input.previous("div.fieldTitle").insert(messageElem);Effect.Appear(messageElem,{duration:0.5});Effect.Pulsate(this.input,{pulses:2,duration:1.4,from:0.4,to:1})}});
BrainstormJs.Forms.ChallengeDatesForm=Class.create(BrainstormJs.Forms.BaseForm,{fieldStartDate:false,fieldDeadline:false,initialize:function($super,profile,options){options=options||{};options.createTitle="Update dates";options.editTitle="Update dates";$super(profile,options)},createFields:function($super){this.fieldStartDate=new BrainstormJs.Forms.Fields.DatePicker({title:"Start Date",required:true});this.fieldDeadline=new BrainstormJs.Forms.Fields.DatePicker({title:"Submission Deadline",subtitle:"optional"});
this.registerField(this.fieldStartDate);this.registerField(this.fieldDeadline)},startEditing:function(container){this.showForm({afterFinish:function(){var startDate=Date.parse(container.down(".data-StartDate").value);var startDateString=bsCommon.getDateString(startDate);this.fieldStartDate.setValue(startDateString,startDate);var endDate=Date.parse(container.down(".data-EndDate").value);var endDateString=bsCommon.getDateString(endDate);this.fieldDeadline.setValue(endDateString,endDate)}.bind(this),
editMode:true})},saveEditedObject:function(){Brainstorm.Web.Services.Ajax.UpdateChallengeDates(this.profile.id,this.fieldStartDate.getValue(),this.fieldDeadline.getValue(),this.datesUpdated.bind(this),this.handleAjaxError.bind(this))},datesUpdated:function(jsonDomElement){var challengeStatus=$("challengeStatus");if(challengeStatus){challengeStatus.innerHTML=jsonDomElement.HTML;this.closeForm({highlight:challengeStatus,afterFinish:function(){var refreshDataMsg=challengeStatus.down("div.refreshDataMsg");
if(refreshDataMsg)refreshDataMsg.blindDown({duration:0.5})}})}}});
BrainstormJs.Forms.ChallengeExistingIdeaForm=Class.create(BrainstormJs.Forms.BaseForm,{challengeId:false,fieldIdea:false,choices:false,afterSubmitted:false,initialize:function($super,options){options=options||{};options.createTitle="Submit an existing idea to this challenge";this.choices=options.choices;this.challengeId=options.challengeId;this.afterSubmitted=options.afterSubmitted;$super(null,options)},createFields:function($super){this.fieldIdea=new BrainstormJs.Forms.Fields.DropDownList({title:"Choose Idea",
required:true,choices:this.choices,addBlank:true});this.registerField(this.fieldIdea)},createNewObject:function(){Brainstorm.Web.Services.Ajax.SubmitIdeaToChallenge(this.challengeId,this.fieldIdea.getValue(),this.getCustomFieldValues(),this.ideaSubmitted.bind(this),this.handleAjaxError.bind(this))},ideaSubmitted:function(jsonChallengeIdea){this.closeForm({afterFinish:function(){this.fieldIdea.removeOptionWithValue(jsonChallengeIdea.IdeaId);if(this.afterSubmitted)this.afterSubmitted(jsonChallengeIdea,
this.fieldIdea.isEmpty())}.bind(this)})}});BrainstormJs.Forms.Fields.MultiSelect.TagSelect=Class.create(BrainstormJs.Forms.Fields.MultiSelect.BaseMultiSelectField,{initialize:function($super,options){options=options||{};options.cssClass="tagsfield";$super(options);this.serviceUrl="/Services/Tagging.asmx/FindLikeTags";this.allowNewValues=true;this.height=24}});
BrainstormJs.Forms.Fields.DropDownTagSelect=Class.create(BrainstormJs.Forms.Fields.BaseField,{dropDownList:false,tagSelect:false,initialize:function($super,options){options=options||{};options.cssClass="dropdowntagselect";$super(options)},render:function($super){this.dropDownList=new BrainstormJs.Forms.Fields.DropDownList({choices:this.options.choices});this.dropDownList.render({controlOnly:true});this.tagSelect=new BrainstormJs.Forms.Fields.MultiSelect.TagSelect({});this.tagSelect.render({controlOnly:true});
return $super([this.dropDownList.getElement(),this.tagSelect.getElement()])},afterRender:function(){this.tagSelect.afterRender()},hasValue:function(){return true},getValue:function(){return{dropDownValue:this.dropDownList.getValue(),tagsValue:this.tagSelect.getValue()}},setValue:function(value){if(value.dropDownValue)this.dropDownList.setValue(value.dropDownValue);if(value.tagsValue)this.tagSelect.setValue(value.tagsValue)},clear:function(){this.dropDownList.clear();this.tagSelect.clear()}});
BrainstormJs.Forms.ChallengeForm=Class.create(BrainstormJs.Forms.BaseForm,{fieldName:false,fieldDescription:false,fieldBU:false,fieldTags:false,fieldSubscribe:false,fieldStartDate:false,fieldDeadline:false,trialMessage:false,initialize:function($super,options){options=options||{};options.createTitle="Create a new challenge";if(options.destroyOnClose)this.destroyOnClose=options.destroyOnClose;this.editObjectType="challenge";this.friendlyObjectName="challenge";$super(null,options)},createFields:function($super){this.fieldName=
new BrainstormJs.Forms.Fields.TextBox({title:"Challenge Name",required:true,maxLength:1024});this.fieldDescription=new BrainstormJs.Forms.Fields.TextArea({title:"Description - What is the primary goal of your challenge?",required:true,enableWysiwyg:true});this.fieldStartDate=new BrainstormJs.Forms.Fields.DatePicker({title:"Start Date",required:true});this.fieldDeadline=new BrainstormJs.Forms.Fields.DatePicker({title:"Submission Deadline",subtitle:"optional"});this.fieldBU=new BrainstormJs.Forms.Fields.DropDownList({title:$F("BS_Config_AreaName"),
required:true,choices:choices_Brainstorm_Model_Data_Ideas_IdeaBusinessUnit,addBlank:true});if($F("BS_TrialMode")!=false)this.trialMessage=new BrainstormJs.Forms.Fields.MessageBox({message:"<strong>To customize the "+$F("BS_Config_AreaName")+' choices for your Brainstorm,</strong> <a href="/Upgrade.aspx" target="_blank">upgrade now</a> or <a href="mailto:support@intuitbrainstorm.com">contact us</a>.',hasIcon:false,cssClass:"upgradeMessage"});this.fieldTags=new BrainstormJs.Forms.Fields.MultiSelect.TagSelect({title:"Tags",
help:"<p>Adding tags to your challenge makes it easier for you to find related ideas and for others to discover your challenge.</p>",subtitle:"(examples: new products, customer acquisition, mobile)",required:false});this.fieldSubscribe=new BrainstormJs.Forms.Fields.CheckBox({title:"Notify me of activity on this challenge.",startChecked:true});this.registerField(this.fieldName);this.registerField(this.fieldDescription);this.registerField(this.fieldStartDate);this.registerField(this.fieldDeadline);
this.registerField(this.fieldBU);if(this.trialMessage!=false)this.registerField(this.trialMessage);this.registerField(this.fieldTags);this.registerField(this.fieldSubscribe)},createNewObject:function($super){$super();Brainstorm.Web.Services.Ajax.CreateChallenge(this.fieldName.getValue(),this.fieldDescription.getValue(),this.fieldStartDate.getValue(),this.fieldDeadline.getValue(),this.fieldBU.getValue(),this.fieldTags.getValue(),this.fieldSubscribe.getValue(),this.challengeCreated.bind(this),this.handleAjaxError.bind(this))},
challengeCreated:function(jsonChallenge){bsCommon.openFormCheck=false;document.location="/Challenge.aspx?id="+jsonChallenge.Id},beforeShow:function($super){$super();this.fieldDescription.createWysiwyg();var template=$("challengeCreateTemplate");if(template)window.setTimeout(function(){this.fieldDescription.setValue(template.innerHTML)}.bind(this),1);var todayDate=new Date;var todayText=bsCommon.getDateString(todayDate);this.fieldStartDate.setValue(todayText,todayDate)},afterClose:function($super){$super();
this.fieldDescription.destroyWysiwyg();if(this.destroyOnClose)this.container.remove()},validateForm:function($super){if(this.fieldDeadline.getValue()!=null&&this.fieldDeadline.getValue()<=this.fieldStartDate.getValue()){this.fieldDeadline.setError("Submission deadline must be after start date");return false}return true}});
BrainstormJs.Forms.Fields.MultiSelect.PersonSelect=Class.create(BrainstormJs.Forms.Fields.MultiSelect.BaseMultiSelectField,{initialize:function($super,options){options=options||{};options.cssClass="personSelect";options.warning=false;$super(options);this.serviceUrl="/Services/PersonSearch.asmx/FindPeople";this.allowNewValues=false;this.valueType="int"}});
BrainstormJs.Forms.Fields.CheckBox=Class.create(BrainstormJs.Forms.Fields.BaseField,{checkbox:false,label:false,startChecked:false,warningWhenChecked:false,fxOnChange:false,fxOnChangeByKeyboard:false,observers:false,initialize:function($super,options){options=options||{};options.cssClass="checkbox";this.startChecked=options.startChecked||false;this.warningWhenChecked=options.warningWhenChecked||false;this.observers=new Array;this.fxOnChange=this.onChange.bind(this);this.fxOnChangeByKeyboard=function(e){if(e.keyCode==
Event.KEY_SPACE||e.charCode==Event.KEY_SPACE)this.fxOnChange()}.bind(this);$super(options)},render:function($super){this.checkbox=new Element("input",{"class":"checkbox","type":"checkbox","tabindex":this.tabIndex});this.checkbox.identify();if(this.required)this.checkbox.addClassName("required");if(!Prototype.Browser.IE)this.checkbox.observe("change",this.onChange.bind(this));else{this.checkbox.observe("click",this.fxOnChange);this.checkbox.observe("keypress",this.fxOnChangeByKeyboard)}this.label=
(new Element("span",{"class":"label"})).update(this.title);if(this.startChecked)this.checkbox.checked=true;return $super([this.checkbox,this.label])},afterRender:function(){if(this.warningWhenChecked&&this.warningDiv&&!this.checkbox.checked)this.warningDiv.hide()},onChange:function(){if(this.warningWhenChecked&&this.warningDiv)if(this.checkbox.checked)Effect.BlindDown(this.warningDiv,{duration:0.5});else Effect.BlindUp(this.warningDiv,{duration:0.5});if(this.observers)for(var i=0,j=this.observers.length;i<
j;i++)this.observers[i](this)},renderTitle:function($super){},hasValue:function(){return true},getValue:function(){return this.checkbox.checked},setValue:function(value){this.checkbox.checked=value===true||value&&value.toString().toLowerCase()=="true"},clear:function(){if(this.warningWhenChecked&&this.warningDiv&&!this.checkbox.checked)this.warningDiv.hide();this.checkbox.checked=this.startChecked||false},beforeValidation:function(){},focus:function(){},getElement:function(){return this.checkbox},
disable:function(){this.checkbox.disabled=true},enable:function(){this.checkbox.disabled=false},addObserver:function(observer){this.observers.push(observer)}});
BrainstormJs.Forms.IdeaForm=Class.create(BrainstormJs.Forms.BaseForm,{fieldTitle:false,fieldBody:false,fieldStatus:false,fieldBU:false,fieldTeam:false,fieldTags:false,fieldSubscribe:false,trialMessage:false,initialize:function($super,options){options=options||{};options.createTitle=options.createTitle||"Add a new idea";if(options.destroyOnClose)this.destroyOnClose=options.destroyOnClose;this.editObjectType="idea";this.friendlyObjectName="idea";$super(null,options)},createFields:function($super){this.fieldTitle=
new BrainstormJs.Forms.Fields.TextBox({title:"Punchline - A short description of your idea that should fit inside this box.",required:true,maxLength:1024});this.fieldBody=new BrainstormJs.Forms.Fields.TextArea({title:"Description - Flesh out your idea. What problem does it solve?  Why is this problem important?",required:true,enableWysiwyg:true});this.fieldStatus=new BrainstormJs.Forms.Fields.DropDownList({title:"Current Status",required:true,choices:choices_Brainstorm_Model_Data_Ideas_IdeaStatus,
addBlank:true});this.fieldBU=new BrainstormJs.Forms.Fields.DropDownList({title:"Which "+$F("BS_Config_AreaName").toLowerCase()+" will this idea help?",required:true,choices:choices_Brainstorm_Model_Data_Ideas_IdeaBusinessUnit,addBlank:true});if($F("BS_TrialMode")!=false)this.trialMessage=new BrainstormJs.Forms.Fields.MessageBox({message:"<strong>To customize the choices for Status or "+$F("BS_Config_AreaName")+',</strong> <a href="/Upgrade.aspx" target="_blank">upgrade now</a> or <a href="mailto:support@intuitbrainstorm.com">contact us</a>.',
hasIcon:false,cssClass:"upgradeMessage"});this.fieldTags=new BrainstormJs.Forms.Fields.MultiSelect.TagSelect({title:"Tags",help:'<p>A tag is a descriptive label. For example, if you\'re adding an idea about a new type of tennis racket, you might add tags like "tennis," "sports equipment," and "new product." Adding tags to your idea makes it easier for you to find related ideas and for others to discover your idea.</p>',subtitle:"(examples: new products, customer acquisition, mobile)",required:false});
this.fieldTags.warning=false;this.fieldSubscribe=new BrainstormJs.Forms.Fields.CheckBox({title:"Send me email alerts when there is activity on this idea",required:false,startChecked:true});this.registerField(this.fieldTitle);this.registerField(this.fieldBody);this.registerField(this.fieldStatus);this.registerField(this.fieldBU);if(this.trialMessage!=false)this.registerField(this.trialMessage);this.registerField(this.fieldTags);this.registerField(this.fieldSubscribe)},createNewObject:function(){Brainstorm.Web.Services.Ajax.CreateIdea(this.fieldTitle.getValue(),
this.fieldBody.getValue(),this.fieldStatus.getValue(),this.fieldBU.getValue(),this.fieldSubscribe.getValue(),this.fieldTags.getValue(),this.ideaCreated.bind(this),this.handleAjaxError.bind(this))},ideaCreated:function(newIdeaId){bsCommon.openFormCheck=false;document.location="/Idea.aspx?id="+newIdeaId},beforeShow:function(){this.fieldBody.createWysiwyg()},afterClose:function(){this.fieldBody.destroyWysiwyg();if(this.destroyOnClose)this.container.remove()}});
BrainstormJs.Forms.ChallengeNewIdeaForm=Class.create(BrainstormJs.Forms.IdeaForm,{challengeId:false,initialize:function($super,options){options=options||{};options.createTitle="Submit a new idea to this challenge";this.challengeId=options.challengeId;$super(options)},createNewObject:function(){Brainstorm.Web.Services.Ajax.SubmitNewIdeaToChallenge(this.fieldTitle.getValue(),this.fieldBody.getValue(),this.fieldStatus.getValue(),this.fieldBU.getValue(),this.fieldSubscribe.getValue(),this.fieldTags.getValue(),
this.challengeId,this.getCustomFieldValues(),this.ideaCreated.bind(this),this.handleAjaxError.bind(this))},ideaCreated:function(jsonChallengeIdea){bsCommon.openFormCheck=false;document.location="/Idea.aspx?id="+jsonChallengeIdea.IdeaId+"&ch="+jsonChallengeIdea.ChallengeId}});
BrainstormJs.Forms.ChallengeTeamMemberForm=Class.create(BrainstormJs.Forms.BaseListForm,{fieldPeople:false,options:false,objectLi:false,initialize:function($super,profile,options){options=options||{};options.createTitle="Add a team member";options.editTitle="Edit team member";options.deleteConfirmText="Are you sure you want to remove this person from the challenge team?";this.options=options;$super(profile,options);this.editObjectType="person";this.friendlyObjectName="team member"},createFields:function($super){this.fieldPeople=
new BrainstormJs.Forms.Fields.MultiSelect.PersonSelect({title:"Full Name",required:true,help:"<p>Start typing a person's name and matches in the directory will appear.</p>",maxItems:1});this.registerField(this.fieldPeople)},createNewObject:function($super){$super();Brainstorm.Web.Services.Ajax.AddChallengeTeamMember(this.profile.id,this.fieldPeople.getValue()[0],this.newObjectCreated.bind(this),bsCommon.ajaxCallError)},saveNewOrder:function($super,profileId,serializedOrder,afterSave){Brainstorm.Web.Services.Ajax.ReorderChallengeTeamMembers(profileId,
serializedOrder,afterSave,bsCommon.ajaxCallError)},callDeleteObject:function(objectLi,objectType,personId){Brainstorm.Web.Services.Ajax.RemoveChallengeTeamMember(this.profile.id,personId,this.objectDeleted.bind(this),bsCommon.ajaxCallError,objectLi)}});
BrainstormJs.Forms.ClassifiedForm=Class.create(BrainstormJs.Forms.BaseListForm,{fieldBody:false,fieldTags:false,fieldFilledBy:false,initialize:function($super,profile,options){options=options||{};options.createTitle="Add a new help wanted ad";options.editTitle="Edit help wanted ad";options.emptyMessage="This idea does not have any help wanted ads.";$super(profile,options);this.editObjectType="ideaclassified";this.friendlyObjectName="help wanted ad"},createFields:function($super){this.fieldBody=new BrainstormJs.Forms.Fields.TextArea({title:"Body",
required:true,enableWysiwyg:false,dataSelector:".data-body"});this.fieldTags=new BrainstormJs.Forms.Fields.MultiSelect.TagSelect({title:"Skills needed",help:"<p>Adding skill tags helps Brainstorm instantly display the people most likely to be able to help you out.</p>",required:false});this.fieldFilledBy=new BrainstormJs.Forms.Fields.MultiSelect.PersonSelect({title:"Filled By",required:false,help:"<p>Selecting a person in this field will mark this classified as filled and will remove it from the profile.</p>",
maxItems:1,hideOnAdd:true});this.registerField(this.fieldBody);this.registerField(this.fieldTags);this.registerField(this.fieldFilledBy)},createNewObject:function($super){$super();Brainstorm.Web.Services.IdeaTasks.CreateClassified(bsCommon.getRequestToken(),this.profile.id,this.fieldBody.getValue(),this.fieldTags.getValue(),this.classifiedCreated.bind(this),bsCommon.ajaxCallError)},classifiedCreated:function(jsonDomElement){var newLi=this.newObjectCreated(jsonDomElement)},loadObjectValues:function($super,
objectLi){$super(objectLi);var data=objectLi.down(".data");this.fieldBody.setValue(data.down(".bodytext").value);this.fieldTags.setValue(data.down(".tags").value)},saveEditedObject:function($super){$super();var filledByValue=this.fieldFilledBy.getValue();if(filledByValue&&filledByValue.length&&filledByValue.length>0)filledByValue=filledByValue[0];else filledByValue=0;Brainstorm.Web.Services.IdeaTasks.UpdateClassified(this.editObjectId,this.fieldBody.getValue(),this.fieldTags.getValue(),filledByValue,
this.classifiedSaved.bind(this),bsCommon.ajaxCallError)},classifiedSaved:function(editedClassified){if(editedClassified.Filled){var listItem=this.editObjectElement;this.objectDeleted(false,listItem);this.closeForm({afterFinish:function(){bsCommon.alert("The classified has been marked as filled and "+editedClassified.FilledByName+" has been added to this team (refresh the page to view in team list).")}});return}var data=this.editObjectElement.down("div.data");data.down(".bodytext").value=editedClassified.Body;
data.down(".tags").value=editedClassified.TagsData;this.editObjectElement.down(".bodytext").innerHTML=editedClassified.Body;this.editObjectElement.down(".tagsView").innerHTML=editedClassified.TagsView;this.closeForm({highlight:this.editObjectElement.down("div.classified")});this.updatePeopleRelated()},updatePeopleRelated:function(){Brainstorm.Web.Services.IdeaTasks.GetRelatedPeopleInClassified(this.editObjectId,this.relatedPeopleUpdated.bind(this),bsCommon.ajaxCallError)},relatedPeopleUpdated:function(relatedPeople){var relatedPeopleDom=
this.editObjectElement.down(".relatedPeople");if(relatedPeopleDom)relatedPeopleDom.replace(relatedPeople.HTML)}});
BrainstormJs.Forms.CommentForm=Class.create(BrainstormJs.Forms.BaseForm,{formContainer:false,destroyOnClose:false,editingComment:false,fieldBody:false,initialize:function($super,options){options=options||{};options.createTitle="Add a new comment";options.editTitle="Edit comment";if(options.destroyOnClose)this.destroyOnClose=options.destroyOnClose;$super(false,options)},createFields:function($super){this.fieldBody=new BrainstormJs.Forms.Fields.TextArea({title:"Body",required:true,enableWysiwyg:true,
dataSelector:".data-Body"});this.registerField(this.fieldBody)},createNewObject:function($super){},startEditing:function(comment,editLinkClicked){this.editingExisting=true;this.editingComment=comment;this.showForm({afterFinish:function(){this.loadObjectValues(this.editingComment.container)}.bind(this),editMode:true,linkClicked:editLinkClicked})},saveEditedObject:function(){if(this.editingExisting&&this.editingComment)Brainstorm.Web.Services.Ajax.EditComment(this.editingComment.id,this.fieldBody.getValue(),
this.commentUpdated.bind(this),this.handleAjaxError.bind(this))},commentUpdated:function(newComment){var container=this.editingComment.container;var commentBody=container.select("div.data-Body")[0];this.closeForm({afterFinish:function(){commentBody.innerHTML=newComment.Body;new Effect.Highlight(commentBody)}.bind(this)});this.editingComment=false;this.stopEditingObject()},onCancel:function(){if(this.hideWhenCanceled)this.hideWhenCanceled.fade({duration:1})},afterShow:function($super){$super();this.fieldBody.createWysiwyg()},
afterClose:function(){this.fieldBody.destroyWysiwyg();if(this.destroyOnClose)this.container.remove()}});
BrainstormJs.Forms.FeatureIdeaForm=Class.create(BrainstormJs.Forms.BaseForm,{fieldMessage:false,initialize:function($super,profile,options){options=options||{};this.ideaId=profile.id;this.link=$("linkFeatureIdea");options.createTitle=this.isFeatured()?"Remove this idea from featured section":"Feature this idea";options.submitButtonTitle=this.isFeatured()?"Remove":"Submit";options.parentContainer="featureIdeaForm-container";options.destroyOnClose=true;$super(profile,options)},isFeatured:function(){return this.link.hasClassName("remove")},
createFields:function($super){if(this.isFeatured());else{this.fieldMessage=new BrainstormJs.Forms.Fields.TextArea({title:"Describe this idea",required:false,enableWysiwyg:false});this.registerField(this.fieldMessage)}},createNewObject:function($super){$super();if(this.isFeatured())Brainstorm.Web.Services.Ajax.UnfeatureIdea(this.profile.id,this.onUntoggle.bind(this),bsCommon.ajaxCallError);else Brainstorm.Web.Services.Ajax.FeatureIdea(this.ideaId,this.fieldMessage.getValue(),this.onSuccess.bind(this),
bsCommon.ajaxCallError)},onSuccess:function(domElement){var featuredMessage=$("featuredMessage");this.closeForm({dontFadeOpenLink:true,afterFinish:function(){featuredMessage.update(domElement.HTML);featuredMessage.next(".featureIdeaSection").remove()}})},afterClose:function($super){if(this.options.destroyOnClose)this.container.remove()},onUntoggle:function(){var featuredMessage=$("featuredMessage");this.closeForm({dontFadeOpenLink:true,afterFinish:function(){featuredMessage.update("This idea is currently not featured. ");
featuredMessage.next(".featureIdeaSection").remove()}})}});
BrainstormJs.Forms.FeedbackForm=Class.create(BrainstormJs.Forms.BaseForm,{fieldTitle:false,fieldBody:false,fieldStatus:false,pageUrl:false,warningInitialized:false,brainstormFeedback:false,initialize:function($super,profile,pageUrl,options){options=options||{};options.createTitle="Submit feedback or help request about Brainstorm";if(options.destroyOnClose)this.destroyOnClose=options.destroyOnClose;var b=$F("BS_EnableBstormFeedback");this.brainstormFeedback=b=="True";this.pageUrl=pageUrl;$super(profile,
options)},createFields:function($super){this.fieldTitle=new BrainstormJs.Forms.Fields.TextBox({title:"Subject",required:true,maxLength:1024});this.fieldBody=new BrainstormJs.Forms.Fields.TextArea({title:"Description - Your detailed feedback message, help request, or bug report",required:true,enableWysiwyg:false});if(this.brainstormFeedback)this.fieldDisclaimer=new BrainstormJs.Forms.Fields.MessageBox({message:$("feedbackConfidentialWarning").innerHTML,hasIcon:true,cssClass:"messagebox"});this.registerField(this.fieldTitle);
this.registerField(this.fieldBody);if(this.brainstormFeedback)this.registerField(this.fieldDisclaimer)},createNewObject:function($super){$super();Brainstorm.Web.Services.Ajax.SubmitFeedback(bsCommon.getRequestToken(),this.fieldTitle.getValue(),this.fieldBody.getValue(),this.pageUrl,this.feedbackCreated.bind(this),bsCommon.ajaxCallError)},feedbackCreated:function(successMessage){if(successMessage){var messageContainer=$("feedbackForm-message");messageContainer.innerHTML=successMessage}this.closeForm({afterFinish:function(){var message=
$("feedbackSuccessMessage");if(message)Effect.BlindDown(message,{duration:0.5,afterFinish:function(){Effect.Fade(message,{duration:0.5,delay:10})}})}})},beforeShow:function($super){$super();this.fieldBody.createWysiwyg();if(!this.warningInitialized){var trigger=$("linkFeedbackConfidential");var content=$("feedbackConfidentialDetail");trigger.observe("click",function(e){e.stop()});new Tip(trigger,content,{title:"About Sensitive Information",style:"darkgrey",closeButton:false,hideAfter:15,stem:"bottomLeft",
hook:{target:"topLeft",tip:"bottomLeft"},offset:{x:0,y:2},width:350,delay:0.25});this.warningInitialized=true}},afterClose:function($super){$super();this.fieldBody.destroyWysiwyg();if(this.destroyOnClose)this.container.remove()}});
BrainstormJs.Forms.ImageUploadForm=Class.create(BrainstormJs.Forms.BaseImageUploadForm,{fieldUrl:false,fieldFileName:false,editor:false,initialize:function($super,editor,options){this.editor=editor;options=options||{};options.createTitle="Insert image";options.submitButtonTitle="Start upload";options.fieldLabel="File";options.editMode=false;options.onImageUploaded=this.imageUploaded.bind(this);this.friendlyObjectName="image";if(options.destroyOnClose)this.destroyOnClose=options.destroyOnClose;$super(options)},
imageUploaded:function(documentId,mimeType,fileSize,file){Brainstorm.Web.Services.Ajax.UploadImage(documentId,file.name,this.imageSaved.bind(this),bsCommon.ajaxCallError)},imageSaved:function(jsonImage){this.preloadImage(jsonImage.ImageUrl,jsonImage.ModifiedImageUrl,jsonImage.WasModified)},preloadImage:function(originalUrl,profileUrl,lightview){var image=new Image;image.onload=function(){this.insertAndClose(originalUrl,profileUrl,lightview)}.bind(this);image.src=lightview?profileUrl:originalUrl},
insertAndClose:function(originalUrl,profileUrl,lightview){var imgArgs={};var linkArgs={};var appUrl=bsCommon.getAppUrl();if(originalUrl&&originalUrl.length>0&&originalUrl.charAt(0)=="/")originalUrl=appUrl+originalUrl;if(profileUrl&&profileUrl.length>0&&profileUrl.charAt(0)=="/")profileUrl=appUrl+profileUrl;var imgSrc=lightview?profileUrl:originalUrl;if(tinymce.isWebKit)this.editor.getWin().focus();tinymce.extend(imgArgs,{src:imgSrc,alt:"Image","class":"wysiwygImage"});var selectedNode=this.editor.selection.getNode();
if(selectedNode&&selectedNode.nodeName=="IMG")this.editor.dom.setAttribs(selectedNode,imgArgs);else{var html='<img id="__mce_tmp" />';if(lightview){var cssClass="";html='<a href="'+originalUrl+'" class="'+cssClass+'">'+html+"</a>"}this.editor.execCommand("mceInsertContent",false,html,{skip_undo:1});this.editor.dom.setAttribs("__mce_tmp",imgArgs);this.editor.dom.setAttrib("__mce_tmp","id","");this.editor.undoManager.add()}this.closeForm()},beforeShow:function($super){$super();var selectedNode=this.editor.selection.getNode();
if(selectedNode&&selectedNode.nodeName=="IMG")this.fieldUrl.setValue(this.editor.dom.getAttrib(selectedNode,"src"))}});
BrainstormJs.Forms.ImageUploadForm2=Class.create(BrainstormJs.Forms.BaseImageUploadForm,{fieldUrl:false,fieldFileName:false,image:false,invoker:false,fieldLabel:false,initialize:function($super,invoker,image,options){options=options||{};options.createTitle="Insert image";options.submitButtonTitle="Start upload";options.editMode=false;options.onImageUploaded=this.imageUploaded.bind(this);options.fieldLabel="Profile Picture";this.friendlyObjectName="image";this.invoker=invoker;this.image=image;if(options.destroyOnClose)this.destroyOnClose=
options.destroyOnClose;$super(options)},imageUploaded:function(documentId,mimeType,fileSize,file){Brainstorm.Web.Services.Ajax.UploadProfileImage(documentId,file.name,this.imageSaved.bind(this),bsCommon.ajaxCallError)},imageSaved:function(jsonImage){this.preloadImage(jsonImage.ImageUrl)},preloadImage:function(imageUrl){var image=new Image;image.onload=function(){this.insertAndClose(imageUrl)}.bind(this);image.src=imageUrl},insertAndClose:function(imageUrl){this.invoker.originalImage=this.image.src=
imageUrl;this.closeForm()}});
BrainstormJs.Forms.ImageUploadForm3=Class.create(BrainstormJs.Forms.BaseImageUploadForm,{existingImage:false,newImage:false,jsonImage:false,initialize:function($super,options){options=options||{};options.createTitle="Insert image";options.submitButtonTitle="Submit";options.fieldLabel="File";options.editMode=false;options.onImageUploaded=this.imageUploaded.bind(this);this.imageSaved=options.imageSaved;$super(options)},imageUploaded:function(documentId,mimeType,fileSize,file){Brainstorm.Web.Services.Ajax.UploadImage(documentId,
file.name,this.imageSaved.bind(this),bsCommon.ajaxCallError)}});
BrainstormJs.Forms.ImStuckForm=Class.create(BrainstormJs.Forms.BaseForm,{trialMessage:false,fieldIsStuck:false,fieldMessage:false,initialize:function($super,profile,options){options=options||{};options.createTitle="Request help from the community";$super(profile,options)},createFields:function($super){if($F("BS_TrialMode")!=false)this.trialMessage=new BrainstormJs.Forms.Fields.MessageBox({message:'<strong>To make "I\'m stuck" alert the people in your organization who can best help,</strong><br /><a href="/Upgrade.aspx" target="_blank">upgrade now</a> or <a href="mailto:support@intuitbrainstorm.com">contact us</a>',hasIcon:false,
cssClass:"upgradeMessage"});this.fieldIsStuck=new BrainstormJs.Forms.Fields.CheckBox({title:"This idea is stuck",startChecked:true,warningWhenChecked:true,warning:"Marking this idea as stuck will display your message to the community, as well as send an email to innovation leaders."});this.fieldMessage=new BrainstormJs.Forms.Fields.TextArea({title:"Current obstacles",help:"<p>Please describe the problems facing your idea/project, and what innovation leaders and the community can do to help you move your idea along.</p>",
required:true,enableWysiwyg:false,triggerCheckbox:this.fieldIsStuck});if(this.trialMessage!=false)this.registerField(this.trialMessage);this.registerField(this.fieldIsStuck);this.registerField(this.fieldMessage)},beforeShow:function(){this.fieldIsStuck.disable()},createNewObject:function($super){$super();Brainstorm.Web.Services.Ajax.UpdateIdeaStuckStatus(this.profile.id,this.fieldIsStuck.getValue(),this.fieldMessage.getValue(),this.onSuccess.bind(this),bsCommon.ajaxCallError)},onSuccess:function(newMessage){this.closeForm({afterFinish:function(){Effect.BlindUp("linkMakeIdeaStuck",
{duration:0.5});$("ideaStuckMessage").innerHTML=newMessage;Effect.BlindDown("stuckMessageContainer",{duration:0.5,delay:0.05})}})}});
BrainstormJs.Forms.InviteOthersForm=Class.create(BrainstormJs.Forms.BaseForm,{fieldEmailAddresses:false,fieldMessage:false,trialMessage:false,signupAllowed:false,whiteListedDomain:false,orgName:false,initialize:function($super,options){options=options||{};options.createTitle="Invite others to Brainstorm";$super(null,options)},createFields:function($super){var warning;var variables=this.parentContainer.down("#signupAdvisory");if(variables)warning=variables.innerHTML;this.fieldEmailAddresses=new BrainstormJs.Forms.Fields.TextArea({title:"Enter email addresses",
help:"Separate multiple email addresses with a comma or semicolon.",autoGrow:true,rows:2,spellcheckOff:true,required:true,warning:warning});if($F("BS_TrialMode")!=false)this.trialMessage=new BrainstormJs.Forms.Fields.MessageBox({message:'<strong>For complete user access control,</strong><br /><a href="/Upgrade.aspx" target="_blank">upgrade now</a> or <a href="mailto:support@intuitbrainstorm.com">contact us</a>',hasIcon:false,cssClass:"upgradeMessage"});this.fieldMessage=new BrainstormJs.Forms.Fields.TextArea({title:"Message",
required:false,enableWysiwyg:false});this.registerField(this.fieldEmailAddresses);if(this.trialMessage!=false)this.registerField(this.trialMessage);this.registerField(this.fieldMessage)},createNewObject:function($super){$super();Brainstorm.Web.Services.Ajax.InviteOthers(this.fieldEmailAddresses.getValue(),this.fieldMessage.getValue(),this.onSuccess.bind(this),bsCommon.ajaxCallError)},onSuccess:function(newMessage){this.closeForm({afterFinish:function(){bsCommon.showSuccess("Brainstorm invitations sent.")}})}});
BrainstormJs.Forms.JoinTeamForm=Class.create(BrainstormJs.Forms.BaseForm,{fieldMessage:false,classifiedId:0,initialize:function($super,profile,options){options=options||{};options.createTitle=options.createTitle||"Request to join this team";this.classifiedId=options.classifiedId||0;$super(profile,options)},createFields:function($super){this.fieldMessage=new BrainstormJs.Forms.Fields.TextArea({title:"Message to team leader",help:"<p>Please provide a brief personal message to the team leader outlining your reasons for being added to the team.</p>",
required:true,enableWysiwyg:false});this.registerField(this.fieldMessage)},createNewObject:function($super){$super();Brainstorm.Web.Services.IdeaTasks.RequestToJoinTeam(this.profile.id,this.classifiedId,this.fieldMessage.getValue(),this.onSuccess.bind(this),bsCommon.ajaxCallError)},onSuccess:function(numPeople){var openLink=this.getPrimaryOpenLink();var classified=openLink.up("div.classified");var confirmMessage=openLink.next("div.confirmMessage");if(classified){confirmMessage=classified.down("div.confirmMessage");
var openLinkContainer=openLink.up();openLinkContainer.blindUp({duration:0.5})}else openLink.blindUp({duration:0.5});this.closeForm({dontFadeOpenLink:true,afterFinish:function(){confirmMessage.blindDown({duration:0.5})}})}});
BrainstormJs.Forms.PersonProfileForm=Class.create(BrainstormJs.Forms.BaseForm,{fieldVisibility:false,onCreate:false,relatedProfileImage:false,initialize:function($super,options){options=options||{};this.personId=options.personId;this.relatedProfileImage=options.relatedProfileImage;options.createTitle="Edit Profile Information";$super(null,options)},createFields:function($super){this.fieldFirstName=new BrainstormJs.Forms.Fields.TextBox({required:true,title:"First Name",dataSelector:"#dataFirstName",
maxLength:50});this.fieldLastName=new BrainstormJs.Forms.Fields.TextBox({required:true,title:"Last Name",dataSelector:"#dataLastName",maxLength:50});this.fieldDisplayName=new BrainstormJs.Forms.Fields.TextBox({required:true,title:"Display Name",dataSelector:"#dataDisplayName",maxLength:100});this.fieldRole=new BrainstormJs.Forms.Fields.TextBox({title:'Role <span class="small">(optional)</span>',dataSelector:"#dataRole",maxLength:150});this.fieldOrg=new BrainstormJs.Forms.Fields.TextBox({title:'Organization <span class="small">(optional)</span>',
dataSelector:"#dataOrg",maxLength:50});this.fieldEmail=new BrainstormJs.Forms.Fields.TextBox({required:true,title:"Email Address",dataSelector:"#dataEmail",maxLength:100});this.fieldPhone=new BrainstormJs.Forms.Fields.TextBox({title:'Phone Number <span class="small">(optional)</span>',dataSelector:"#dataPhone",maxLength:100});this.fieldLocation=new BrainstormJs.Forms.Fields.TextBox({title:'Location <span class="small">(optional)</span>',dataSelector:"#dataLocation",maxLength:100});this.registerField(this.fieldFirstName);
this.registerField(this.fieldLastName);this.registerField(this.fieldDisplayName);this.registerField(this.fieldRole);this.registerField(this.fieldOrg);this.registerField(this.fieldEmail);this.registerField(this.fieldPhone);this.registerField(this.fieldLocation)},createNewObject:function($super){$super();Brainstorm.Web.Services.Ajax.EditPersonProfile(this.personId,this.fieldFirstName.getValue(),this.fieldLastName.getValue(),this.fieldDisplayName.getValue(),this.fieldRole.getValue(),this.fieldOrg.getValue(),
this.fieldEmail.getValue(),this.fieldPhone.getValue(),this.fieldLocation.getValue(),this.profileUpdated.bind(this),bsCommon.ajaxCallError)},profileUpdated:function(user){this.closeForm({afterFinish:function(){var updateInputs=$H({dataFirstName:user.FirstName,dataLastName:user.LastName});var keys=updateInputs.keys();for(var i=0,numKeys=keys.length;i<numKeys;i++){var input=$(keys[i]);if(input)input.value=updateInputs.get(keys[i])}var updateFields=$H({dataRole:user.Role,dataPhone:user.Phone,dataEmail:user.EmailAddress,
dataDisplayName:user.Name,dataLocation:user.DisplayLocation,dataOrg:user.Organization});keys=updateFields.keys();for(i=0,numKeys=keys.length;i<numKeys;i++){var dataElem=$(keys[i]);var dataDisplay=$$("."+keys[i]+"Display")[0];var newValue=updateFields.get(keys[i]);if(dataElem){dataElem.update(newValue);if(dataDisplay)if(newValue==null||newValue=="")dataDisplay.hide();else dataDisplay.show()}}if(updateFields.get("dataRole")==null||updateFields.get("dataOrg")==null)if(updateFields.get("dataRole")==null&&
updateFields.get("dataOrg")==null)$("roleOrgRow").hide();else $("roleOrgDelimiter").hide();else $("roleOrgRow").show();var profileBody=$("personIntro");new Effect.Highlight(profileBody)}.bind(this)})},afterClose:function($super,options){$super();if(this.destroyOnClose)this.container.remove();if(this.relatedProfileImage){$("editImage").removeClassName("active");this.relatedProfileImage.hideChange()}},afterShow:function($super){$super();this.loadObjectValues(this.parentContainer);if(this.relatedProfileImage){$("editImage").addClassName("active");
this.relatedProfileImage.showChange()}}});
BrainstormJs.Forms.PersonReportFieldForm=Class.create(BrainstormJs.Forms.BaseForm,{fieldVisibility:false,onCreate:false,initialize:function($super,options){this.personId=options.personId;$super(null,options)},createFields:function($super){this.fieldUniqueId=new BrainstormJs.Forms.Fields.TextBox({title:'Unique ID <span class="small">(optional)</span>',dataSelector:"#dataUniqueId",maxLength:60,protectedLinkFn:function(){bsCommon.confirm({title:"Confirm Unique ID Change",text:"Are you sure you want to change the Unique ID for this user?",
detailText:"The Unique ID is critical for bulk user imports/updates to work successfully. Changing Unique IDs in Brainstorm without ensuring that they match with the Unique IDs included in your Bulk Import/Update files may result in undesirable and irreparable results (such as duplicate users, inaccurate user data, etc).",width:500,onConfirm:function(){this.enable();this.focus()}.bind(this)})}});this.field1=new BrainstormJs.Forms.Fields.TextBox({title:'Reporting Field 1 <span class="small">(optional)</span>',
dataSelector:"#dataField1",maxLength:64});this.field2=new BrainstormJs.Forms.Fields.TextBox({title:'Reporting Field 2 <span class="small">(optional)</span>',dataSelector:"#dataField2",maxLength:64});this.field3=new BrainstormJs.Forms.Fields.TextBox({title:'Reporting Field 3 <span class="small">(optional)</span>',dataSelector:"#dataField3",maxLength:64});this.field4=new BrainstormJs.Forms.Fields.TextBox({title:'Reporting Field 4 <span class="small">(optional)</span>',dataSelector:"#dataField4",maxLength:64});
this.field5=new BrainstormJs.Forms.Fields.TextBox({title:'Reporting Field 5 <span class="small">(optional)</span>',dataSelector:"#dataField5",maxLength:64});this.registerField(this.fieldUniqueId);this.registerField(this.field1);this.registerField(this.field2);this.registerField(this.field3);this.registerField(this.field4);this.registerField(this.field5)},createNewObject:function($super){$super();$$(".submit-error").each(function(adv){adv.remove()});Brainstorm.Web.Services.Ajax.EditPersonReportingInfo(this.personId,
this.fieldUniqueId.getValue(),this.field1.getValue(),this.field2.getValue(),this.field3.getValue(),this.field4.getValue(),this.field5.getValue(),this.reportInfoUpdated.bind(this),this.onError.bind(this))},onError:function(error){this.enableForm();var message=error.get_message();if(message.indexOf("The unique Id")!=-1){this.fieldUniqueId.input.addClassName("validation-failed");var advice=(new Element("span",{"class":"validation-advice submit-error","style":"color: red; display: none"})).update(" * "+
message);this.fieldUniqueId.input.previous("div.fieldTitle").insert(advice);Effect.Appear(advice,{duration:0.5});Effect.Pulsate(this.fieldUniqueId.input,{pulses:2,duration:1.4,from:0.4,to:1})}},enableForm:function(){this.validator.reset();this.toggleSubmitButton(true);this.progressSpinner.hide();this.cancelButton.show();this.fieldContainer.removeClassName("disabledFields");for(var i=0,j=this.fields.length;i<j;i++){var field=this.fields[i];field.enabled=true;field.enable()}},reportInfoUpdated:function(user){this.closeForm({afterFinish:function(){var updateInputs=
$H({dataUniqueId:user.UniqueId,dataField1:user.Field1,dataField2:user.Field2,dataField3:user.Field3,dataField4:user.Field4,dataField5:user.Field5});var keys=updateInputs.keys();for(var i=0,numKeys=keys.length;i<numKeys;i++){var input=$(keys[i]);if(input)input.value=updateInputs.get(keys[i])}var profileBody=$("personIntro");new Effect.Highlight(profileBody)}.bind(this)})},afterClose:function($super,options){$super();if(this.destroyOnClose)this.container.remove()},afterShow:function($super){$super();
this.loadObjectValues(this.parentContainer);this.fieldUniqueId.disable()}});
BrainstormJs.Forms.PipelineCandidateFilterForm=Class.create(BrainstormJs.Forms.BaseForm,{fieldBusinessAreas:false,fieldTags:false,trialMessage:false,afterFiltersUpdated:false,initialize:function($super,profile,options){options=options||{};options.createTitle="Update candidate filters";options.editTitle="Update candidate filters";this.afterFiltersUpdated=options.afterFiltersUpdated||false;options.submitButtonTitle="Apply";$super(profile,options)},createFields:function($super){this.fieldBusinessAreas=
new BrainstormJs.Forms.Fields.MultiDropDownList({title:"Area Filters &ndash; select the "+$F("BS_Config_AreaName").toLowerCase()+"(s) you want ideas in your pipeline to come from",required:false,choices:choices_Brainstorm_Model_Data_Ideas_IdeaBusinessUnit,addBlank:true,blankLabel:"All "+$F("BS_Config_AreaName")+"s",popupTitle:"Select multiple "+$F("BS_Config_AreaName").toLowerCase()+"s",help:"<p>Use the Area Filter dropdown to focus on a specific "+$F("BS_Config_AreaName").toLowerCase()+' you want ideas in your pipeline to come from.  If more than one area is applicable, click the "Select Multiple" link and check the boxes for the areas you want.  If you don\'t want to focus on a specific area, set the dropdown to "all."</p>'});
if($F("BS_TrialMode")!=false)this.trialMessage=new BrainstormJs.Forms.Fields.MessageBox({message:"<strong>To customize the "+$F("BS_Config_AreaName")+' choices for your Brainstorm,</strong> <a href="/Upgrade.aspx" target="_blank">upgrade now</a> or <a href="mailto:support@intuitbrainstorm.com">contact us</a>.',hasIcon:false,cssClass:"upgradeMessage"});this.fieldTags=new BrainstormJs.Forms.Fields.DropDownTagSelect({title:"Tag Filters &ndash; type the topics you want ideas in your pipeline to cover",
choices:[{value:Brainstorm.Model.Enums.BooleanOperation.Or,text:"ANY of the following"},{value:Brainstorm.Model.Enums.BooleanOperation.And,text:"ALL of the following"}],help:'<p>Use the Tag Filters to focus the ideas you want in your pipeline on specific topics.  As you type, suggestions will appear that already exist in Brainstorm.  Select from these suggestions until you\'re happy.  If the dropdown is set to "ANY of the following," then the filter will find ideas that contain at least one of the tags you typed.  If the dropdown is set to "ALL of the following," then the filter will find only the ideas that have each of the tags you typed.</p>'});
this.registerField(this.fieldBusinessAreas);if(this.trialMessage!=false)this.registerField(this.trialMessage);this.registerField(this.fieldTags)},beforeShow:function(){var noDataSection=$("welcomeCandidatesSection");if(noDataSection){noDataSection.blindUp({duration:0.5,afterFinish:function(){noDataSection.remove()}});$("candidateGrid").blindDown()}this.fieldBusinessAreas.setValue($F("bizAreaFilterIds"));this.fieldTags.setValue({dropDownValue:$F("tagOperatorValue"),tagsValue:$F("tagFiltersValue")})},
createNewObject:function($super){$super();var tagFieldValues=this.fieldTags.getValue();Brainstorm.Web.Services.Ajax.UpdatePipelineCandidateFilters(this.profile.id,this.fieldBusinessAreas.getIntValues(),tagFieldValues.dropDownValue,tagFieldValues.tagsValue,this.onFiltersUpdated.bind(this),bsCommon.ajaxCallError)},onFiltersUpdated:function(domElement){var filterBoxContainer=$("filterBoxContainer");if(filterBoxContainer){filterBoxContainer.innerHTML=domElement.HTML;var afterFinishFx=this.afterFiltersUpdated;
this.closeForm({highlight:filterBoxContainer.down("div.filterBox"),afterFinish:function(){if(afterFinishFx)afterFinishFx()}})}}});
BrainstormJs.Forms.PipelineForm=Class.create(BrainstormJs.Forms.BaseForm,{fieldName:false,fieldDescription:false,fieldSubscribe:false,initialize:function($super,options){options=options||{};options.createTitle="Create a new pipeline";if(options.destroyOnClose)this.destroyOnClose=options.destroyOnClose;this.editObjectType="pipeline";this.friendlyObjectName="pipeline";$super(null,options)},createFields:function($super){this.fieldName=new BrainstormJs.Forms.Fields.TextBox({title:"Pipeline Name",required:true,
maxLength:1024});this.fieldDescription=new BrainstormJs.Forms.Fields.TextArea({title:"Description - What is the primary goal of your pipeline?",required:true,enableWysiwyg:true});this.fieldSubscribe=new BrainstormJs.Forms.Fields.CheckBox({title:"Notify me of activity on this pipeline.",startChecked:true});this.registerField(this.fieldName);this.registerField(this.fieldDescription);this.registerField(this.fieldSubscribe)},createNewObject:function($super){$super();Brainstorm.Web.Services.Ajax.CreatePipeline(this.fieldName.getValue(),
this.fieldDescription.getValue(),this.fieldSubscribe.getValue(),this.pipelineCreated.bind(this),this.handleAjaxError.bind(this))},pipelineCreated:function(jsonPipeline){bsCommon.openFormCheck=false;document.location="/Pipeline.aspx?id="+jsonPipeline.Id},beforeShow:function($super){$super();this.fieldDescription.createWysiwyg()},afterClose:function($super){$super();this.fieldDescription.destroyWysiwyg();if(this.destroyOnClose)this.container.remove()}});
BrainstormJs.Forms.PipelineStatusForm=Class.create(BrainstormJs.Forms.BaseForm,{dropDown:false,initialize:function($super,profile,options){options=options||{};options.createTitle="Edit pipeline status";options.editTitle="Edit pipeline status";$super(profile,options)},createFields:function($super){this.dropDown=new BrainstormJs.Forms.Fields.DropDownList({title:"Select Status",required:true,addBlank:true,choices:[{value:Brainstorm.Model.Enums.PipelineStatus.Active,text:"Active"},{value:Brainstorm.Model.Enums.PipelineStatus.Inactive,
text:"Inactive"}]});this.registerField(this.dropDown)},createNewObject:function($super){$super();Brainstorm.Web.Services.Ajax.UpdatePipelineStatus(this.profile.id,this.dropDown.getValue(),this.statusUpdated.bind(this),bsCommon.ajaxCallError)},statusUpdated:function(newStatus){var statusDiv=$("pipelineStatus");if(statusDiv){statusDiv.innerHTML=newStatus;this.closeForm({highlight:statusDiv})}}});
BrainstormJs.Forms.PipelineTeamMemberForm=Class.create(BrainstormJs.Forms.BaseListForm,{fieldPeople:false,options:false,objectLi:false,initialize:function($super,profile,options){options=options||{};options.createTitle="Add a team member";options.editTitle="Edit team member";options.deleteConfirmText="Are you sure you want to remove this person from the pipeline team?";this.options=options;$super(profile,options);this.editObjectType="person";this.friendlyObjectName="team member"},createFields:function($super){this.fieldPeople=
new BrainstormJs.Forms.Fields.MultiSelect.PersonSelect({title:"Full Name",required:true,help:"<p>Start typing a person's name and matches in the directory will appear.</p>",maxItems:1});this.registerField(this.fieldPeople)},createNewObject:function($super){$super();Brainstorm.Web.Services.Ajax.AddPipelineTeamMember(this.profile.id,this.fieldPeople.getValue()[0],this.newObjectCreated.bind(this),bsCommon.ajaxCallError)},saveNewOrder:function($super,profileId,serializedOrder,afterSave){Brainstorm.Web.Services.Ajax.ReorderPipelineTeamMembers(profileId,
serializedOrder,afterSave,bsCommon.ajaxCallError)},callDeleteObject:function(objectLi,objectType,personId){Brainstorm.Web.Services.Ajax.RemovePipelineTeamMember(this.profile.id,personId,this.objectDeleted.bind(this),bsCommon.ajaxCallError,objectLi)}});
BrainstormJs.Forms.RelatedTagsForm=Class.create(BrainstormJs.Forms.BaseForm,{fieldTag:false,fieldStrength:false,fieldRelatedTags:false,cloudContainer:false,initialize:function($super,profile,options){options=options||{};options.createTitle="Add a new tag";options.editTitle="Edit tag";this.cloudContainer=$("relatedTags");this.editObjectType="tag";this.friendlyObjectName="tag";$super(profile,options)},createFields:function($super){this.fieldTag=new BrainstormJs.Forms.Fields.MultiSelect.TagSelect({title:"Tag",
required:true,warning:"",maxItems:1,help:"<p>This is the original tag that you would like to specify a relation from. It is pre-filled with the tag on this page, but it can be changed to any tag.</p>"});this.fieldStrength=new BrainstormJs.Forms.Fields.DropDownList({title:"Is ...",required:true,addBlank:true,choices:[{value:100,text:"Synonymous with ..."},{value:75,text:"Very similar to ..."},{value:50,text:"Somewhat related to ..."},{value:0,text:"Not related at all to ..."}]});this.fieldRelatedTags=
new BrainstormJs.Forms.Fields.MultiSelect.TagSelect({title:"Related Tag(s)",required:true,help:"<p>These are the tags that you think are related to the above tag with the strength you specified above.</p>"});this.registerField(this.fieldTag);this.registerField(this.fieldStrength);this.registerField(this.fieldRelatedTags)},beforeShow:function($super){var tagName=$("tagName").innerHTML.trim();this.fieldTag.setValue(tagName)},createNewObject:function($super){$super();Brainstorm.Web.Services.Tagging.AddTagRelation(this.fieldTag.getValue(),
this.fieldStrength.getValue(),this.fieldRelatedTags.getValue(),this.loadTagCloud.bind(this),bsCommon.ajaxCallError)},loadTagCloud:function(tagCloud){this.cloudContainer.innerHTML=tagCloud;this.closeForm({highlight:this.cloudContainer})}});
BrainstormJs.Forms.StatusForm=Class.create(BrainstormJs.Forms.BaseForm,{fieldStatus:false,trialMessage:false,currentStatusId:false,initialize:function($super,profile,options){options=options||{};options.createTitle="Change idea status";options.editTitle="Change idea status";this.currentStatusId=$("currentIdeaStatusId");this.editObjectType="idea";this.friendlyObjectName="idea";$super(profile,options)},createFields:function($super){this.fieldStatus=new BrainstormJs.Forms.Fields.DropDownList({title:"Current Status",
required:true,choices:choices_Brainstorm_Model_Data_Ideas_IdeaStatus,selectedValue:this.currentStatusId.value});if($F("BS_TrialMode")!=false)this.trialMessage=new BrainstormJs.Forms.Fields.MessageBox({message:'<strong>To customize the choices for Status,</strong><br /><a href="/Upgrade.aspx" target="_blank">upgrade now</a> or <a href="mailto:support@intuitbrainstorm.com">contact us</a>.',hasIcon:false,cssClass:"upgradeMessage"});this.registerField(this.fieldStatus);if(this.trialMessage!=false)this.registerField(this.trialMessage)},
createNewObject:function($super){$super();Brainstorm.Web.Services.IdeaTasks.EditStatus(this.profile.id,this.fieldStatus.getValue(),this.statusUpdated.bind(this),bsCommon.ajaxCallError);this.currentStatusId.value=this.fieldStatus.getValue();this.fieldStatus.options.selectedValue=this.currentStatusId.value},statusUpdated:function(newStatus){var status=$("lblIdeaStatus");if(status){status.innerHTML=newStatus;this.closeForm({highlight:status})}}});
BrainstormJs.Forms.Fields.ChoiceGroup=Class.create(BrainstormJs.Forms.Fields.BaseField,{choices:false,boundToInput:false,choiceElements:false,displayLimit:false,initialize:function($super,options){options=options||{};this.boundToInput=options.boundToInput;var choices=options.choices;this.choiceElements=new Array;this.displayLimit=5;for(var i=0,j=choices.length;i<j;i++)this.choiceElements.push(new BrainstormJs.Controls.CustomButton({value:choices[i],fxClick:this.pickChoice.bind(this),altText:"Add as an interest"}));
options.cssClass="choiceGroup";$super(options)},render:function($super){this.container=new Element("div",{"class":"groupWrapper"});var renderLimit=this.choiceElements.length>this.displayLimit?this.displayLimit:this.choiceElements.length;for(var i=0;i<renderLimit;i++)if(!this.choiceElements[i].element)this.container.insert(this.choiceElements[i].render());return $super([this.container])},pickChoice:function(choice){if(this.boundToInput){var value=this.boundToInput.getValue();var currentValues=value==
""?new Array:this.boundToInput.getValue().split(",");currentValues.push(choice.value);this.boundToInput.setValue(currentValues.join(","))}choice.element.fade();for(var i=0,j=this.choiceElements.length;i<j;i++)if(choice==this.choiceElements[i]){this.choiceElements.splice(i,1);break}this.update()},update:function(){var renderCount=this.choiceElements.length>this.displayLimit?this.displayLimit:this.choiceElements.length;for(var i=0;i<renderCount;i++)if(!this.choiceElements[i].element){var newChoice=
this.choiceElements[i].render();newChoice.hide();this.container.insert(newChoice);newChoice.appear()}},hasValue:function(){return true},getValue:function(){return true},setValue:function(value){},clear:function(){},focus:function(){},enable:function(){this.container.removeClassName("disabledChoiceGroup")},disable:function(){this.container.addClassName("disabledChoiceGroup")}});
BrainstormJs.Forms.TagForm=Class.create(BrainstormJs.Forms.BaseForm,{fieldTags:false,cloudContainer:false,tagCategory:false,onTagsChanged:false,fieldPreamble:false,preambleText:false,activePicker:false,activeTags:false,currentTags:false,initialize:function($super,profile,tagCategory,options){options=options||{};options.createTitle=options.createTitle||"Add a new tag";options.editTitle=options.editTitle||"Edit tag";this.editObjectType="tag";this.friendlyObjectName="tag";this.tagCategory=tagCategory;
this.onTagsChanged=options.onTagsChanged||false;this.preambleText=options.preambleText||false;this.activeTags=options.activeTags||false;if(options.cloudContainer)this.cloudContainer=$(options.cloudContainer);if(!profile&&(tagCategory==Brainstorm.Model.Enums.TagCategory.SkilledAt||tagCategory==Brainstorm.Model.Enums.TagCategory.InterestedIn))profile={objectType:"Person",id:bsCommon.userId};$super(profile,options)},createFields:function($super){if(this.preambleText!=false){this.fieldPreamble=new BrainstormJs.Forms.Fields.MessageBox({message:this.preambleText,
cssClass:"preambleText"});this.registerField(this.fieldPreamble)}var subtitle=false;var title="Tags";if(this.tagCategory==Brainstorm.Model.Enums.TagCategory.SkilledAt)subtitle="(ex. cost savings, marketing, TPS reports)";else if(this.tagCategory==Brainstorm.Model.Enums.TagCategory.InterestedIn){subtitle="(separate each with a comma, i.e. <strong>new products, marketing, mobile</strong>)";title="Interests"}this.fieldTags=new BrainstormJs.Forms.Fields.MultiSelect.TagSelect({title:title,required:false,
subtitle:subtitle,warning:this.activeTags?"":false});this.registerField(this.fieldTags);if(this.activeTags!=false){this.activePicker=new BrainstormJs.Forms.Fields.ChoiceGroup({choices:this.activeTags,required:false,title:"Active Tags:",boundToInput:this.fieldTags});this.registerField(this.activePicker)}},createNewObject:function($super){$super();Brainstorm.Web.Services.Tagging.AddTagsRaw(this.profile.objectType,this.profile.id,this.tagCategory,this.fieldTags.getValue(),this.loadTagCloud.bind(this),
bsCommon.ajaxCallError)},loadTagCloud:function(tagCloud){if(this.cloudContainer){this.cloudContainer.innerHTML=tagCloud;this.closeForm({highlight:this.cloudContainer})}else this.closeForm()},startEditing:function(){this.showForm({editMode:true,afterFinish:function(){this.loadObjectValues()}.bind(this)})},loadObjectValues:function($super,container){if(this.currentTags)this.setTags(this.currentTags);else if(this.cloudContainer){var containerTags=this.cloudContainer.select("a.usertag");var numCurrentTags=
containerTags.length;var tags=new Array(numCurrentTags);for(var i=0;i<numCurrentTags;i++)tags[i]=containerTags[i].innerHTML;this.setTags(tags)}else Brainstorm.Web.Services.Tagging.GetTags(this.profile.objectType,this.profile.id,this.tagCategory,this.setTags.bind(this),bsCommon.ajaxCallError)},setTags:function(tags){this.fieldTags.setValue(tags.join(","));this.editingExisting=true;this.currentTags=tags},saveEditedObject:function(){if(this.editingExisting)Brainstorm.Web.Services.Tagging.UpdateMyTags(bsCommon.getRequestToken(),
this.profile.objectType,this.profile.id,this.tagCategory,this.fieldTags.getValue(),this.tagsSaved.bind(this),bsCommon.ajaxCallError)},tagsSaved:function(newTagCloud){this.currentTags=false;this.stopEditingObject();this.loadTagCloud(newTagCloud);if(this.onTagsChanged)this.onTagsChanged()}});
BrainstormJs.Forms.TeamMemberForm=Class.create(BrainstormJs.Forms.BaseListForm,{fieldPeople:false,fieldTags:false,fieldLead:false,objectLi:false,initialize:function($super,profile,options){options=options||{};options.createTitle="Add a team member";options.editTitle="Edit team member";$super(profile,options);this.editObjectType="person";this.friendlyObjectName="team member"},createFields:function($super){this.fieldPeople=new BrainstormJs.Forms.Fields.MultiSelect.PersonSelect({title:"Full Name",required:true,
help:"<p>Start typing a person's name and matches in the directory will appear.</p>",maxItems:1});this.fieldTags=new BrainstormJs.Forms.Fields.MultiSelect.TagSelect({title:"Team Role(s)",help:"<p>Adding role tags helps others see what this person's role is on this team. It also helps Brainstorm better organize people by skills.</p>",required:false});this.fieldLead=new BrainstormJs.Forms.Fields.CheckBox({title:"This person is the team leader",required:false,startChecked:false,hideOnAdd:true,warning:"Setting this person as the team leader will remove this role from the current leader. This person will be notified via email of their new team lead status.",
warningWhenChecked:true});this.registerField(this.fieldPeople);this.registerField(this.fieldTags);this.registerField(this.fieldLead)},createNewObject:function($super){$super();Brainstorm.Web.Services.IdeaTasks.AddTeamMember(this.profile.id,this.fieldPeople.getValue()[0],this.fieldTags.getValue(),this.newObjectCreated.bind(this),bsCommon.ajaxCallError)},loadObjectValues:function($super,objectLi){$super(objectLi);this.objectLi=objectLi;var data=objectLi.down("div.data");var icon=data.down("input.icon").value;
var name=data.down("input.name").value;var id=parseInt(data.down(".id").value,10);var tags=data.down(".tags").value;this.fieldTags.setValue(tags);this.fieldPeople.setValue([{id:id,label:name}]);this.editingExisting=true},saveEditedObject:function($super){$super();Brainstorm.Web.Services.IdeaTasks.UpdateTeamMember(this.profile.id,this.fieldPeople.getValue()[0],this.fieldLead.getValue(),this.fieldTags.getValue(),this.teamMemberSaved.bind(this),bsCommon.ajaxCallError)},teamMemberSaved:function(editedTeamMember){if(this.objectLi){var data=
this.objectLi.down(".data");data.down("input.tags").value=editedTeamMember.RoleTagData;if(editedTeamMember.IsLeader)data.up("div.editableList").select("div.editableItem div.person span.leader").each(function(icon){icon.remove()});this.objectLi=false}var personDiv=this.editObjectElement.down("div.person");var roles=personDiv.down("span.roles");if(roles)roles.innerHTML=editedTeamMember.RoleTagView;this.closeForm({highlight:personDiv})}});
BrainstormJs.Forms.Fields.CheckTextBox=Class.create(BrainstormJs.Forms.Fields.BaseField,{checkbox:false,label:false,textbox:false,textboxLabel:false,textboxTitle:false,textboxWrapper:false,maxLength:false,fxOnChange:false,fxOnChangeByKeyboard:false,initialize:function($super,options){options=options||{};options.cssClass="checkbox";this.textboxLabel=options.textboxLabel||"Text",this.maxLength=options.maxLength||100;this.fxOnChange=this.onChange.bind(this);this.fxOnChangeByKeyboard=function(e){if(e.keyCode==
Event.KEY_SPACE||e.charCode==Event.KEY_SPACE)this.fxOnChange()}.bind(this);$super(options)},render:function($super){this.checkbox=new Element("input",{"class":"checkbox","type":"checkbox","tabindex":this.tabIndex});this.checkbox.identify();if(!Prototype.Browser.IE)this.checkbox.observe("change",this.onChange.bind(this));else this.checkbox.observe("click",this.fxOnChange);this.label=(new Element("span",{"class":"label"})).update(this.title);var textboxTitle=(new Element("span")).update(this.textboxLabel);
this.textbox=new Element("input",{"type":"text","class":"textbox","tabindex":this.tabIndex,"maxlength":this.maxLength});this.textbox.identify();this.textboxWrapper=new Element("span",{"class":"checkTextBox","style":"display:none"});this.textboxWrapper.insert(textboxTitle);this.textboxWrapper.insert(this.textbox);this.label.insert(this.textboxWrapper);if(this.startChecked)this.checkbox.checked=true;return $super([this.checkbox,this.label,this.textboxWrapper])},afterRender:function(){},onChange:function(){if(this.checkbox.checked)this.textboxWrapper.appear({duration:0.5});
else this.textboxWrapper.fade({duration:0.5})},renderTitle:function($super){},hasValue:function(){return true},getValue:function(){return{checked:this.checkbox.checked,text:this.textbox.value.strip()}},setValue:function(value){this.checkbox.checked=value===true||value&&value.toString().toLowerCase()=="true"},clear:function(){if(!this.checkbox.checked)this.textboxWrapper.hide();this.checkbox.checked=false;this.textbox.value=""},beforeValidation:function(){},focus:function(){},getElement:function(){return this.checkbox},
disable:function(){this.checkbox.disabled=true},enable:function(){this.checkbox.disabled=false}});
BrainstormJs.Forms.Fields.MessageBox=Class.create(BrainstormJs.Forms.Fields.BaseField,{container:false,message:false,hasIcon:false,initialize:function($super,options){options=options||{};this.message=options.message;this.hasIcon=options.hasIcon;$super(options)},render:function($super){this.container=(new Element("div",{"class":"messageWrapper"})).update(this.message);if(this.hasIcon){this.icon=new Element("span",{"class":"icon"});this.container.insert({top:this.icon})}return $super([this.container])},
hasValue:function(){return true},getValue:function(){return true},setValue:function(value){},clear:function(){},focus:function(){},enable:function(){this.container.removeClassName("disabledMessageBox")},disable:function(){this.container.addClassName("disabledMessageBox")}});
BrainstormJs.Forms.TenantProfile.ApiAccessForm=Class.create(BrainstormJs.Forms.BaseListForm,{appName:false,appEmail:false,adminKey:false,emailKey:false,initialize:function($super,profile,options){options=options||{};options.createTitle="Add a new API key";options.editTitle="Edit existing API key";options.deleteConfirmText="Are you sure you want to remove this API key?";$super(profile,options);this.editObjectType="apiaccess";this.friendlyObjectName="item"},createFields:function($super){this.appName=
new BrainstormJs.Forms.Fields.TextBox({title:"Application Name",required:true,maxLength:127,dataSelector:".data-appName"});this.appEmail=new BrainstormJs.Forms.Fields.TextBox({title:"Email of API Developer",help:"Will be used to trasmit API credentials",required:true,maxLength:64,submitOnEnter:true,dataSelector:".data-emailContact"});this.emailKey=new BrainstormJs.Forms.Fields.CheckBox({title:"Email the API key to the developer",required:false,startChecked:true});this.adminKey=new BrainstormJs.Forms.Fields.CheckBox({title:"Make this an Admin enabled API Key. (Will allow access to administrative API endpoints)",
required:false,startChecked:false});this.registerField(this.appName);this.registerField(this.adminKey);this.registerField(this.appEmail);this.registerField(this.emailKey)},createNewObject:function($super){$super();Brainstorm.Web.Services.TenantAdmin.CreateApiKey(bsCommon.getRequestToken(),this.appName.getValue(),this.appEmail.getValue(),this.adminKey.getValue(),this.emailKey.getValue(),this.appKeyCreated.bind(this),bsCommon.ajaxCallError)},appKeyCreated:function(jsonObjectView){var newLi=this.newObjectCreated(jsonObjectView.View);
var newBizUnit=jsonObjectView.Object},loadObjectValues:function($super,objectLi){$super(objectLi);var data=objectLi.down(".data");this.appName.setValue(data.down(".appname").value);this.appEmail.setValue(data.down(".emailContact").value);this.adminKey.setValue(data.down(".admin").value)},saveEditedObject:function($super){$super();Brainstorm.Web.Services.TenantAdmin.UpdateApiKey(bsCommon.getRequestToken(),this.editObjectId,this.appName.getValue(),this.appEmail.getValue(),this.adminKey.getValue(),this.emailKey.getValue(),
this.appKeyUpdated.bind(this),bsCommon.ajaxCallError)},appKeyUpdated:function(jsonApiKey){var data=this.editObjectElement.down("div.data");data.down(".appname").value=jsonApiKey.AppName;data.down(".emailContact").value=jsonApiKey.EmailContact;data.down(".admin").value=jsonApiKey.adminKey;this.editObjectElement.down(".appname").innerHTML=jsonApiKey.AppName;this.editObjectElement.down(".emailContact").innerHTML=jsonApiKey.EmailContact;if(jsonApiKey.SuperKey)this.editObjectElement.down(".uber").show();
else this.editObjectElement.down(".uber").hide();this.closeForm({highlight:this.editObjectElement.down(".appName")})},deleteObject:function($super,objectLi){bsCommon.confirm({title:"Removal Confirmation",text:"Are you sure you would like to delete this API Key?",width:500,confirmText:"Delete",cancelText:"Cancel",onConfirm:function(context){this.onDeleteConfirmed(objectLi,context)}.bind(this)})},callDeleteObject:function(objectLi,objectType,objectId,context){Brainstorm.Web.Services.TenantAdmin.DeleteApiKey(bsCommon.getRequestToken(),
objectId,this.objectDeleted.bind(this),bsCommon.ajaxCallError,{objectLi:objectLi,deletedId:objectId})},objectDeleted:function($super,returnval,context){$super(returnval,context.objectLi)}});
BrainstormJs.Forms.TenantProfile.BusinessUnitForm=Class.create(BrainstormJs.Forms.BaseListForm,{fieldName:false,fieldShortName:false,initialize:function($super,profile,options){options=options||{};options.createTitle="Add a new item";options.editTitle="Edit existing item";options.deleteConfirmText="Are you sure you want to remove this item?";$super(profile,options);this.editObjectType="ideabusinessunit";this.friendlyObjectName="item"},createFields:function($super){this.fieldName=new BrainstormJs.Forms.Fields.TextBox({title:"Name",
required:true,maxLength:127,dataSelector:".data-Name"});this.fieldShortName=new BrainstormJs.Forms.Fields.TextBox({title:"Short Name",required:true,maxLength:64,submitOnEnter:true,dataSelector:".data-ShortName"});this.registerField(this.fieldName);this.registerField(this.fieldShortName)},createNewObject:function($super){$super();Brainstorm.Web.Services.TenantAdmin.CreateBusinessUnit(this.fieldName.getValue(),this.fieldShortName.getValue(),this.bizUnitCreated.bind(this),bsCommon.ajaxCallError)},bizUnitCreated:function(jsonObjectView){var newLi=
this.newObjectCreated(jsonObjectView.View);var newBizUnit=jsonObjectView.Object;choices_Brainstorm_Model_Data_Ideas_IdeaBusinessUnit.push({value:newBizUnit.Id,text:newBizUnit.Name})},loadObjectValues:function($super,objectLi){$super(objectLi);var data=objectLi.down(".data");this.fieldName.setValue(data.down(".name").value);this.fieldShortName.setValue(data.down(".shortName").value)},saveEditedObject:function($super){$super();Brainstorm.Web.Services.TenantAdmin.UpdateBusinessUnit(this.editObjectId,
this.fieldName.getValue(),this.fieldShortName.getValue(),this.bizUnitSaved.bind(this),bsCommon.ajaxCallError)},bizUnitSaved:function(jsonBusinessUnit){var data=this.editObjectElement.down("div.data");data.down(".name").value=jsonBusinessUnit.Name;data.down(".shortName").value=jsonBusinessUnit.ShortName;this.editObjectElement.down(".bizUnitName").innerHTML='<span class="icon"></span>'+jsonBusinessUnit.Name;this.closeForm({highlight:this.editObjectElement.down(".bizUnitName")})},saveNewOrder:function($super,
profileId,serializedOrder,afterSave){Brainstorm.Web.Services.TenantAdmin.ReorderBusinessUnits(serializedOrder,afterSave,bsCommon.ajaxCallError)},deleteObject:function($super,objectLi){bsCommon.promptDropDown({title:"Removal Confirmation",text:"Are you sure you would like to delete this "+$F("BS_Config_AreaName").toLowerCase()+"? <br/>If so, please select another "+$F("BS_Config_AreaName").toLowerCase()+" to migrate ideas to:",width:500,confirmText:"Migrate and Delete",cancelText:"Cancel",ignoreChoice:parseInt(objectLi.id.split("_")[1],
10),choices:choices_Brainstorm_Model_Data_Ideas_IdeaBusinessUnit,onConfirm:function(context){this.onDeleteConfirmed(objectLi,context)}.bind(this)})},callDeleteObject:function(objectLi,objectType,objectId,context){Brainstorm.Web.Services.TenantAdmin.ArchiveBusinessUnit(objectId,context.selectedValue,this.objectDeleted.bind(this),bsCommon.ajaxCallError,{objectLi:objectLi,deletedId:objectId})},objectDeleted:function($super,returnval,context){$super(returnval,context.objectLi);choices_Brainstorm_Model_Data_Ideas_IdeaBusinessUnit=
bsCommon.removeDropDownChoice(choices_Brainstorm_Model_Data_Ideas_IdeaBusinessUnit,context.deletedId)}});
BrainstormJs.Forms.TenantProfile.IdeaStageForm=Class.create(BrainstormJs.Forms.BaseListForm,{fieldName:false,fieldShortName:false,initialize:function($super,profile,options){options=options||{};options.createTitle="Add a new idea stage";options.editTitle="Edit idea stage";options.deleteConfirmText="Are you sure you want to remove this idea stage?";$super(profile,options);this.editObjectType="ideastatus";this.friendlyObjectName="idea stage"},createFields:function($super){this.fieldName=new BrainstormJs.Forms.Fields.TextBox({title:"Name",
required:true,maxLength:1E3,dataSelector:".data-Name"});this.fieldShortName=new BrainstormJs.Forms.Fields.TextBox({title:"Short Name",required:true,maxLength:64,submitOnEnter:true,dataSelector:".data-ShortName"});this.registerField(this.fieldName);this.registerField(this.fieldShortName)},createNewObject:function($super){$super();Brainstorm.Web.Services.TenantAdmin.CreateIdeaStage(this.fieldName.getValue(),this.fieldShortName.getValue(),this.stageCreated.bind(this),bsCommon.ajaxCallError)},stageCreated:function(jsonObjectView){var newLi=
this.newObjectCreated(jsonObjectView.View);var newStage=jsonObjectView.Object;choices_Brainstorm_Model_Data_Ideas_IdeaStatus.push({value:newStage.Id,text:newStage.Name})},loadObjectValues:function($super,objectLi){$super(objectLi);var data=objectLi.down(".data");this.fieldName.setValue(data.down(".name").value);this.fieldShortName.setValue(data.down(".shortName").value)},saveEditedObject:function($super){$super();Brainstorm.Web.Services.TenantAdmin.UpdateIdeaStage(this.editObjectId,this.fieldName.getValue(),
this.fieldShortName.getValue(),this.stageSaved.bind(this),bsCommon.ajaxCallError)},stageSaved:function(jsonStage){var data=this.editObjectElement.down("div.data");data.down(".name").value=jsonStage.Name;data.down(".shortName").value=jsonStage.ShortName;this.editObjectElement.down(".stageName").innerHTML='<span class="icon"></span>'+jsonStage.Name;this.closeForm({highlight:this.editObjectElement.down(".stageName")})},saveNewOrder:function($super,profileId,serializedOrder,afterSave){Brainstorm.Web.Services.TenantAdmin.ReorderIdeaStages(serializedOrder,
afterSave,bsCommon.ajaxCallError)},deleteObject:function($super,objectLi){bsCommon.promptDropDown({title:"Removal Confirmation",text:"Are you sure you would like to delete this idea stage? <br/>If so, please select the stage to migrate ideas to:",width:500,confirmText:"Migrate and Delete",cancelText:"Cancel",ignoreChoice:parseInt(objectLi.id.split("_")[1],10),choices:choices_Brainstorm_Model_Data_Ideas_IdeaStatus,onConfirm:function(context){this.onDeleteConfirmed(objectLi,context)}.bind(this)})},
callDeleteObject:function(objectLi,objectType,objectId,context){Brainstorm.Web.Services.TenantAdmin.ArchiveIdeaStage(objectId,context.selectedValue,this.objectDeleted.bind(this),bsCommon.ajaxCallError,{objectLi:objectLi,deletedId:objectId})},objectDeleted:function($super,returnval,context){$super(returnval,context.objectLi);choices_Brainstorm_Model_Data_Ideas_IdeaStatus=bsCommon.removeDropDownChoice(choices_Brainstorm_Model_Data_Ideas_IdeaStatus,context.deletedId)}});
BrainstormJs.Forms.TenantProfile.TagConsolidationForm=Class.create(BrainstormJs.Forms.BaseForm,{similarTags:false,favoredTag:false,fieldConsolidateTo:false,fieldTags:false,fieldWarning:false,fnAfterClose:false,initialize:function($super,profile,options){options=options||{};options.createTitle="Consolidate Tag";options.editTitle="Consolidate Tag";if(options.afterClose)this.fnAfterClose=options.afterClose;this.favoredTag=options.favoredTag;this.similarTags=new Array;for(var i=0;i<options.similarTags.length;i++){var tag=
options.similarTags[i].innerHTML;this.similarTags.push({value:tag,text:tag})}$super(profile,options)},createFields:function($super){this.registerField(new BrainstormJs.Forms.Fields.MessageBox({message:"Change these tags:"}));this.fieldTags=new Array;for(var i=0;i<this.similarTags.length;i++){var similarTermBox=new BrainstormJs.Forms.Fields.CheckBox({title:this.similarTags[i].text,startChecked:false});similarTermBox.addObserver(this.updateWarning.bind(this));this.fieldTags.push(similarTermBox);this.registerField(similarTermBox)}this.fieldConsolidateTo=
new BrainstormJs.Forms.Fields.DropDownList({title:"To:",required:true,addBlank:false,choices:this.similarTags,defaultValue:this.favoredTag});this.registerField(this.fieldConsolidateTo);this.fieldWarning=new BrainstormJs.Forms.Fields.MessageBox({message:"This action cannot be undone",hasIcon:true,cssClass:"messagebox"});this.registerField(this.fieldWarning)},updateWarning:function(){var tagNamesToChange=this.getSelectedTags();this.fieldWarning.message=tagNamesToChange.join(", ")},getSelectedTags:function(){var tagNamesToChange=
new Array;var numOptions=this.fieldTags.length;if(numOptions>1)for(var i=0;i<this.fieldTags.length;i++)if(this.fieldTags[i].getValue())tagNamesToChange.push(this.fieldTags[i].title);return tagNamesToChange},createNewObject:function($super){var tagNamesToChange=this.getSelectedTags();var consolidateTo=this.fieldConsolidateTo.getValue();if(tagNamesToChange.length==0){this.closeForm();return}bsCommon.confirm({title:"Are you sure?",text:'The tags "'+tagNamesToChange.join(", ")+'" will be changed to "'+
consolidateTo+'" &ndash; This action cannot be undone.',width:450,confirmText:"Yes, consolidate away!",cancelText:"No. Don't do it yet.",onConfirm:function(){this.doTagConsolidation(tagNamesToChange,consolidateTo)}.bind(this),onCancel:this.clearSubmissionInProgress.bind(this)})},doTagConsolidation:function(tagNamesToChange,consolidateTo){Brainstorm.Web.Services.TenantAdmin.ConsolidateTags(tagNamesToChange,consolidateTo,this.afterConsolidate.bind(this),bsCommon.ajaxCallError)},afterConsolidate:function(message){bsCommon.showMessage(message);
var parseResults=message.match(/([\d]+) tags/);var numConsolidated=parseResults.length==2?parseInt(parseResults[1]):0;this.updateRecommendationElem(this.parentContainer,numConsolidated);new Effect.Highlight(this.parentContainer);this.closeForm()},updateRecommendationElem:function(recElem,numChanged){try{var tagNamesToChange=this.getSelectedTags();var consolidateTo=this.fieldConsolidateTo.getValue();var selfConsolidation=false;var similarTermElems=recElem.select(".similarTerm");var consolidateToCountEl=
null;for(var j=0;j<similarTermElems.length;j++){var similarElem=similarTermElems[j];for(var i=0,n=tagNamesToChange.length;i<n;i++)if(similarElem.innerHTML!=consolidateTo){if(similarElem.innerHTML==tagNamesToChange[i]){var countElem=similarElem.next();similarElem.fade();countElem.fade();var possibleCommaElem=countElem.next();if(!possibleCommaElem||possibleCommaElem.innerHTML.indexOf(",")!=0)possibleCommaElem=similarElem.previous();if(possibleCommaElem&&possibleCommaElem.innerHTML.indexOf(",")==0)possibleCommaElem.fade()}}else{if(consolidateToCountEl==
null)consolidateToCountEl=similarElem.next();if(similarElem.innerHTML==tagNamesToChange[i])selfConsolidation=true}}var oldCount=parseInt(consolidateToCountEl.innerHTML.match(/[\d]+/)[0],10);var newCount=selfConsolidation?numChanged:oldCount+numChanged;consolidateToCountEl.update("("+newCount+")")}catch(exception){recElem.update(numChanged+" have been consolidated.  Refresh to update.")}},afterClose:function(){if(this.fnAfterClose)this.fnAfterClose()}});
BrainstormJs.Forms.TenantProfile.TenantAdminsForm=Class.create(BrainstormJs.Forms.BaseListForm,{fieldPeople:false,objectLi:false,objectType:"person",objectId:false,objectProperty:false,initialize:function($super,profile,options){options=options||{};options.createTitle="Add a network "+options.objectName;$super(profile,options);this.editObjectType="administrator";this.friendlyObjectName=options.objectName;this.objectProperty=options.property},createFields:function($super){this.fieldPeople=new BrainstormJs.Forms.Fields.MultiSelect.PersonSelect({title:"Full Name",
required:true,help:"<p>Start typing a person's name and matches in the directory will appear.</p>",maxItems:10});this.registerField(this.fieldPeople)},createNewObject:function($super){$super();Brainstorm.Web.Services.TenantAdmin.ToggleAdminsFlag(bsCommon.getRequestToken(),this.fieldPeople.getValue(),this.objectProperty,this.newObjectCreated.bind(this),bsCommon.ajaxCallError)},loadObjectValues:function($super,objectLi){$super(objectLi);this.objectLi=objectLi;var data=objectLi.down("div.data");var isLeader=
data.down("input.isLeader").value;var id=parseInt(data.down(".id").value,10);this.objectId=id;this.editingExisting=true},saveEditedObject:function($super){$super()},deleteObject:function($super,objectLi){bsCommon.confirm({title:"Removal Confirmation",text:"Are you sure you would like to remove this "+this.friendlyObjectName+"?",width:500,confirmText:"Delete",cancelText:"Cancel",onConfirm:function(context){this.onDeleteConfirmed(objectLi,context)}.bind(this)})},callDeleteObject:function(objectLi,objectType,
objectId,context){Brainstorm.Web.Services.TenantAdmin.ToggleAdminFlag(bsCommon.getRequestToken(),this.objectType,objectId,this.objectProperty,this.objectDeleted.bind(this),bsCommon.ajaxCallError,{objectLi:objectLi,deletedId:objectId})},objectDeleted:function($super,returnval,context){$super(returnval,context.objectLi)}});BrainstormJs.Modules.BaseModule=Class.create({options:false,profile:false,initialize:function(options){this.options=options||{};this.profile=this.options.profile||false}});
BrainstormJs.Modules.ChallengeProfile.ChallengeSnapshotModule=Class.create(BrainstormJs.Modules.BaseModule,{datesForm:false,initialize:function($super,options){$super(options);var linkEditStatus=$("linkEditStatus");if(linkEditStatus){this.datesForm=new BrainstormJs.Forms.ChallengeDatesForm(this.profile,{parentContainer:"formEditDates-container",openLinks:[linkEditStatus],bindOpenLinks:false});linkEditStatus.observe("click",function(e){this.startEditingDates();e.stop()}.bind(this))}var contextualHelpItem=
$("shareHelpMessage");var relatedContextualHelpItem=$("customizeHelpMessage");if(!relatedContextualHelpItem&&contextualHelpItem)contextualHelpItem.blindDown()},startEditingDates:function(){this.datesForm.startEditing($("challengeStatus"))}});
BrainstormJs.Modules.ChallengeProfile.ChallengeTagsModule=Class.create(BrainstormJs.Modules.BaseModule,{tagForm:false,initialize:function($super,options){$super(options);var editTagLink=$("linkEditTags");if(editTagLink!=null){this.tagForm=new BrainstormJs.Forms.TagForm(this.profile,Brainstorm.Model.Enums.TagCategory.Generic,{parentContainer:$("tagForm-container"),cloudContainer:"challengeGenericTagCloud",openLinks:[editTagLink],bindOpenLinks:false,editTitle:"Add/edit idea tags"});editTagLink.observe("click",
function(e){this.tagForm.startEditing();e.stop()}.bind(this))}}});BrainstormJs.Modules.ChallengeProfile.ChallengeTeamModule=Class.create(BrainstormJs.Modules.BaseModule,{teamMemberForm:false,initialize:function($super,options){$super(options);this.teamMemberForm=new BrainstormJs.Forms.ChallengeTeamMemberForm(this.profile,{list:"teamMembers",parentContainer:"teamMemberForm-container",emptyMessage:"No team members added yet."})}});
BrainstormJs.Modules.Idea.IdeaSnapshotModule=Class.create(BrainstormJs.Modules.BaseModule,{statusForm:false,bizUnitForm:false,imStuckForm:false,initialize:function($super,options){$super(options);var linkEditStatus=$("linkEditStatus");if(linkEditStatus)this.statusForm=new BrainstormJs.Forms.StatusForm(this.profile,{parentContainer:"formEditStatus-container",openLinks:[linkEditStatus]});var linkEditUnit=$("linkEditBusinessUnit");if(linkEditUnit)this.bizUnitForm=new BrainstormJs.Forms.BusinessUnitForm(this.profile,
{parentContainer:"formEditUnit-container",openLinks:[linkEditUnit]});var linkMakeIdeaStuck=$("linkMakeIdeaStuck");if(linkMakeIdeaStuck)this.imStuckForm=new BrainstormJs.Forms.ImStuckForm(this.profile,{parentContainer:"stuckIdeaForm-container",openLinks:[linkMakeIdeaStuck]});var linkMakeIdeaUnstuck=$("linkMakeIdeaUnstuck");if(linkMakeIdeaUnstuck)linkMakeIdeaUnstuck.observe("click",function(e){e.stop();bsCommon.confirm({title:"Removal Confirmation",text:"Are you sure you would like to make this idea NOT stuck?",
width:450,confirmText:"Yes, I'm NOT stuck anymore.",cancelText:"No wait - abort, abort!",onConfirm:this.commitUnstuck.bind(this)})}.bind(this));var addToPipelineLink=$("linkJoinPipeline");if(addToPipelineLink)var addToPipelineForm=new BrainstormJs.Forms.AddToPipelineForm(this.profile,{openLinks:[addToPipelineLink]});var featureIdeaLink=$("linkFeatureIdea");if(featureIdeaLink)var featureIdeaForm=new BrainstormJs.Forms.FeatureIdeaForm(this.profile,{openLinks:[featureIdeaLink]})},commitUnstuck:function(){Brainstorm.Web.Services.Ajax.UpdateIdeaStuckStatus(this.profile.id,
false,"",this.onUnstuck.bind(this),bsCommon.ajaxCallError)},onUnstuck:function(){Effect.BlindUp("stuckMessageContainer",{duration:0.5,afterFinish:function(){var ideaStuckMessage=$("ideaStuckMessage");var ideaStuckLink=$("linkMakeIdeaStuck");if(ideaStuckLink){ideaStuckMessage.innerHTML="";ideaStuckLink.blindDown({duration:0.5})}else{var stuckSection=ideaStuckMessage.up("div.stuckSection");if(stuckSection)stuckSection.blindUp({duration:0.5})}}})}});
BrainstormJs.Modules.Idea.IdeaTagsModule=Class.create(BrainstormJs.Modules.BaseModule,{tagForm:false,initialize:function($super,options){$super(options);var editTagLink=$("linkEditTags");if(editTagLink){this.tagForm=new BrainstormJs.Forms.TagForm(this.profile,Brainstorm.Model.Enums.TagCategory.Generic,{parentContainer:$("tagForm-container"),cloudContainer:"ideaGenericTagCloud",openLinks:[editTagLink],bindOpenLinks:false,onTagsChanged:this.updateRelatedIdeas.bind(this),editTitle:"Add/edit idea tags"});
editTagLink.observe("click",function(e){this.tagForm.startEditing();e.stop()}.bind(this))}},updateRelatedIdeas:function(){Brainstorm.Web.Services.IdeaTasks.GetRelatedIdeasContent(this.profile.id,this.relatedIdeasLoaded.bind(this),bsCommon.ajaxCallError)},relatedIdeasLoaded:function(domElement){var relatedIdeas=$("relatedIdeas");relatedIdeas.innerHTML=domElement.HTML;new Effect.Highlight(relatedIdeas);new BrainstormJs.Controls.TabPane(relatedIdeas.down("div.tabPane"))}});
BrainstormJs.Modules.Idea.IdeaTeamModule=Class.create(BrainstormJs.Modules.BaseModule,{teamMemberForm:false,joinTeamForm:false,classifiedForm:false,teamRequests:false,initialize:function($super,options){$super(options);this.teamMemberForm=new BrainstormJs.Forms.TeamMemberForm(this.profile,{list:"teamMembers",parentContainer:"teamMemberForm-container",emptyMessage:"No team members added yet."});var joinTeamLink=$("linkJoinTeam");if(joinTeamLink)this.joinTeamForm=new BrainstormJs.Forms.JoinTeamForm(this.profile,
{parentContainer:$("joinTeamForm-container"),openLinks:[joinTeamLink]});this.classifiedForm=new BrainstormJs.Forms.ClassifiedForm(this.profile,{list:"classifieds",parentContainer:$("classifiedForm-container")});this.wireTeamRequestActions()},wireTeamRequestActions:function(){this.teamRequests=$("teamRequests");if(this.teamRequests){var fxApprove=function(e){this.approveRequest(e.element());e.stop()}.bindAsEventListener(this);var fxStartDeny=function(e){this.startDenyRequest(e.element());e.stop()}.bindAsEventListener(this);
var requestDivs=this.teamRequests.select("div.teamRequest");for(var i=0;i<requestDivs.length;i++){var request=requestDivs[i];var buttons=request.down("div.buttons");var linkApprove=buttons.down("a.approve");var linkDeny=buttons.down("a.deny");linkApprove.observe("click",fxApprove);linkDeny.observe("click",fxStartDeny)}}},approveRequest:function(linkClicked){var request=this.getRequestInfo(linkClicked);Brainstorm.Web.Services.IdeaTasks.UpdateTeamJoinRequest(request.id,Brainstorm.Model.Enums.TeamMemberStatus.Approved,
this.completeApproval.bind(this),bsCommon.ajaxCallError,request)},completeApproval:function(domElement,request){this.teamMemberForm.newObjectCreated(domElement);this.removeRequest(request)},startDenyRequest:function(linkClicked){var request=this.getRequestInfo(linkClicked);bsCommon.confirm({title:"Team Request",text:"Are you sure you want to deny "+request.name+"'s request to join this team?",width:450,confirmText:"Yes, but thanks for asking!",cancelText:"Nope, I changed my mind",onConfirm:function(){this.commitDenyRequest(linkClicked,
request)}.bind(this)})},commitDenyRequest:function(linkClicked,request){Brainstorm.Web.Services.IdeaTasks.UpdateTeamJoinRequest(request.id,Brainstorm.Model.Enums.TeamMemberStatus.Denied,function(){this.removeRequest(request)}.bind(this),bsCommon.ajaxCallError)},removeRequest:function(request){var requestDiv=request.link.up("div.teamRequest");var teamRequests=this.teamRequests;var oneItemLeft=teamRequests.select("div.teamRequest").length==1;var itemToRemove=oneItemLeft?teamRequests:requestDiv;Effect.BlindUp(itemToRemove,
{duration:0.5,afterFinish:function(){itemToRemove.remove()}})},getRequestInfo:function(linkClicked){var parts=linkClicked.rel.split(":");var requestId=parseInt(parts[0],10);var requestorName=parts.length>1?parts[1]:false;return{id:requestId,name:requestorName,link:linkClicked}}});
BrainstormJs.Modules.Person.AccessTokenForm=Class.create(BrainstormJs.Forms.BaseListForm,{appName:false,initialize:function($super,profile,options){options=options||{};options.createTitle="Add a new API key";options.editTitle="Edit existing API key";options.deleteConfirmText="Are you sure you want to remove this API key?";$super(profile,options);this.editObjectType="apiaccess";this.friendlyObjectName="item"},createFields:function($super){this.appName=new BrainstormJs.Forms.Fields.TextBox({title:"Application Name",
required:true,maxLength:127,dataSelector:".data-appName"});this.appEmail=new BrainstormJs.Forms.Fields.TextBox({title:"Email of API Developer",help:"Will be used to trasmit API credentials",required:true,maxLength:64,submitOnEnter:true,dataSelector:".data-emailContact"});this.emailKey=new BrainstormJs.Forms.Fields.CheckBox({title:"Do you want the API key to be emailed to the developer?",required:false,startChecked:true});this.adminKey=new BrainstormJs.Forms.Fields.CheckBox({title:"Is this an admin API Key? (Will allow access to administrative API endpoints)",
required:false,startChecked:false});this.registerField(this.appName);this.registerField(this.adminKey);this.registerField(this.appEmail);this.registerField(this.emailKey)},createNewObject:function($super){$super();Brainstorm.Web.Services.TenantAdmin.CreateApiKey(bsCommon.getRequestToken(),this.appName.getValue(),this.appEmail.getValue(),this.adminKey.getValue(),this.emailKey.getValue(),this.appKeyCreated.bind(this),bsCommon.ajaxCallError)},appKeyCreated:function(jsonObjectView){var newLi=this.newObjectCreated(jsonObjectView.View);
var newBizUnit=jsonObjectView.Object},loadObjectValues:function($super,objectLi){$super(objectLi);var data=objectLi.down(".data");this.appName.setValue(data.down(".appname").value);this.appEmail.setValue(data.down(".emailContact").value);this.adminKey.setValue(data.down(".admin").value)},saveEditedObject:function($super){$super();Brainstorm.Web.Services.TenantAdmin.UpdateApiKey(bsCommon.getRequestToken(),this.editObjectId,this.appName.getValue(),this.appEmail.getValue(),this.adminKey.getValue(),this.emailKey.getValue(),
this.appKeyUpdated.bind(this),bsCommon.ajaxCallError)},appKeyUpdated:function(jsonApiKey){var data=this.editObjectElement.down("div.data");data.down(".appname").value=jsonApiKey.AppName;data.down(".emailContact").value=jsonApiKey.EmailContact;data.down(".admin").value=jsonApiKey.adminKey;this.editObjectElement.down(".appname").innerHTML=jsonApiKey.AppName;this.editObjectElement.down(".emailContact").innerHTML=jsonApiKey.EmailContact;if(jsonApiKey.SuperKey)this.editObjectElement.down(".uber").show();
else this.editObjectElement.down(".uber").hide();this.closeForm({highlight:this.editObjectElement.down(".appName")})},deleteObject:function($super,objectLi){bsCommon.confirm({title:"Removal Confirmation",text:"Are you sure you would like to delete this API Key?",width:500,confirmText:"Delete",cancelText:"Cancel",onConfirm:function(context){this.onDeleteConfirmed(objectLi,context)}.bind(this)})},callDeleteObject:function(objectLi,objectType,objectId,context){Brainstorm.Web.Services.TenantAdmin.DeleteApiKey(bsCommon.getRequestToken(),
objectId,this.objectDeleted.bind(this),bsCommon.ajaxCallError,{objectLi:objectLi,deletedId:objectId})},objectDeleted:function($super,returnval,context){$super(returnval,context.objectLi)}});
BrainstormJs.Modules.Person.PersonProfileImage=Class.create({image:false,originalImage:false,defaultImage:false,changeText:false,imageDiv:false,i:0,links:false,editOverlay:false,initialize:function(options){this.image=options.image;this.imageDiv=$$(".profilePhoto")[0];this.formContainer=$("photoFormContainer");this.imageUploadForm=false;this.originalImage=this.image.src;if(this.originalImage.indexOf("photo_none")!=-1){this.defaultImage=true;this.editOverlay=this.imageDiv.select(".addBanner")[0]}if(!this.defaultImage||
this.editOverlay===undefined)this.editOverlay=this.imageDiv.select(".editBanner")[0];if(this.defaultImage){this.image.addClassName("active");this.editOverlay.show()}this.image.observe("mouseenter",function(e){this.showChange(e.element())}.bind(this));this.image.observe("mouseleave",this.onMouseLeave.bind(this));this.editOverlay.observe("mouseleave",this.onMouseLeave.bind(this));this.image.observe("click",this.onClick.bind(this));this.editOverlay.observe("click",this.onClick.bind(this))},onClick:function(e){this.showForm(e.element(),
this.changeText);e.stop()},onMouseLeave:function(e){if(!e)var e=window.event;var relTarg=$(e.relatedTarget||e.toElement);if(relTarg!=null&&!relTarg.descendantOf(this.imageDiv))this.hideChange(e.element())},showForm:function(linkToActivate,linkToDeactivate){if(this.image.hasClassName("displayed")||linkToActivate.hasClassName("activeTabLink")||linkToActivate.hasClassName("inactiveTabLink"));else{this.image.addClassName("active");this.image.addClassName("displayed");this.imageUploadForm=new BrainstormJs.Forms.ImageUploadForm2(this,
this.image,{parentContainer:this.formContainer,destroyOnClose:true,afterClose:this.afterHide.bind(this),scrollToBottom:false});this.formContainer.show();this.imageUploadForm.showForm({editMode:false})}},afterHide:function(links){this.formContainer.hide();this.image.removeClassName("active");this.image.removeClassName("displayed");this.hideChange(this.image);new Effect.Highlight($$(".profilePhoto")[0])},showChange:function(elm){this.editOverlay.show()},hideChange:function(elm){if(!this.image.hasClassName("active"))this.editOverlay.hide()}});
BrainstormJs.Modules.Person.PersonSnapshotModule=Class.create(BrainstormJs.Modules.BaseModule,{skillTagForm:false,interestTagForm:false,initialize:function($super,options){$super(options);var linkEditSkills=$("linkEditSkills");this.skillTagForm=new BrainstormJs.Forms.TagForm(this.profile,Brainstorm.Model.Enums.TagCategory.SkilledAt,{parentContainer:$("skillTagForm-container"),cloudContainer:"skillTagCloud",openLinks:[linkEditSkills],bindOpenLinks:false,editTitle:"Add/edit skills"});linkEditSkills.observe("click",
function(e){this.skillTagForm.startEditing();e.stop()}.bind(this));var editInterestsLink=$("linkEditInterests");if(editInterestsLink){this.interestTagForm=new BrainstormJs.Forms.TagForm(this.profile,Brainstorm.Model.Enums.TagCategory.InterestedIn,{parentContainer:$("interestTagForm-container"),cloudContainer:"interestTagCloud",openLinks:[editInterestsLink],bindOpenLinks:false,editTitle:"Add/edit interests"});editInterestsLink.observe("click",function(e){this.interestTagForm.startEditing();e.stop()}.bind(this))}}});
BrainstormJs.Modules.PipelineProfile.PipelineSnapshotModule=Class.create(BrainstormJs.Modules.BaseModule,{initialize:function($super,options){$super(options);var linkEditStatus=$("linkEditStatus");if(linkEditStatus)var statusForm=new BrainstormJs.Forms.PipelineStatusForm(this.profile,{parentContainer:"formEditStatus-container",openLinks:[linkEditStatus]})}});
BrainstormJs.Modules.PipelineProfile.PipelineTeamModule=Class.create(BrainstormJs.Modules.BaseModule,{teamMemberForm:false,initialize:function($super,options){$super(options);this.teamMemberForm=new BrainstormJs.Forms.PipelineTeamMemberForm(this.profile,{list:"teamMembers",parentContainer:"teamMemberForm-container",emptyMessage:"No team members added yet."})}});
BrainstormJs.Modules.Tag.RelatedTagsModule=Class.create(BrainstormJs.Modules.BaseModule,{initialize:function($super,options){$super(options);this.form=new BrainstormJs.Forms.RelatedTagsForm(this.profile,{parentContainer:$("relatedTagFormContainer"),parentModule:this,openLinks:["linkAddRelatedTag"]})}});
BrainstormJs.Pages.ChallengesPage=Class.create({challengeForm:false,challengesGrid:false,initialize:function(){if($("challengesDisabled"))return;if($("linkCreateChallenge"))this.challengeForm=new BrainstormJs.Forms.ChallengeForm({parentContainer:$("challengeFormContainer"),openLinks:["linkCreateChallenge"],appearOpenLink:true});else this.challengeRequestForm=new BrainstormJs.Forms.AdminRequestForm({requestType:Brainstorm.Model.Enums.AdminRequestType.ChallengeCreation,parentContainer:$("challengeFormContainer"),
openLinks:["linkRequestChallenge"],appearOpenLink:true});this.challengesGrid=new BrainstormJs.Controls.Grid.ChallengeGrid("challengesGrid")}});BrainstormPages.register(BrainstormJs.Pages.ChallengesPage,"/Challenges.aspx");
BrainstormJs.Pages.DashboardPage=Class.create({lazyLists:{},initialize:function(){var showhidelinks=$("dashboardDataSection").select(".listToggle");var dashboardPage=this;this.lazyLists=new Object;for(var i=0;i<showhidelinks.length;i++){var showhidelink=showhidelinks[i];if(showhidelink.rel){var containerElem=$(showhidelink.rel);if(containerElem)if(containerElem.hasClassName("ajaxContentPane"))showhidelink.observe("click",function(event){this.toggleLazyLoadedList(event.target.rel)}.bind(this));else showhidelink.observe("click",
function(event){this.toggle()}.bind(containerElem))}}},toggleLazyLoadedList:function(listId){var lazyListElem=$(listId);lazyListElem.toggle();if(this.lazyLists[listId]==null){var ajaxPane=new BrainstormJs.Controls.AjaxContentPane(lazyListElem);this.lazyLists[listId]=ajaxPane;ajaxPane.startLoading({fadeTransition:true,dataMethod:function(){if($(listId+"_ideaIds"))Brainstorm.Web.Services.Ajax.GetIdeaLinks($F(listId+"_ideaIds").split(","),function(content){ajaxPane.insertContent(content);ajaxPane.showContent()},
function(){ajaxPane.insertContent("<div class='error'>Oops! There was a problem loading these ideas. Please try again later.</div>");ajaxPane.showContent()});else if($(listId+"_contentId"))Brainstorm.Web.Services.Ajax.GetTabPaneContent($F(listId+"_contentId"),function(content){ajaxPane.insertContent(content);ajaxPane.showContent()},function(){ajaxPane.insertContent("Oops! There was a problem loading these ideas. Please try again later.");ajaxPane.showContent()})}})}}});
BrainstormPages.register(BrainstormJs.Pages.DashboardPage,["/","/Dashboard.aspx"]);
BrainstormJs.Pages.HomePage=Class.create({ideaForm:false,byInterestTagUpdater:false,subscribables:false,newsEditor:false,inviteOthersForm:false,successStoryActivityFeed:false,initialize:function(){this.ideaForm=new BrainstormJs.Forms.IdeaForm({parentContainer:$("homeAddIdeaFormContainer"),destroyOnClose:false,afterClose:this.afterFormClose.bind(this),openLinks:["ctaLink"],bindOpenLinks:true});this.inviteOthersForm=new BrainstormJs.Forms.InviteOthersForm({parentContainer:$("inviteOthersFormContainer"),
destroyOnClose:false,openLinks:["inviteOthersLink"],bindOpenLinks:true});var excitingIdeasTabs=$("excitingIdeasTabs");if(excitingIdeasTabs!=null)var ideasModeTabs=new BrainstormJs.Controls.TabPane(excitingIdeasTabs,{fxAfterAjaxLoad:function(tabContent){if(tabContent.identify()=="byInterests"){this.byInterestTagUpdater=new BrainstormJs.Controls.TagUpdater({profile:{objectType:"Person",id:bsCommon.userId},sectionId:"byInterestTagUpdater",tagCategory:Brainstorm.Model.Enums.TagCategory.InterestedIn,contentFetchMethod:Brainstorm.Web.Services.Ajax.LoadDiscoverIdeas,
editTitle:"Discover ideas related to your interests",preambleText:"Provide the topics you are most interested in, and Brainstorm will point you to the ideas and activity that you care about most!",onTagFormClose:function(){if(!$("byInterestTagUpdateHeaders").visible())$("byInterestTagUpdateHeaders").appear()}});var noInterests=this.byInterestTagUpdater.container.down(".noInterests");if(noInterests){this.byInterestTagUpdater.container.down(".refreshArea").hide();$("byInterestTagUpdateHeaders").hide();
this.byInterestTagUpdater.startUpdate();this.byInterestTagUpdater.tagForm.cancelButton.hide();BrainstormForms.openForms--}}}.bind(this)});else if($("noIdeasAddLink")!=null)$("noIdeasAddLink").observe("click",function(e){this.ideaForm.showForm();e.stop()}.bind(this));var feedTabs=new BrainstormJs.Controls.TabPane($("feedTabsContainer"),{fxAfterAjaxLoad:function(tabContent){bsCommon.wireActivityFeeds(tabContent);if($("introAddIdeaLink")!=null){$("introAddIdeaLink").observe("click",function(e){this.ideaForm.showForm();
e.stop()}.bind(this));$("introInvitingOthers").observe("click",function(e){this.inviteOthersForm.showForm();e.stop()}.bind(this))}}.bind(this)});this.initSubscribables();var newsModule=$("homeNewsModule");if(newsModule!=null){var editableNews=$("homeNewsModule").down("div.inlineContentEditor div.editableContent");if(editableNews)this.newsEditor=new BrainstormJs.Controls.InLineContentEditor({container:editableNews.up("div.inlineContentEditor"),formEditTitle:"Update news",trigger:$("lnkEditNewsContent"),
onSave:function(newContent,callback){Brainstorm.Web.Services.TenantAdmin.UpdateNewsContent(newContent,callback,bsCommon.ajaxCallError)}})}this.profileImage=$("editImage");if(this.profileImage)this.imageEdit=new BrainstormJs.Modules.Person.PersonProfileImage({profile:this,image:this.profileImage});var successStoryFeed=$("successStoryFeed");if(successStoryFeed)this.successStoryActivityFeed=new BrainstormJs.Controls.SuccessStoryFeed(successStoryFeed,{singleItem:true})},initSubscribables:function(){this.subscribables=
$$(".followLink");for(var i=0,j=this.subscribables.length;i<j;i++)this.subscribables[i].observe("click",function(e){this.subscribe(e)}.bind(this))},subscribe:function(e){var el=e.element();var split=el.id.split("_");var objType=split[0];var id=split[1];this.lastSubscribed=el;Brainstorm.Web.Services.Ajax.UpdateSubscription(objType,id,"daily",true,this.onSuccess.bind(this),bsCommon.ajaxCallError)},onSuccess:function(appendTagMessage){this.lastSubscribed.fade({afterFinish:function(){this.lastSubscribed.innerHTML=
"following";this.lastSubscribed.removeClassName("followLink");this.lastSubscribed.addClassName("following");this.lastSubscribed.appear();this.lastSubscribed.stopObserving("click")}.bind(this)});bsCommon.subscriptionMessage(appendTagMessage,true);Brainstorm.Web.Services.Ajax.GetLatestMyFeed(this.refreshMyFeed.bind(this),bsCommon.ajaxCallError)},refreshMyFeed:function(newFeed){var refreshArea=$$("#myFeedUpdater")[0].down(".refreshArea");var noData=refreshArea.down(".noData");if(newFeed.HTML==null)return;
if(noData)noData.blindUp({duration:0.75,afterFinish:function(){noData.remove();var e=newFeed.HTML;refreshArea.insert(e).hide().blindDown();new Effect.Highlight(refreshArea.down(),{delay:0.3})}});else{var oldFeed=refreshArea.down(".activityFeed");if(oldFeed){oldFeed.remove();refreshArea.insert(newFeed.HTML);new Effect.Highlight(refreshArea.down(),{delay:0.3})}}bsCommon.wireActivityFeeds();bsCommon.wireContentPreviews()},afterFormClose:function(){}});
BrainstormPages.register(BrainstormJs.Pages.HomePage,["/","/Home.aspx"]);
BrainstormJs.Pages.IdeasPage=Class.create({grid:false,subscriptionModule:false,ideaForm:false,bizSubsForm:false,successStoryActivityFeed:false,initialize:function(){this.grid=new BrainstormJs.Controls.Grid.IdeaGrid("ideaGrid");this.ideaForm=new BrainstormJs.Forms.IdeaForm({parentContainer:$("ideasNewIdeaContainer"),openLinks:["linkAddIdea"],appearOpenLink:true});var successStoryFeed=$("ideasSuccessStories");if(successStoryFeed)this.successStoryActivityFeed=new BrainstormJs.Controls.SuccessStoryFeed(successStoryFeed)}});
BrainstormPages.register(BrainstormJs.Pages.IdeasPage,"/Ideas.aspx");
BrainstormJs.Pages.PassResetPage=Class.create({txtEmail:false,fieldContainer:false,valEmail:false,processing:false,sendReminderBtn:false,resetError:false,validators:[],initialize:function(){this.sendReminderBtn=$("btnSendReminder");this.pane=$("passResetPane");this.resetError=this.pane.down("div.errorMessage");this.sendReminderBtn.observe("click",function(e){this.sendPassword();e.stop()}.bind(this));this.fieldContainer=this.pane.down("div.formFields");var valEmail=new LiveValidation("txtRemindEmail",
{validMessage:"",wait:500,onlyOnBlur:true});valEmail.add(Validate.Email,{failureMessage:"Invalid Email"});valEmail.add(Validate.Presence,{failureMessage:"Required"});this.validators[0]=valEmail;this.txtEmail=$("txtRemindEmail");this.txtEmail.observe("keypress",function(e){this.onResetEmailKeyPress(e.element(),e)}.bind(this))},checkKeyPress:function(element,e){if(e.keyCode==Event.KEY_RETURN&&element.id=="txtSignUpTitle"&&!this.processing){e.stop();this.signUpNewUser()}},onResetEmailKeyPress:function(element,
e){if(e.keyCode==Event.KEY_RETURN&&!this.processing){e.stop();this.sendPassword()}},toggleFields:function(enabled){this.txtEmail.disabled=!enabled;if(enabled)this.fieldContainer.removeClassName("inactiveFieldContainer");else this.fieldContainer.addClassName("inactiveFieldContainer")},sendPassword:function(){if(this.processing)return;if(!LiveValidation.massValidate(this.validators)){this.resetError.innerHTML="Please enter your email address";this.resetError.show();Effect.Pulsate(this.resetError,{pulses:3,
duration:1.5});return}this.resetError.hide();this.resetError.innerHTML="";this.toggleFields(false);var valid=true;if(valid){bsCommon.startButtonSpinner($("btnSendReminder"),"Verifying Email");this.processing=true;Brainstorm.Web.Services.Ajax.RequestPasswordReset(this.txtEmail.value,this.onResponse.bind(this),this.onError.bind(this))}else this.toggleFields(true)},onResponse:function(userData){this.processing=false;if(userData.Status==Brainstorm.Model.Enums.AccountStatus.NewPassEmailSent){$("passResetPane").down("div.introAndFields").blindUp();
var passSentMessage=$("passSentMessage");var emailAddress=passSentMessage.down("span.emailAddress");if(emailAddress)emailAddress.innerHTML=$F("txtRemindEmail");passSentMessage.blindDown()}if(userData.Email!=null)this.sendReminderBtn.stopObserving("click");else{this.resetError.style.color="red";this.resetForm(true,userData.Status,false)}},onError:function(error){this.processing=false;var message=error.get_message();this.resetForm(true,false,message)},resetForm:function(showError,accountStatus,errorMessage){bsCommon.stopButtonSpinner($("btnSendReminder"),
"Submit");this.toggleFields(true);this.txtEmail.valueOf="";this.txtEmail.focus();if(showError){if(errorMessage)this.resetError.innerHTML="Error: "+errorMessage;else if(accountStatus)if(accountStatus==Brainstorm.Model.Enums.AccountStatus.OffsiteAuth)this.resetError.innerHTML="Your account is not authenticated through Brainstorm. Use your Directory Login credentials to sign into Brainstorm.";else if(accountStatus==Brainstorm.Model.Enums.AccountStatus.NoUserFound)this.resetError.innerHTML="No user found with this email address.";
this.resetError.show()}this.toggleFields(true);if(showError)Effect.Pulsate(this.resetError,{pulses:3,duration:1.5})}});
BrainstormJs.Pages.PeoplePage=Class.create({peopleGrid:false,initialize:function(){var linkEditSkills=$("linkEditSkills");if(linkEditSkills){var skillTagForm=new BrainstormJs.Forms.TagForm(false,Brainstorm.Model.Enums.TagCategory.SkilledAt,{parentContainer:$("editSkills-container"),openLinks:[linkEditSkills],bindOpenLinks:false,editTitle:"Update my skills"});linkEditSkills.observe("click",function(e){skillTagForm.startEditing();e.stop()})}var linkEditInterests=$("linkEditInterests");if(linkEditInterests){var interestTagForm=
new BrainstormJs.Forms.TagForm(false,Brainstorm.Model.Enums.TagCategory.InterestedIn,{parentContainer:$("editInterests-container"),openLinks:[linkEditInterests],bindOpenLinks:false,editTitle:"Update my interests"});linkEditInterests.observe("click",function(e){interestTagForm.startEditing();e.stop()})}var findPeopleLink=$("linkFindPeople");if(findPeopleLink){findPeopleLink.observe("click",function(e){bsCommon.openSlideout(e.element());e.stop()});findPeopleLink.appear()}this.peopleGrid=new BrainstormJs.Controls.Grid.GenericGrid(Brainstorm.Model.Enums.GridType.PeopleGrid,
"personGrid")}});BrainstormPages.register(BrainstormJs.Pages.PeoplePage,"/People.aspx");
BrainstormJs.Pages.PipelinesPage=Class.create({pipelineForm:false,pipelinesGrid:false,initialize:function(){if($("pipelinesDisabled"))return;if($("linkCreatePipeline"))this.pipelineForm=new BrainstormJs.Forms.PipelineForm({parentContainer:$("pipelineFormContainer"),openLinks:["linkCreatePipeline"],appearOpenLink:true});else this.challengeRequestForm=new BrainstormJs.Forms.AdminRequestForm({requestType:Brainstorm.Model.Enums.AdminRequestType.PipelineCreation,parentContainer:$("pipelineFormContainer"),
openLinks:["linkRequestPipeline"],appearOpenLink:true});this.pipelinesGrid=new BrainstormJs.Controls.Grid.PipelineGrid("pipelineGrid")}});BrainstormPages.register(BrainstormJs.Pages.PipelinesPage,"/Pipelines.aspx");BrainstormJs.Pages.SearchPage=Class.create({initialize:function(){}});BrainstormPages.register(BrainstormJs.Pages.SearchPage,"/Search.aspx");var LiveValidation=Class.create();
Object.extend(LiveValidation,{VERSION:"1.3 prototype",TEXTAREA:1,TEXT:2,PASSWORD:3,CHECKBOX:4,SELECT:5,FILE:6,massValidate:function(validations){var returnValue=true;for(var i=0,len=validations.length;i<len;++i){var valid=validations[i].validate();if(returnValue)returnValue=valid}return returnValue}});
LiveValidation.prototype={validClass:"LV_valid",invalidClass:"LV_invalid",messageClass:"LV_validation_message",validFieldClass:"LV_valid_field",invalidFieldClass:"LV_invalid_field",initialize:function(element,optionsObj){if(!element)throw new Error("LiveValidation::initialize - No element reference or element id has been provided!");this.element=$(element);if(!this.element)throw new Error("LiveValidation::initialize - No element with reference or id of '"+element+"' exists!");this.elementType=this.getElementType();
this.validations=[];this.form=this.element.form;this.options=Object.extend({validMessage:"Thankyou!",onValid:function(){this.insertMessage(this.createMessageSpan());this.addFieldClass()},onInvalid:function(){this.insertMessage(this.createMessageSpan());this.addFieldClass();this.element.pulsate({pulses:1})},insertAfterWhatNode:this.element,onlyOnBlur:false,wait:0,onlyOnSubmit:false},optionsObj||{});var node=this.options.insertAfterWhatNode||this.element;this.options.insertAfterWhatNode=$(node);Object.extend(this,
this.options);if(this.form){this.formObj=LiveValidationForm.getInstance(this.form);this.formObj.addField(this)}this.boundFocus=this.doOnFocus.bindAsEventListener(this);Event.observe(this.element,"focus",this.boundFocus);if(!this.onlyOnSubmit)switch(this.elementType){case LiveValidation.CHECKBOX:this.boundClick=this.validate.bindAsEventListener(this);Event.observe(this.element,"click",this.boundClick);case LiveValidation.SELECT:case LiveValidation.FILE:this.boundChange=this.validate.bindAsEventListener(this);
Event.observe(this.element,"change",this.boundChange);break;default:if(!this.onlyOnBlur){this.boundKeyup=this.deferValidation.bindAsEventListener(this);Event.observe(this.element,"keyup",this.boundKeyup)}this.boundBlur=this.validate.bindAsEventListener(this);Event.observe(this.element,"blur",this.boundBlur)}},destroy:function(){if(this.formObj){this.formObj.removeField(this);this.formObj.destroy()}Event.stopObserving(this.element,"focus",this.boundFocus);if(!this.onlyOnSubmit)switch(this.elementType){case LiveValidation.CHECKBOX:Event.stopObserving(this.element,
"click",this.boundClick);case LiveValidation.SELECT:case LiveValidation.FILE:Event.stopObserving(this.element,"change",this.boundChange);break;default:if(!this.onlyOnBlur)Event.stopObserving(this.element,"keyup",this.boundKeyup);Event.stopObserving(this.element,"blur",this.boundBlur)}this.validations=[];this.removeMessageAndFieldClass()},add:function(validationFunction,validationParamsObj){this.validations.push({type:validationFunction,params:validationParamsObj||{}});return this},remove:function(validationFunction,
validationParamsObj){this.validations=this.validations.reject(function(v){return v.type==validationFunction&&v.params==validationParamsObj});return this},deferValidation:function(e){if(this.wait>=300)this.removeMessageAndFieldClass();if(this.timeout)clearTimeout(this.timeout);this.timeout=setTimeout(this.validate.bind(this),this.wait)},doOnBlur:function(){this.focused=false;this.validate()},doOnFocus:function(){this.focused=true;this.removeMessageAndFieldClass()},getElementType:function(){switch(true){case this.element.nodeName.toUpperCase()==
"TEXTAREA":return LiveValidation.TEXTAREA;case this.element.nodeName.toUpperCase()=="INPUT"&&this.element.type.toUpperCase()=="TEXT":return LiveValidation.TEXT;case this.element.nodeName.toUpperCase()=="INPUT"&&this.element.type.toUpperCase()=="PASSWORD":return LiveValidation.PASSWORD;case this.element.nodeName.toUpperCase()=="INPUT"&&this.element.type.toUpperCase()=="CHECKBOX":return LiveValidation.CHECKBOX;case this.element.nodeName.toUpperCase()=="INPUT"&&this.element.type.toUpperCase()=="FILE":return LiveValidation.FILE;
case this.element.nodeName.toUpperCase()=="SELECT":return LiveValidation.SELECT;case this.element.nodeName.toUpperCase()=="INPUT":throw new Error("LiveValidation::getElementType - Cannot use LiveValidation on an "+this.element.type+" input!");default:throw new Error("LiveValidation::getElementType - Element must be an input, select, or textarea!");}},doValidations:function(){this.validationFailed=false;for(var i=0,len=this.validations.length;i<len;++i){var validation=this.validations[i];switch(validation.type){case Validate.Presence:case Validate.Confirmation:case Validate.Acceptance:this.displayMessageWhenEmpty=
true;this.validationFailed=!this.validateElement(validation.type,validation.params);break;default:this.validationFailed=!this.validateElement(validation.type,validation.params);break}if(this.validationFailed)return false}this.message=this.validMessage;return true},validateElement:function(validationFunction,validationParamsObj){var value=this.elementType==LiveValidation.SELECT?this.element.options[this.element.selectedIndex].value:this.element.value;if(validationFunction==Validate.Acceptance){if(this.elementType!=
LiveValidation.CHECKBOX)throw new Error("LiveValidation::validateElement - Element to validate acceptance must be a checkbox!");value=this.element.checked}var isValid=true;try{validationFunction(value,validationParamsObj)}catch(error){if(error instanceof Validate.Error){if(value!==""||value===""&&this.displayMessageWhenEmpty){this.validationFailed=true;this.message=error.message;isValid=false}}else throw error;}finally{return isValid}},validate:function(){if(!this.element.disabled){var isValid=this.doValidations();
if(isValid){this.onValid();return true}else{this.onInvalid();return false}}else return true},enable:function(){this.element.disabled=false;return this},disable:function(){this.element.disabled=true;this.removeMessageAndFieldClass();return this},createMessageSpan:function(){var span=document.createElement("span");var textNode=document.createTextNode(this.message);span.appendChild(textNode);return span},insertMessage:function(elementToInsert){this.removeMessage();var className=this.validationFailed?
this.invalidClass:this.validClass;if(this.displayMessageWhenEmpty&&(this.elementType==LiveValidation.CHECKBOX||this.element.value=="")||this.element.value!=""){$(elementToInsert).addClassName(this.messageClass+(" "+className));if(nxtSibling=this.insertAfterWhatNode.nextSibling)this.insertAfterWhatNode.parentNode.insertBefore(elementToInsert,nxtSibling);else this.insertAfterWhatNode.parentNode.appendChild(elementToInsert)}},addFieldClass:function(){this.removeFieldClass();if(!this.validationFailed){if(this.displayMessageWhenEmpty||
this.element.value!="")if(!this.element.hasClassName(this.validFieldClass))this.element.addClassName(this.validFieldClass)}else if(!this.element.hasClassName(this.invalidFieldClass))this.element.addClassName(this.invalidFieldClass)},removeMessage:function(){if(nxtEl=this.insertAfterWhatNode.next("."+this.messageClass))nxtEl.remove()},removeFieldClass:function(){this.element.removeClassName(this.invalidFieldClass);this.element.removeClassName(this.validFieldClass)},removeMessageAndFieldClass:function(){this.removeMessage();
this.removeFieldClass()}};var LiveValidationForm=Class.create();Object.extend(LiveValidationForm,{instances:{},getInstance:function(element){var rand=Math.random()*Math.random();if(!element.id)element.id="formId_"+rand.toString().replace(/\./,"")+(new Date).valueOf();if(!LiveValidationForm.instances[element.id])LiveValidationForm.instances[element.id]=new LiveValidationForm(element);return LiveValidationForm.instances[element.id]}});
LiveValidationForm.prototype={initialize:function(element){this.element=$(element);this.fields=[];this.oldOnSubmit=this.element.onsubmit||function(){};this.element.onsubmit=function(e){var ret=LiveValidation.massValidate(this.fields)?this.oldOnSubmit.call(this.element,e)!==false:false;if(!ret)Event.stop(e)}.bindAsEventListener(this)},addField:function(lvObj){this.fields.push(lvObj)},removeField:function(victim){this.fields=this.fields.without(victim)},destroy:function(force){if(this.fields.length!=
0&&!force)return false;this.element.onsubmit=this.oldOnSubmit;LiveValidationForm.instances[this.element.id]=null;return true}};
var Validate={Presence:function(value,paramsObj){var params=Object.extend({failureMessage:"Can't be empty!"},paramsObj||{});if(value===""||value===null||value===undefined)Validate.fail(params.failureMessage);return true},Numericality:function(value,paramsObj){var suppliedValue=value;var value=Number(value);var paramsObj=paramsObj||{};var params={notANumberMessage:paramsObj.notANumberMessage||"Must be a number!",notAnIntegerMessage:paramsObj.notAnIntegerMessage||"Must be an integer!",wrongNumberMessage:paramsObj.wrongNumberMessage||
"Must be "+paramsObj.is+"!",tooLowMessage:paramsObj.tooLowMessage||"Must not be less than "+paramsObj.minimum+"!",tooHighMessage:paramsObj.tooHighMessage||"Must not be more than "+paramsObj.maximum+"!",is:paramsObj.is||paramsObj.is==0?paramsObj.is:null,minimum:paramsObj.minimum||paramsObj.minimum==0?paramsObj.minimum:null,maximum:paramsObj.maximum||paramsObj.maximum==0?paramsObj.maximum:null,onlyInteger:paramsObj.onlyInteger||false};if(!isFinite(value))Validate.fail(params.notANumberMessage);if(params.onlyInteger&&
(/\.0+$|\.$/.test(String(suppliedValue))||value!=parseInt(value)))Validate.fail(params.notAnIntegerMessage);switch(true){case params.is!==null:if(value!=Number(params.is))Validate.fail(params.wrongNumberMessage);break;case params.minimum!==null&&params.maximum!==null:Validate.Numericality(value,{tooLowMessage:params.tooLowMessage,minimum:params.minimum});Validate.Numericality(value,{tooHighMessage:params.tooHighMessage,maximum:params.maximum});break;case params.minimum!==null:if(value<Number(params.minimum))Validate.fail(params.tooLowMessage);
break;case params.maximum!==null:if(value>Number(params.maximum))Validate.fail(params.tooHighMessage);break}return true},Format:function(value,paramsObj){var value=String(value);var params=Object.extend({failureMessage:"Not valid!",pattern:/./,negate:false},paramsObj||{});if(!params.negate&&!params.pattern.test(value))Validate.fail(params.failureMessage);if(params.negate&&params.pattern.test(value))Validate.fail(params.failureMessage);return true},Email:function(value,paramsObj){var params=Object.extend({failureMessage:"Must be a valid email address!"},
paramsObj||{});Validate.Format(value,{failureMessage:params.failureMessage,pattern:/^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i});return true},Length:function(value,paramsObj){var value=String(value);var paramsObj=paramsObj||{};var params={wrongLengthMessage:paramsObj.wrongLengthMessage||"Must be "+paramsObj.is+" characters long!",tooShortMessage:paramsObj.tooShortMessage||"Must not be less than "+paramsObj.minimum+" characters long!",tooLongMessage:paramsObj.tooLongMessage||"Must not be more than "+
paramsObj.maximum+" characters long!",is:paramsObj.is||paramsObj.is==0?paramsObj.is:null,minimum:paramsObj.minimum||paramsObj.minimum==0?paramsObj.minimum:null,maximum:paramsObj.maximum||paramsObj.maximum==0?paramsObj.maximum:null};switch(true){case params.is!==null:if(value.length!=Number(params.is))Validate.fail(params.wrongLengthMessage);break;case params.minimum!==null&&params.maximum!==null:Validate.Length(value,{tooShortMessage:params.tooShortMessage,minimum:params.minimum});Validate.Length(value,
{tooLongMessage:params.tooLongMessage,maximum:params.maximum});break;case params.minimum!==null:if(value.length<Number(params.minimum))Validate.fail(params.tooShortMessage);break;case params.maximum!==null:if(value.length>Number(params.maximum))Validate.fail(params.tooLongMessage);break;default:throw new Error("Validate::Length - Length(s) to validate against must be provided!");}return true},Inclusion:function(value,paramsObj){var params=Object.extend({failureMessage:"Must be included in the list!",
within:[],allowNull:false,partialMatch:false,caseSensitive:true,negate:false},paramsObj||{});if(params.allowNull&&value==null)return true;if(!params.allowNull&&value==null)Validate.fail(params.failureMessage);if(!params.caseSensitive){var lowerWithin=[];params.within.each(function(item){if(typeof item=="string")item=item.toLowerCase();lowerWithin.push(item)});params.within=lowerWithin;if(typeof value=="string")value=value.toLowerCase()}var found=params.within.indexOf(value)==-1?false:true;if(params.partialMatch){found=
false;params.within.each(function(arrayVal){if(value.indexOf(arrayVal)!=-1)found=true})}if(!params.negate&&!found||params.negate&&found)Validate.fail(params.failureMessage);return true},Exclusion:function(value,paramsObj){var params=Object.extend({failureMessage:"Must not be included in the list!",within:[],allowNull:false,partialMatch:false,caseSensitive:true},paramsObj||{});params.negate=true;Validate.Inclusion(value,params);return true},Confirmation:function(value,paramsObj){if(!paramsObj.match)throw new Error("Validate::Confirmation - Error validating confirmation: Id of element to match must be provided!");
var params=Object.extend({failureMessage:"Does not match!",match:null},paramsObj||{});params.match=$(paramsObj.match);if(!params.match)throw new Error("Validate::Confirmation - There is no reference with name of, or element with id of '"+params.match+"'!");if(value!=params.match.value)Validate.fail(params.failureMessage);return true},Acceptance:function(value,paramsObj){var params=Object.extend({failureMessage:"Must be accepted!"},paramsObj||{});if(!value)Validate.fail(params.failureMessage);return true},
Custom:function(value,paramsObj){var params=Object.extend({against:function(){return true},args:{},failureMessage:"Not valid!"},paramsObj||{});if(!params.against(value,params.args))Validate.fail(params.failureMessage);return true},now:function(validationFunction,value,validationParamsObj){if(!validationFunction)throw new Error("Validate::now - Validation function must be provided!");var isValid=true;try{validationFunction(value,validationParamsObj||{})}catch(error){if(error instanceof Validate.Error)isValid=
false;else throw error;}finally{return isValid}},Error:function(errorMessage){this.message=errorMessage;this.name="ValidationError"},fail:function(errorMessage){throw new Validate.Error(errorMessage);}};function signInLoad(){IN.Event.on(IN,"auth",function(){onLinkedInLogin()})}
function onLinkedInLogin(){$("linkedInDiv").down("p.li").fade();$$("span.liBadge").each(function(el){el.appear()});IN.API.Profile("me").fields(["id","firstName","lastName","pictureUrl","headline","specialties","interests","skills","positions:(company)","location:(name)"]).result(function(result){profile=result.values[0];liProfile=profile;$("txtSignUpFirstName").value=profile.firstName;$("txtSignUpLastName").value=profile.lastName;var skillStr=getSkillStr(profile.skills);$("hiddenSkills").value=skillStr;
$("hiddenInterests").value=profile.interests;$("hiddenPictureUrl").value=profile.pictureUrl;$("hiddenHeadline").value=profile.headline;$("hiddenLocation").value=profile.location})}function getSkillStr(arr){var tags=[];tags=arr.values;var skillStr="";for(var index=0;index<tags.length;index++)skillStr+=tags[index].skill.name+",";return skillStr}
BrainstormJs.Pages.SignUpPage=Class.create({fieldContainer:false,signUp:false,valUsername:false,valPassword:false,processing:false,signUpLink:false,signInLink:false,forgotPwLink:false,processing:false,txtSignUpFirstName:false,txtSignUpLastName:false,txtSignUpEmail:false,txtSignUpPassword:false,signUpPane:false,signInPane:false,passResetPane:false,signUpError:false,terms:false,termsChecked:false,validators:[],initialize:function(){$("txtSignUpPassword").observe("keypress",function(e){this.checkKeyPress(e.element(),
e)}.bind(this));this.signUpBtn=$("btnSignUp");this.signUpBtn.observe("click",function(e){this.signUpNewUser();e.stop()}.bind(this));this.fieldContainer=$("signUpPane").down("div.formFields");this.signUpPane=$("signUpPane");this.signInPane=$("signInPane");this.passResetPane=$("passResetPane");this.signUpError=this.signUpPane.down("div.errorMessage");if(!this.signUpPane&&!this.passResetPane)return;var signUpLinks=$$("a.signUpLink");for(var i=0,j=signUpLinks.length;i<j;i++)signUpLinks[i].observe("click",
function(e){this.togglePane(e,$("signUpPane"),"Sign Up")}.bind(this));var signInLinks=$$("a.signInLink");for(var i=0,j=signInLinks.length;i<j;i++)signInLinks[i].observe("click",function(e){this.togglePane(e,$("signInPane"),"Sign In")}.bind(this));var forgotPwLinks=$$("a.forgotPassLink");for(var i=0,j=forgotPwLinks.length;i<j;i++)forgotPwLinks[i].observe("click",function(e){this.togglePane(e,$("passResetPane"),"Reset Password")}.bind(this));var i=0;var validateFirstName=new LiveValidation("txtSignUpFirstName",
{validMessage:"",wait:500,onlyOnBlur:true});validateFirstName.add(Validate.Presence,{failureMessage:"Required"});this.validators[i++]=validateFirstName;var validateLastName=new LiveValidation("txtSignUpLastName",{validMessage:"",wait:500,onlyOnBlur:true});validateLastName.add(Validate.Presence,{failureMessage:"Required"});this.validators[i++]=validateLastName;var validateEmail=new LiveValidation("txtSignUpEmail",{validMessage:"",wait:500,onlyOnBlur:true});validateEmail.add(Validate.Presence,{failureMessage:"Required"});
validateEmail.add(Validate.Email,{failureMessage:"Invalid Email"});this.validators[i++]=validateEmail;var validatePassword=new LiveValidation("txtSignUpPassword",{validMessage:"",wait:500,onlyOnBlur:true});validatePassword.add(Validate.Presence,{failureMessage:"Required"});if(typeof listOfRegs!="undefined"&&listOfRegs!=[])for(var j=0;j<listOfRegs.length;j++){var re=listOfRegs[j];validatePassword.add(Validate.Format,{pattern:re.regexp,failureMessage:re.failMsg,onValid:{}})}this.validators[i++]=validatePassword;
this.txtSignUpFirstName=$("txtSignUpFirstName");this.txtSignUpLastName=$("txtSignUpLastName");this.txtSignUpEmail=$("txtSignUpEmail");this.txtSignUpPassword=$("txtSignUpPassword");this.chkTermsAgree=$("chkTermsAgree");if(this.passResetPane)new BrainstormJs.Pages.PassResetPage(this.passResetPane);var termsLink=$("termsLink");if(termsLink){this.terms=$$(".terms")[0];termsLink.observe("click",function(e){this.tocClick(e);e.stop()}.bind(this))}var els=getUrlParam("nav");if(els=="SignUp"){$("signInPane").blindUp({duration:0.5});
$("signUpPane").blindDown({duration:0.5})}},validFields:function(){var areAllValid=LiveValidation.massValidate(this.validators);return areAllValid},tocClick:function(e){if(!this.tocEnabled){this.terms.blindDown({duration:0.5});this.tocEnabled=true}else{this.terms.blindUp({duration:0.5});this.tocEnabled=false}},togglePane:function(clickEvent,newPane,pageTitle){clickEvent.stop();var blindTime=0.5;var linkClicked=clickEvent.element();var currentPane=linkClicked.up("div.formPane");currentPane.blindUp({duration:blindTime});
newPane.blindDown({duration:blindTime})},checkKeyPress:function(element,e){if(e.keyCode==Event.KEY_RETURN&&element.id=="txtSignUpPassword"&&!this.processing){e.stop();this.signUpNewUser()}},toggleFields:function(enabled){this.txtSignUpFirstName.disabled=!enabled;this.txtSignUpLastName.disabled=!enabled;this.txtSignUpEmail.disabled=!enabled;this.txtSignUpPassword.disabled=!enabled;if(enabled)this.fieldContainer.removeClassName("inactiveFieldContainer");else this.fieldContainer.addClassName("inactiveFieldContainer")},
signUpNewUser:function(){if(this.processing)return;if(!this.validFields()){var errorMessage="Please complete all required fields";if(this.chkTermsAgree)if(!this.chkTermsAgree.checked)errorMessage+=" and agree to the terms";this.signUpError.innerHTML=errorMessage;this.signUpError.show();Effect.Pulsate(this.signUpError,{pulses:3,duration:1.5});return}if(this.chkTermsAgree){tocChecked=this.chkTermsAgree.checked;if(!tocChecked){this.signUpError.innerHTML="You must agree to the Terms and Conditions to continue";
this.signUpError.show();Effect.Pulsate(this.signUpError,{pulses:3,duration:1.5});Effect.Pulsate(this.chkTermsAgree.up(),{pulses:3,duration:1.5});return}}this.signUpError.hide();this.toggleFields(false);var valid=true;if(valid){bsCommon.startButtonSpinner($("btnSignUp"),"Signing Up");this.processing=true;Brainstorm.Web.Services.Ajax.CreateUser(this.txtSignUpFirstName.value,this.txtSignUpLastName.value,this.txtSignUpEmail.value,this.txtSignUpPassword.value,$("hiddenSkills").value,$("hiddenInterests").value,
$("hiddenPictureUrl").value,$("hiddenHeadline").value,$("hiddenLocation").value,this.onResponse.bind(this),this.onError.bind(this))}else this.toggleFields(true)},onResponse:function(userData){this.processing=false;if(userData.Email==null){this.resetForm(true,userData.Status,false,userData.Message);return}$("signUpPane").down("div.introAndFields").blindUp();$("emailSentMessage").blindDown();this.signUpBtn.stopObserving("click");if($("linkedInDiv"))IN.UI.Share().params({url:document.location.href}).place()},
onError:function(error){this.processing=false;var message="Uh oh! ... Try again or contact <a href='mailto:brainstorm@intuit.com'>Brainstorm</a>";this.resetForm(true,false,message)},resetForm:function(showError,signUpStatus,errorMessage,message){bsCommon.stopButtonSpinner($("btnSignUp"),"Sign Up");var emailEntered=$F("txtSignUpEmail");var focusField=this.txtSignUpFirstName;this.toggleFields(true);if(showError){if(errorMessage)this.signUpError.innerHTML="Error: "+errorMessage;else if(signUpStatus)if(signUpStatus==
Brainstorm.Model.Enums.AccountStatus.EmailNotUnique){this.signUpError.innerHTML='The email you chose is already in use. <br/><a href="#" class="forgotPassword">Did you forget your password?</a>';focusField=this.txtSignUpEmail;window.setTimeout(function(){var forgotPasswordLink=this.signUpError.down("a.forgotPassword");if(forgotPasswordLink){forgotPasswordLink.observe("click",function(e){this.togglePane(e,$("passResetPane"),"Reset Password")}.bind(this));$("txtRemindEmail").value=emailEntered}}.bind(this),
1)}else if(signUpStatus==Brainstorm.Model.Enums.AccountStatus.DomainNotAllowed){this.signUpError.innerHTML="The domain name of the email you chose is not allowed for this Brainstorm network.";focusField=this.txtSignUpEmail}else if(signUpStatus==Brainstorm.Model.Enums.AccountStatus.SignUpNotAllowed)this.signUpError.innerHTML="Sign up is currently disabled for this network.";else if(signUpStatus==Brainstorm.Model.Enums.AccountStatus.PasswordInsufficient)this.signUpError.innerHTML=message;this.signUpError.appear();
this.signUpError.appear()}this.toggleFields(true);focusField.focus();if(showError)Effect.Pulsate(this.signUpError,{pulses:3,duration:1.5})},clearSignUpFields:function(){this.txtSignUpFirstName.value="";this.txtSignUpLastName.value="";this.txtSignUpEmail.value="";this.txtSignUpPassword.value=""}});var myVal=false;
BrainstormJs.Pages.SignInPage=Class.create({txtUsername:false,txtPassword:false,chkRemember:false,fieldContainer:false,signUp:false,signInError:false,valUsername:false,valPassword:false,processing:false,vcode:false,passToken:false,email:false,validators:[],initialize:function(){this.vcode=bsCommon.getUrlParam("v");this.passToken=bsCommon.getUrlParam("fpw");this.email=bsCommon.getUrlParam("u");if(this.passToken!=""&&this.email!="")$("btnLogIn").observe("click",function(e){this.startResetPw();e.stop()}.bind(this));
else $("btnLogIn").observe("click",function(e){this.startAuth();e.stop()}.bind(this));$("txtPassword").observe("keypress",function(e){this.checkKeyPress(e.element(),e)}.bind(this));$("chkRemember").observe("keypress",function(e){this.checkKeyPress(e.element(),e)}.bind(this));this.txtUsername=$("txtUsername");this.txtPassword=$("txtPassword");this.chkRemember=$("chkRemember");var signInPane=$("signInPane");this.fieldContainer=signInPane.down("div.formFields");this.signInError=signInPane.down("div.errorMessage");
this.toggleFields(true);var i=0;var validateUsername=new LiveValidation("txtUsername",{validMessage:"",wait:500,onlyOnBlur:true});validateUsername.add(Validate.Presence,{failureMessage:"Required"});this.validators[i++]=validateUsername;var validatePassword=new LiveValidation("txtPassword",{validMessage:"",wait:500,onlyOnBlur:true});validatePassword.add(Validate.Presence,{failureMessage:"Required"});this.validators[i++]=validatePassword;var username=bsCommon.getUrlParam("u");var pw=bsCommon.getUrlParam("p");
if(username||pw)this.prepopulate(username,pw);this.fieldFocus();var signUpLink=$$(".signUpLink");var forgotPwLinks=$$("a.forgotPassLink");if(signUpLink.length>1||forgotPwLinks.length>1)this.signUp=new BrainstormJs.Pages.SignUpPage(signUpLink)},checkKeyPress:function(element,e){if(e.keyCode==Event.KEY_RETURN&&(element.id=="txtPassword"||element.id=="chkRemember")&&!this.processing){e.stop();if(this.passToken!=""&&this.email!="")this.startResetPw();else this.startAuth()}},fieldFocus:function(){var username=
this.txtUsername.value;var password=this.txtPassword.value;if($("txtGetTempPassword")){$("txtGetTempPassword").focus();return}if(username.strip()=="")this.txtUsername.focus();else if(password.strip()=="")this.txtPassword.focus()},prepopulate:function(username,pw){username=unescape(username);this.txtUsername.value=username;this.txtPassword.value=pw},toggleFields:function(enabled){this.txtUsername.disabled=!enabled;this.txtPassword.disabled=!enabled;this.chkRemember.disabled=!enabled;if(enabled)this.fieldContainer.removeClassName("inactiveFieldContainer");
else this.fieldContainer.addClassName("inactiveFieldContainer")},startAuth:function(){if(this.processing)return;if(!LiveValidation.massValidate(this.validators)){this.signInError.innerHTML="Please complete all required fields";this.signInError.show();Effect.Pulsate(this.signInError,{pulses:3,duration:1.5});return}var username=this.txtUsername.value;var password=this.txtPassword.value;this.signInError.hide();this.toggleFields(false);var btnText="Signing In";if(this.vcode==""||!this.vcode)this.vcode=
"-1";var remember=$F("chkRemember")=="on"?true:false;var valid=true;if(valid){bsCommon.startButtonSpinner($("btnLogIn"),btnText);this.processing=true;Brainstorm.Web.Services.Ajax.AuthenticateUser(username,password,remember,this.vcode,(new Date).getTimezoneOffset(),this.onResponse.bind(this),this.onError.bind(this))}else this.toggleFields(true)},onResponse:function(authResponse){this.processing=false;var authEnum=authResponse.AuthResp;if(authEnum==Brainstorm.Model.Enums.AuthResponse.NeedToReverify||
authEnum==Brainstorm.Model.Enums.AuthResponse.LockedOut||authEnum==Brainstorm.Model.Enums.AuthResponse.TokenInvalid){var fields=$("signInPane").down(".introAndFields");fields.blindUp({afterFinish:function(){fields.remove()}});var formTitle=$("signInPane").down(".formTitle");new Insertion.After(formTitle,authResponse.Message);return}if(!(authEnum==Brainstorm.Model.Enums.AuthResponse.DirectoryAuthenticated||authEnum==Brainstorm.Model.Enums.AuthResponse.MasterAdminAuthenticated||authEnum==Brainstorm.Model.Enums.AuthResponse.SignUpAuthenticated)){this.resetForm(true,
authResponse.Message);return}this.signInError.hide();bsCommon.stopButtonSpinner($("btnLogIn"),"Signed In - Redirecting ...","done");var returnUrl=bsCommon.getUrlParam("ReturnUrl");var hostname=window.location.hostname||"";if(hostname.match(/localhost/i)==null){var protocol="http:";if($F("BS_RequireHttps")==="1")protocol=document.location.protocol;hostname=protocol+"//"+hostname}else hostname="";if(returnUrl!=""){returnUrl=urldecode(returnUrl);document.location.href=hostname+returnUrl}else document.location.href=
hostname+"/Home.aspx"},onError:function(error){this.processing=false;var message=error.get_message();this.resetForm(true,"Error: "+message)},resetForm:function(showError,errorMessage){bsCommon.stopButtonSpinner($("btnLogIn"),"Sign In");if(showError){if(errorMessage)this.signInError.innerHTML=errorMessage;this.signInError.show()}this.toggleFields(true);this.txtUsername.focus();this.txtPassword.value="";this.fieldFocus();if(showError){Effect.Pulsate(this.signInError,{pulses:3,duration:1.5});this.helpContent=
this.signInError.next(".helpContent");if(this.helpContent)this.helpContent.blindDown()}},startResetPw:function(){if(this.processing)return;if(!LiveValidation.massValidate(this.validators)){this.signInError.innerHTML="Please fill out missing fields";this.signInError.show();Effect.Pulsate(this.signInError,{pulses:3,duration:1.5});return}var username=this.txtUsername.value;var password=this.txtPassword.value;this.signInError.hide();this.toggleFields(false);var valid=true;if(valid){bsCommon.startButtonSpinner($("btnLogIn"),
"Signing In");this.processing=true;Brainstorm.Web.Services.Ajax.ResetPassword(username,this.passToken,password,this.onResponse.bind(this),this.onError.bind(this))}else this.toggleFields(true)}});BrainstormPages.register(BrainstormJs.Pages.SignInPage,"/SignIn.aspx");
BrainstormJs.Pages.UpgradePage=Class.create({txtName:false,txtEmail:false,txtPhone:false,fieldContainer:false,valUsername:false,valPassword:false,processing:false,validators:[],initialize:function(){this.formDiv=$("form");this.btnSubmit=$("btnSubmit");this.formPane=this.formDiv.down("div.formPane");this.fieldContainer=this.formPane.down("div.formFields");this.successMessage=this.formPane.next("div.successMessage");this.errorMessage=this.successMessage.next("div.errorMessage");this.initUpgradeForm();
this.btnSubmit.observe("click",function(e){this.submitUpgradeForm();e.stop()}.bind(this))},initUpgradeForm:function(){this.txtName=$("txtName");this.txtEmail=$("txtEmail");this.txtPhone=$("txtPhone");this.validators=[];var validateName=new LiveValidation(this.txtName,{validMessage:"",wait:500,onlyOnBlur:true});validateName.add(Validate.Presence,{failureMessage:"Required"});this.validators.push(validateName);var validateEmail=new LiveValidation(this.txtEmail,{validMessage:"",wait:500,onlyOnBlur:true});
validateEmail.add(Validate.Presence,{failureMessage:"Required"});validateEmail.add(Validate.Email,{failureMessage:"Invalid"});this.validators.push(validateEmail);var validatePhone=new LiveValidation(this.txtPhone,{validMessage:"",wait:500,onlyOnBlur:true});validatePhone.add(Validate.Presence,{failureMessage:"Required"});this.validators.push(validatePhone);this.toggleUpgradeFields(true)},toggleUpgradeFields:function(enabled){this.txtName.disabled=!enabled;this.txtEmail.disabled=!enabled;this.txtPhone.disabled=
!enabled;if(enabled)this.fieldContainer.removeClassName("inactiveFieldContainer");else this.fieldContainer.addClassName("inactiveFieldContainer")},submitUpgradeForm:function(){if(this.processing)return;if(!LiveValidation.massValidate(this.validators))return;this.toggleUpgradeFields(false);this.startButtonSpinner(this.btnSubmit,"Please Wait ...");this.processing=true;Brainstorm.Web.Services.Ajax.RequestUpgrade(this.txtName.value,this.txtEmail.value,this.txtPhone.value,this.onResponse.bind(this),this.onError.bind(this))},
onResponse:function(obj){this.stopButtonSpinner(this.btnSubmit,"Form Submitted");this.formPane.blindUp({duration:1});this.successMessage.blindDown({duration:1})},onError:function(error){this.formPane.blindUp({duration:1});this.errorMessage.blindDown({duration:1})},startButtonSpinner:function(linkButton,message){linkButton.addClassName("workingLinkButton");linkButton.href="";var label=linkButton.down("span.label");label.addClassName("working");if(message)label.innerHTML=message},stopButtonSpinner:function(linkButton,
message,markDone){if(!linkButton)return;linkButton.removeClassName("workingLinkButton");linkButton.href="#";var label=linkButton.down("span.label");label.removeClassName("working");if(message)label.innerHTML=message;if(markDone)label.addClassName("done")}});BrainstormPages.register(BrainstormJs.Pages.UpgradePage,"/Upgrade.aspx");if(typeof Effect=="undefined")throw"accordion.js requires including script.aculo.us' effects.js library!";var accordion=Class.create();
accordion.prototype={showAccordion:null,currentAccordion:null,duration:null,effects:[],animating:false,AlreadyActivated:[],initialize:function(container,options){if(!$(container)){throw container+" doesn't exist!";return false}this.options=Object.extend({resizeSpeed:8,classNames:{toggle:"accordion_toggle",toggleActive:"accordion_toggle_active",content:"accordion_content"},defaultSize:{height:null,width:null},direction:"vertical",onEvent:"click",onActivate:null,RepeatActivate:{}},options||{});this.duration=
(11-this.options.resizeSpeed)*0.15;this.AlreadyActivated=[];var accordions=$$("#"+container+" ."+this.options.classNames.toggle);accordions.each(function(accordion){Event.observe(accordion,this.options.onEvent,this.activate.bind(this,accordion),false);if(this.options.onEvent=="click")accordion.onclick=function(){return false};if(this.options.direction=="horizontal")var options={width:"0px"};else var options={height:"0px"};Object.extend(options,{display:"none"});this.currentAccordion=$(accordion.next(0)).setStyle(options)}.bind(this))},
activate:function(accordion){if(this.animating)return false;this.effects=[];this.currentAccordion=$(accordion.next(0));this.currentAccordion.setStyle({display:"block"});this.currentAccordion.previous(0).addClassName(this.options.classNames.toggleActive);if(this.options.direction=="horizontal")this.scaling={scaleX:true,scaleY:false};else this.scaling={scaleX:false,scaleY:true};if(this.currentAccordion==this.showAccordion)this.deactivate();else{var bolCall=true;var elementid=$(this.currentAccordion).id;
var AA=this.AlreadyActivated.indexOf(elementid);var RA=this.options.RepeatActivate[elementid];if(RA!=undefined)if(AA!=-1){if(RA!=undefined)bolCall=RA}else this.AlreadyActivated.push(elementid);if(this.options.onActivate&&bolCall)this.options.onActivate(this.currentAccordion);this._handleAccordion()}},deactivate:function(){var options={duration:this.duration,scaleContent:false,transition:Effect.Transitions.sinoidal,queue:{position:"end",scope:"accordionAnimation"},scaleMode:{originalHeight:this.options.defaultSize.height?
this.options.defaultSize.height:this.currentAccordion.scrollHeight,originalWidth:this.options.defaultSize.width?this.options.defaultSize.width:this.currentAccordion.scrollWidth},afterFinish:function(){this.showAccordion.setStyle({height:"0px",display:"none"});this.showAccordion=null;this.animating=false}.bind(this)};Object.extend(options,this.scaling);this.showAccordion.previous(0).removeClassName(this.options.classNames.toggleActive);new Effect.Scale(this.showAccordion,0,options)},_handleAccordion:function(){var options=
{sync:true,scaleFrom:0,scaleContent:false,transition:Effect.Transitions.sinoidal,scaleMode:{originalHeight:this.options.defaultSize.height?this.options.defaultSize.height:this.currentAccordion.scrollHeight,originalWidth:this.options.defaultSize.width?this.options.defaultSize.width:this.currentAccordion.scrollWidth}};Object.extend(options,this.scaling);this.effects.push(new Effect.Scale(this.currentAccordion,100,options));if(this.showAccordion){this.showAccordion.previous(0).removeClassName(this.options.classNames.toggleActive);
options={sync:true,scaleContent:false,transition:Effect.Transitions.sinoidal};Object.extend(options,this.scaling);this.effects.push(new Effect.Scale(this.showAccordion,0,options))}new Effect.Parallel(this.effects,{duration:this.duration,queue:{position:"end",scope:"accordionAnimation"},beforeStart:function(){this.animating=true}.bind(this),afterFinish:function(){if(this.showAccordion)this.showAccordion.setStyle({display:"none"});$(this.currentAccordion).setStyle({height:"auto"});this.showAccordion=
this.currentAccordion;this.animating=false}.bind(this)})}};
BrainstormJs.Profiles.BaseProfile=Class.create({objectType:false,titleEditor:false,initialize:function(objectType){this.objectType=objectType;this.initializeTitleEditor();this.initializeParts();this.initializeCustomFields();this.wireAdminModule();BrainstormJs.Controls.Comments.CommentUtils.wireComments()},initializeTitleEditor:function(){var pageTitle=$("profilePageTitle");if(!pageTitle)return;var editTitleLink=pageTitle.down("a.editTitle");if(editTitleLink){var inlineEditorEl=pageTitle.down("div.inlineEditor");
var profileNameEl=pageTitle.down("span.profileName");var bgColor=pageTitle.getStyle("background-color");bgColor=bgColor?bgColor.parseColor():false;this.titleEditor=new BrainstormJs.Controls.InLineEditor({contentEl:profileNameEl,editLink:editTitleLink,container:inlineEditorEl,restoreColor:bgColor,serviceMethod:this.getTitleUpdateMethod(),serviceParams:[this.id],afterSave:function(newTitle){this.afterTitleSave(newTitle)}.bind(this)});editTitleLink.appear({delay:0.25,from:0,to:0.5})}},initializeParts:function(){var partContainer=
$("partContainer");if(partContainer)this.partContainer=new BrainstormJs.Controls.Parts.PartContainer(partContainer)},initializeCustomFields:function(){var panelDiv=$("customFieldsConfigPanel");if(panelDiv)var panel=new BrainstormJs.Controls.CustomFields.CustomFieldsConfigPanel(panelDiv)},wireAdminModule:function(){var adminModule=$("profileAdminModule");if(adminModule){var toggleLink=$("showProfileAdminModule");toggleLink.observe("click",function(e){toggleLink.fade({duration:0.25,afterFinish:function(){adminModule.blindDown({duration:0.8})}});
e.stop()});var toggleFlagLinks=adminModule.select("a.toggleAdminValue");var toggleFx=function(e){this.toggleAdminFlag(e.element());e.stop()}.bind(this);for(var i=0,j=toggleFlagLinks.length;i<j;i++)toggleFlagLinks[i].observe("click",toggleFx);var actionLinks=adminModule.select("a.adminUserAction");var actionFx=function(e){this.performAdminAction(e.element());e.stop()}.bind(this);for(var i=0,j=actionLinks.length;i<j;i++)actionLinks[i].observe("click",actionFx)}},toggleAdminFlag:function(linkClicked){var propertyName=
linkClicked.rel;Brainstorm.Web.Services.TenantAdmin.ToggleAdminFlag(bsCommon.getRequestToken(),this.objectType,this.id,propertyName,this.afterToggleFlag.bind(this),bsCommon.ajaxCallError,linkClicked)},afterToggleFlag:function(newValue,linkClicked){var value=linkClicked.up("td.value").down("span.value");value.innerHTML=newValue?"Yes":"No";new Effect.Highlight(value)},performAdminAction:function(linkClicked){if(linkClicked.hasClassName("running")){Effect.Shake(linkClicked,{distance:3});return}var li=
linkClicked.up("li");var status=li.down("span.status");status.innerHTML="Please wait ...";status.show();li.addClassName("running");li.removeClassName("done");linkClicked.addClassName("running");var actionName=linkClicked.rel;Brainstorm.Web.Services.TenantAdmin.ExecuteAdminAction(bsCommon.getRequestToken(),this.objectType,this.id,actionName,this.afterActionPerformed.bind(this),bsCommon.ajaxCallError,linkClicked)},afterActionPerformed:function(newValue,linkClicked){linkClicked.removeClassName("running");
var li=linkClicked.up("li");var status=li.down("span.status");li.addClassName("done");li.removeClassName("running");status.innerHTML="Done";new Effect.Highlight(status,{afterFinish:function(){status.fade({duration:1,delay:1})}})},getTitleUpdateMethod:function(){},afterTitleSave:function(newTitle){}});
BrainstormJs.Profiles.ChallengeProfile=Class.create(BrainstormJs.Profiles.BaseProfile,{challengeId:false,ideasGrid:false,ideasTabPane:false,ideasCountSpan:false,teamModule:false,tagsModule:false,observed:true,submitActionBox:false,newIdeaForm:false,existingIdeaForm:false,newDataMessage:false,initialize:function($super){if($("challengesDisabled"))return;var challengeId=$("challengeId");if(!challengeId)return;this.id=challengeId.value;this.challengeId=parseInt(challengeId.value,10);$super("challenge");
if($("isChallengeArchived"))return;this.newDataMessage=new BrainstormJs.Controls.RefreshDataMessage($("needRefreshMsg"),{onRefresh:function(){this.ideasGrid.refreshGrid()}.bind(this)});this.initializeModules();this.initializeIdeasSection();var position=Position.getWindowSize()},initializeModules:function(){this.snapshotModule=new BrainstormJs.Modules.ChallengeProfile.ChallengeSnapshotModule({profile:this});this.teamModule=new BrainstormJs.Modules.ChallengeProfile.ChallengeTeamModule({profile:this});
this.tagsModule=new BrainstormJs.Modules.ChallengeProfile.ChallengeTagsModule({profile:this})},initializeIdeasSection:function(){var challengeTabs=$("challengeIdeaTabs");this.ideasCountSpan=challengeTabs.down("a#submissionsTab_link span.label span.count");this.ideasTabPane=new BrainstormJs.Controls.TabPane(challengeTabs,{afterSwitch:this.afterIdeaTabSwitched.bind(this)});var submitIdeaLink=$("challengeIdeasSection").down("a.submitIdea");if(submitIdeaLink){var linkSubmitExisting=$("linkSubmitExisting");
linkSubmitExisting.observe("click",function(e){this.startSubmitExistingIdea();e.stop()}.bind(this));var linkCreateAndSubmit=$("linkSubmitNew");linkCreateAndSubmit.observe("click",function(e){this.startSubmitNewIdea();e.stop()}.bind(this));this.submitActionBox=new BrainstormJs.Controls.ActionBox($("ideaSubmitChoice"),{triggers:[$("challengeIdeasSection").down("a.submitIdea"),$("submitChallengeIdea")],afterOpen:this.afterSubmitBoxOpened.bind(this)})}this.ideasGrid=new BrainstormJs.Controls.Grid.ChallengeIdeasGrid(this.id,
"challengeIdeasGrid_"+this.id,{onTotalChange:this.updateIdeaGridCount.bind(this),filterAreaEl:$("challengeIdeasGrid").down("div.dataFilterArea"),onGridRefresh:function(){this.newDataMessage.hide()}.bind(this)})},afterSubmitBoxOpened:function(){var formContainer=$("ideaFormContainer");var formOptions={parentContainer:formContainer,destroyOnClose:false,afterClose:this.afterIdeaFormClose.bind(this),afterSubmitted:this.afterIdeaSubmitted.bind(this),bindOpenLinks:false,challengeId:this.challengeId};if(!this.newIdeaForm)this.newIdeaForm=
new BrainstormJs.Forms.ChallengeNewIdeaForm(Object.extend(formOptions,{customFields:BrainstormJs.Controls.CustomFields.CustomFieldHelper.convertToFormFields(BS_Challenge_SubmissionQuestions,"new")}));if(!this.existingIdeaForm)this.existingIdeaForm=new BrainstormJs.Forms.ChallengeExistingIdeaForm(Object.extend(formOptions,{choices:BS_Challenge_MyIdeas,customFields:BrainstormJs.Controls.CustomFields.CustomFieldHelper.convertToFormFields(BS_Challenge_SubmissionQuestions,"existing")}))},startSubmitExistingIdea:function(){if(!BS_Challenge_MyIdeas||
!BS_Challenge_MyIdeas.length||BS_Challenge_MyIdeas.length==0){bsCommon.alert("Oops, it looks like you don't have any ideas eligible for submission. Please use the 'Create and submit a new idea' link to submit a brand new idea.");return}this.toggleSubmitBox(false);this.existingIdeaForm.showForm()},startSubmitNewIdea:function(){this.toggleSubmitBox(false);this.newIdeaForm.showForm()},toggleSubmitBox:function(show){if(show)this.submitActionBox.show();else this.submitActionBox.hide()},afterIdeaFormClose:function(){this.toggleSubmitBox(true)},
afterIdeaSubmitted:function(jsonChallengeIdea,existingIdeasEmpty){bsCommon.showSuccess("You have successfully submitted your idea to this challenge!");this.submitActionBox.restore();bsCommon.updateTabCount(this.ideasCountSpan,1,0,1);this.newDataMessage.show();var moduleCount=$("moduleSubmissionCount");if(moduleCount)bsCommon.updateTabCount(moduleCount,1,0,1);if(existingIdeasEmpty)BS_Challenge_MyIdeas={}},updateIdeaGridCount:function(newTotal){if(this.ideasGrid.dataFilters)this.ideasGrid.dataFilters.updateRecordCount(newTotal)},
afterIdeaTabSwitched:function(selectedTab){},getTitleUpdateMethod:function($super){return Brainstorm.Web.Services.Ajax.ChangeChallengeName},afterTitleSave:function($super,newName){document.title="Brainstorm \u203a Challenge \u203a "+newName}});BrainstormPages.register(BrainstormJs.Profiles.ChallengeProfile,"/Challenge.aspx");
BrainstormJs.Profiles.IdeaProfile=Class.create(BrainstormJs.Profiles.BaseProfile,{ideaId:false,snapshotModule:false,teamModule:false,tagsModule:false,reviewSummaries:false,reviewsContainer:false,successStoryContainer:false,initialize:function($super){var ideaId=$("ideaId");var isArchived=$("isIdeaArchived");this.id=ideaId.value;this.reviewSummaries=[];$super("idea");if(isArchived)return;var approveConfirmation=$("showConfirmationOnLoad");if(approveConfirmation)bsCommon.showSuccess(approveConfirmation.innerHTML);
var bayesianAverage=parseFloat($F("bayesian_avg"));var totalRatings=parseInt($F("total_ratings"),10);var userRating=parseInt($F("user_rating"),10);var reviewSummaries=$$("div.reviewsSummary");for(var i=0,j=reviewSummaries.length;i<j;i++){var container=reviewSummaries[i];var summary=new BrainstormJs.Controls.ReviewsSummary(this,container,{bayesianAverage:bayesianAverage,totalRatings:totalRatings,userRating:userRating>0?userRating:false});this.reviewSummaries.push(summary)}var profileInfo=bsCommon.parseObjectGuid($("profileGUID").value);
this.reviewsContainer=new BrainstormJs.Controls.ReviewsContainer(this,profileInfo);this.initializeModules();var ideaPipelinesSection=$("ideaPipelinesSection");if(ideaPipelinesSection){var previewLinks=ideaPipelinesSection.select("a.showPreview");for(var i=0,j=previewLinks.length;i<j;i++){var trigger=previewLinks[i];var ajaxPane=trigger.next("div.ajaxContentPane");var workflowControl=new BrainstormJs.Controls.Evaluation.PipelineIdeaEvaluation(false,{trigger:trigger,ajaxPane:ajaxPane,dataMethod:Brainstorm.Web.Services.Ajax.GetPipelineEvaluation})}}var ideaChallengesSection=
$("ideaChallengesSection");if(ideaChallengesSection){var previewLinks=ideaChallengesSection.select("a.showPreview");for(var i=0,j=previewLinks.length;i<j;i++){var trigger=previewLinks[i];var ajaxPane=trigger.next("div.ajaxContentPane");var workflowControl=new BrainstormJs.Controls.Evaluation.ChallengeIdeaEvaluation(false,{trigger:trigger,ajaxPane:ajaxPane,dataMethod:Brainstorm.Web.Services.Ajax.GetChallengeIdeaEvaluation})}}this.successStoryContainer=new BrainstormJs.Controls.SuccessStoryContainer(profileInfo)},
addChallengeMembership:function(jsonChallengeIdea){var sectionContentElement=$("ideaChallengesSectionContent");sectionContentElement.update('"'+jsonChallengeIdea.Title+'" has been submitted to "'+jsonChallengeIdea.ChallengeName+'" &ndash; <a href="/Idea.aspx?id='+jsonChallengeIdea.IdeaId+'">Refresh</a>');sectionContentElement.addClassName("intro")},initializeModules:function(){this.snapshotModule=new BrainstormJs.Modules.Idea.IdeaSnapshotModule({profile:this});this.teamModule=new BrainstormJs.Modules.Idea.IdeaTeamModule({profile:this});
this.tagsModule=new BrainstormJs.Modules.Idea.IdeaTagsModule({profile:this})},getTitleUpdateMethod:function($super){return Brainstorm.Web.Services.IdeaTasks.EditPunchline},afterTitleSave:function($super,newPunchline){document.title="Brainstorm \u203a Idea \u203a "+newPunchline}});BrainstormPages.register(BrainstormJs.Profiles.IdeaProfile,"/Idea.aspx");
BrainstormJs.Profiles.PersonProfile=Class.create(BrainstormJs.Profiles.BaseProfile,{snapshotModule:false,bound_subscriptionUpdated:false,bound_changeSubscription:false,profileImage:false,reportsToggle:false,reportsPreview:false,reportsDetail:false,profileEditForm:false,reportFieldForm:false,imageEdit:false,apiForm:false,initialize:function($super){var personId=$("personId");if(!personId)return;this.id=personId.value;$super("person");bsCommon.wireSubscriptionCheckboxes();bsCommon.setAutoScroll($("title"));
this.reportsToggle=$("toggleReportsDetail");if(this.reportsToggle){this.reportsPreview=$("directReportPreview");this.reportsDetail=$("directReportDetail");this.reportsToggle.observe("click",function(e){this.toggleReports();e.stop()}.bind(this))}this.initializeProfile();$$(".inactive").each(function(el){new Effect.Highlight(el,{duration:1.3})});this.formContainer=$("personIntro");this.profileEditForm=new BrainstormJs.Forms.PersonProfileForm({relatedProfileImage:this.imageEdit,parentContainer:this.formContainer,
personId:this.id,destroyOnClose:false,scrollToBottom:false,openLinks:["linkEditProfile"],appearOpenLink:true});this.reportFieldForm=new BrainstormJs.Forms.PersonReportFieldForm({parentContainer:this.formContainer,personId:this.id,destroyOnClose:false,scrollToBottom:false,openLinks:["linkAdminEdit"],appearOpenLink:true})},initializeProfile:function(){this.snapshotModule=new BrainstormJs.Modules.Person.PersonSnapshotModule({profile:this});this.profileImage=$("editImage");if(this.profileImage)this.imageEdit=
new BrainstormJs.Modules.Person.PersonProfileImage({profile:this,image:this.profileImage});if($("apiKeys"))this.apiForm=new BrainstormJs.Forms.AccessKeyForm(this,{list:"apiKeys",parentContainer:"apiAccessForm-container",emptyMessage:"You have no linked applications."})},toggleReports:function(){if(!this.reportsDetail.visible()){this.reportsToggle.innerHTML="hide detail";this.reportsPreview.hide();this.reportsDetail.appear()}else{this.reportsToggle.innerHTML="show detail";this.reportsDetail.hide();
this.reportsPreview.appear()}}});BrainstormPages.register(BrainstormJs.Profiles.PersonProfile,"/Person.aspx");
BrainstormJs.Profiles.PipelineProfile=Class.create(BrainstormJs.Profiles.BaseProfile,{pipelineId:false,candidateFilterForm:false,candidateGrid:false,ideasGrid:false,ideasTabPane:false,candidateCountSpan:false,ideasCountSpan:false,teamModule:false,categoriesModule:false,savedViewsMenu:false,savedViewsList:false,savedViewsLink:false,resetViewLink:false,observed:true,newDataMessage:false,initialize:function($super){if($("pipelinesDisabled"))return;var pipelineId=$("pipelineId");if(!pipelineId)return;
this.id=pipelineId.value;$super("pipeline");if($("isPipelineArchived"))return;this.newDataMessage=new BrainstormJs.Controls.RefreshDataMessage($("needRefreshMsg"),{onRefresh:function(){this.ideasGrid.refreshGrid()}.bind(this)});this.initializeModules();this.initializeCandidateSection();this.initializeIdeasSection();var position=Position.getWindowSize()},initializeModules:function(){this.snapshotModule=new BrainstormJs.Modules.PipelineProfile.PipelineSnapshotModule({profile:this});this.teamModule=
new BrainstormJs.Modules.PipelineProfile.PipelineTeamModule({profile:this})},initializeCandidateSection:function(){var filtersDiv=$("candidateFilters");if(!filtersDiv)return;var editFiltersLink=filtersDiv.down("div.filterIntro a.editFiltersLink");if(editFiltersLink)this.candidateFilterForm=new BrainstormJs.Forms.PipelineCandidateFilterForm(this,{parentContainer:$("editFiltersFormContainer"),replaceElement:$("filterBoxContainer"),openLinks:[editFiltersLink],afterFiltersUpdated:this.updateCandidateGrid.bind(this)});
this.candidateGrid=new BrainstormJs.Controls.Grid.PipelineCandidatesGrid(this,"candidateGrid",{onTotalChange:this.updateCandidateCount.bind(this)});this.initAddAll()},initializeIdeasSection:function(){var pipelineTabs=$("pipelineIdeaTabs");this.candidateCountSpan=pipelineTabs.down("a#candidatesTab_link span.label span.count");this.ideasCountSpan=pipelineTabs.down("a#pipelinesTab_link span.label span.count");this.ideasTabPane=new BrainstormJs.Controls.TabPane(pipelineTabs,{afterSwitch:this.afterIdeaTabSwitched.bind(this)});
this.ideasGrid=new BrainstormJs.Controls.Grid.PipelineIdeasGrid(this.id,"pipelineIdeasGrid_"+this.id,{onTotalChange:this.updateIdeaGridCount.bind(this),filterAreaEl:$("pipelineIdeasGrid").down("div.dataFilterArea"),onGridRefresh:function(){this.newDataMessage.hide()}.bind(this)})},initAddAll:function(){this.addAllLink=$("addAllLink");if(this.addAllLink){this.addAllSection=this.addAllSection||this.addAllLink.up(2);this.loading=this.loading||this.addAllLink.up(1).next();this.addAllText=this.addAllText||
$("addAllText");if(this.observed){this.addAllLink.observe("click",this.onAddAllClick.bind(this));this.observed=true}var noResults=$("candidateGridWrapper").down(".noResults");if(noResults==undefined){if(!this.addAllSection.visible()&&$("candidateGridWrapper").visible())this.addAllSection.blindDown()}else if(this.addAllSection.visible())this.addAllSection.blindUp()}},onAddAllClick:function(e){var numCandidates=this.candidateCountSpan.innerHTML;bsCommon.confirm({title:"Alert",text:"Are you sure that you would like to add these <u>"+
numCandidates+"</u> ideas to your pipeline?",width:450,confirmText:"Yes, add them!",cancelText:"No, leave them.",onConfirm:this.onAddAllCommit.bind(this)})},onAddAllCommit:function(){this.addAllText.blindUp({afterFinish:function(){this.loading.blindDown({afterFinish:function(){Brainstorm.Web.Services.Ajax.AddAllCandidates(this.id,this.afterAddAllCandidates.bind(this),bsCommon.ajaxCallError)}.bind(this)})}.bind(this)})},afterAddAllCandidates:function(numAdded){if(this.addAllSection){this.candidateGrid.resetFilters();
this.addAllSection.fade();this.addAllText.appear();this.loading.hide()}if(numAdded>0){bsCommon.updateTabCount(this.ideasCountSpan,numAdded,0,1);this.showStaleIdeasMessage()}},afterIdeaApproved:function(){bsCommon.updateTabCount(this.ideasCountSpan,1,0,1);bsCommon.updateTabCount(this.candidateCountSpan,-1,0,0);this.showStaleIdeasMessage()},showStaleIdeasMessage:function(){this.newDataMessage.show(false)},updateCandidateCount:function(newTotal){bsCommon.updateTabCount(this.candidateCountSpan,false,
newTotal,1)},updateIdeaGridCount:function(newTotal){if(this.ideasGrid.dataFilters)this.ideasGrid.dataFilters.updateRecordCount(newTotal)},afterIdeaTabSwitched:function(selectedTab){if(selectedTab.id=="pipelinesTab")this.newDataMessage.pulsateIf(this.ideaTabStale);else if(selectedTab.id=="candidatesTab");},updateCandidateGrid:function(){this.candidateGrid.resetFilters();this.initAddAll.delay(2)},getTitleUpdateMethod:function($super){return Brainstorm.Web.Services.Ajax.ChangePipelineName},afterTitleSave:function($super,
newName){document.title="Brainstorm \u203a Pipeline \u203a "+newName}});BrainstormPages.register(BrainstormJs.Profiles.PipelineProfile,"/Pipeline.aspx");BrainstormJs.Profiles.TagProfile=Class.create(BrainstormJs.Profiles.BaseProfile,{relatedTagsModule:false,initialize:function($super){$super("tag");this.object={Id:bsCommon.getUrlParam("tag")};this.initializeProfile()},initializeProfile:function(){this.relatedTagsModule=new BrainstormJs.Modules.Tag.RelatedTagsModule({profile:this,container:"moduleTagRelated"})}});
BrainstormPages.register(BrainstormJs.Profiles.TagProfile,"/Tag.aspx");
BrainstormJs.Profiles.TenantProfile=Class.create(BrainstormJs.Profiles.BaseProfile,{stageForm:false,businessUnitForm:false,usersGrid:false,apiForm:false,initialize:function($super){$super("tenant");this.stageForm=new BrainstormJs.Forms.TenantProfile.IdeaStageForm(this,{list:"ideaStages",parentContainer:"stageForm-container",emptyMessage:"There are no idea stages defined yet."});this.businessUnitForm=new BrainstormJs.Forms.TenantProfile.BusinessUnitForm(this,{list:"businessAreas",parentContainer:"bizUnitForm-container",
emptyMessage:"There are no "+$F("BS_Config_AreaName").toLowerCase()+" items defined yet."});this.tenantAdminsForm=new BrainstormJs.Forms.TenantProfile.TenantAdminsForm(this,{list:"tenantAdmins",parentContainer:"adminsForm-container",emptyMessage:"There are no administrators set.",property:"IsTenantAdmin",objectName:"admin"});this.tenantHelpersForm=new BrainstormJs.Forms.TenantProfile.TenantAdminsForm(this,{list:"tenantHelpers",parentContainer:"helpersForm-container",emptyMessage:"There are no stuck helpers set.",
property:"IsStuckHelper",objectName:"stuck helper"});var generalSettingsForm=new BrainstormJs.Admin.Forms.Tenant.GeneralSettingsForm("tenantGeneralForm");var userRegistrationForm=new BrainstormJs.Admin.Forms.Tenant.UserRegistrationForm("tenantSignupForm");var emailSettingsForm=new BrainstormJs.Admin.Forms.Tenant.EmailSettingsForm("tenantEmailsForm");var pipelineSettingsForm=new BrainstormJs.Admin.Forms.Tenant.PipelineSettingsForm("tenantPipelinesForm");var challengeSettingsForm=new BrainstormJs.Admin.Forms.Tenant.ChallengeSettingsForm("tenantChallengesForm");
var miscSettingsForm=new BrainstormJs.Admin.Forms.Tenant.MiscSettingsForm("tenantMiscForm");var userSearchForm=new BrainstormJs.Admin.Forms.Tenant.UserSearchForm("tenantUserSearchForm");if($("tenantDirectoryImportForm"))var userSearchForm=new BrainstormJs.Admin.Forms.Tenant.DirectoryImportForm("tenantDirectoryImportForm");if($("tenantBulkUserForm"))var bulkImportForm=new BrainstormJs.Admin.Forms.Tenant.BulkUserImportForm("tenantBulkUserForm");if($("tenantBulkDeactivateForm"))var bulkDeacForm=new BrainstormJs.Admin.Forms.Tenant.BulkDeactivateForm("tenantBulkDeactivateForm");
var profileInfoSettingsForm=new BrainstormJs.Admin.Forms.Tenant.ProfileInfoSettingsForm("profileInfoSettingsForm");this.globalTagsUpdater=new BrainstormJs.Controls.TagUpdater({profile:{objectType:"Tenant",id:0},sectionId:"globalTagsUpdater",tagCategory:Brainstorm.Model.Enums.TagCategory.Global,contentFetchMethod:Brainstorm.Web.Services.TenantAdmin.LoadGlobalTagCloud,cloudContainer:$("globalTagCloud"),editTitle:"Edit global tags"});$("linkLoadUsersGrid").observe("click",function(e){this.loadUsersGrid(e.element());
e.stop()}.bind(this));$("linkLoadAllTags").observe("click",function(e){this.loadAllTags(e.element());e.stop()}.bind(this));$("linkLoadAllTagRelations").observe("click",function(e){this.loadAllTagRelations(e.element());e.stop()}.bind(this));$("getRecommendationsByActivity").observe("click",function(e){this.loadAllRecommendations(e.element(),"byActivity");e.stop()}.bind(this));$("getRecommendationsByAlternates").observe("click",function(e){this.loadAllRecommendations(e.element(),"byNumAlternates");
e.stop()}.bind(this));$("lnkArchivedIdeaCount").observe("click",function(e){this.scrollToArchiveList("archivedIdeas");e.stop()}.bind(this));$("lnkArchivedChallengeCount").observe("click",function(e){this.scrollToArchiveList("archivedChallenges");e.stop()}.bind(this));$("lnkArchivedPipelineCount").observe("click",function(e){this.scrollToArchiveList("archivedPipelines");e.stop()}.bind(this));this.wireBackToTopLinks();this.wireArchiveList($("archivedIdeas"),"idea");this.wireArchiveList($("archivedChallenges"),
"challenge");this.wireArchiveList($("archivedPipelines"),"pipeline");var loadManuallyImportedUsersLink=$("linkLoadManuallyImportedUsers");if(loadManuallyImportedUsersLink)loadManuallyImportedUsersLink.observe("click",function(e){this.loadManuallyImportedUsers(e.element());e.stop()}.bind(this));this.initializeModules()},initializeModules:function(){this.apiForm=new BrainstormJs.Forms.TenantProfile.ApiAccessForm(this,{list:"apiKeys",parentContainer:"apiAccessForm-container",emptyMessage:"There are no active API keys."})},
loadUsersGrid:function(linkClicked){if(linkClicked.hasClassName("loading"))return;linkClicked.innerHTML="Please Wait ...";linkClicked.addClassName("loading");this.peopleGrid=new BrainstormJs.Controls.Grid.GenericGrid(Brainstorm.Model.Enums.GridType.UserAdminGrid,"allUsersGrid",{lazyInitialize:true});this.peopleGrid.changePage({pageNum:1,refreshPager:true,afterFinish:function(){this.wireUsersGrid(linkClicked)}.bind(this)})},wireUsersGrid:function(linkClicked){window.setTimeout(function(){linkClicked.blindUp({duration:0.25});
$("allUsersGrid").blindDown({duration:0.5})}.bind(this),1)},scrollToArchiveList:function(objectId){bsCommon.scrollTo($(objectId),{offset:-10})},loadManuallyImportedUsers:function(linkClicked){if(linkClicked.hasClassName("loading"))return;linkClicked.innerHTML="Please Wait ...";linkClicked.addClassName("loading");Brainstorm.Web.Services.TenantAdmin.LoadManuallyImportedList(this.showManuallyImportedUsers.bind(this),bsCommon.ajaxCallError,linkClicked)},showManuallyImportedUsers:function(jsonDomElement,
linkClicked){var container=$("manuallyImportedList");linkClicked.hide();if(container)container.innerHTML=jsonDomElement.HTML},loadAllTags:function(linkClicked){if(linkClicked.hasClassName("loading"))return;linkClicked.innerHTML="Please Wait ...";linkClicked.addClassName("loading");Brainstorm.Web.Services.TenantAdmin.GetAllTagsList(this.wireAllTagsList.bind(this),bsCommon.ajaxCallError,linkClicked)},loadAllRecommendations:function(linkClicked,sortKey){if(linkClicked.hasClassName("loading"))return;
var allTagsList=$("allTagRecommendationsList");if(!allTagsList.visible())allTagsList.appear();allTagsList.innerHTML="Loading. Please wait...";linkClicked.disabled=true;Brainstorm.Web.Services.TenantAdmin.GetTagConsolidationRecommendations(sortKey,this.wireTagConsolidationList.bind(this),bsCommon.ajaxCallError,linkClicked)},wireBackToTopLinks:function(){var backToTopLinks=$$("a.backToTop");var fxBackToTopLink=function(e){this.scrollToArchiveList("archiveListSummary");e.stop()}.bind(this);if(backToTopLinks)for(var i=
0;i<backToTopLinks.length;++i)backToTopLinks[i].observe("click",fxBackToTopLink)},wireTagConsolidationList:function(listHtml,linkClicked){var allTagsList=$("allTagRecommendationsList");allTagsList.innerHTML=listHtml.HTML;var fxConsolidateLink=function(e){this.consolidateTag(e.element())}.bind(this);var fxShowConsolidateEl=function(event){var recoCell=event.findElement("td");if(recoCell){var consolidateTrigger=recoCell.down(".consolidateTag");if(consolidateTrigger){if(!consolidateTrigger.hasClassName("wired")){consolidateTrigger.observe("click",
fxConsolidateLink);consolidateTrigger.addClassName("wired")}consolidateTrigger.setStyle({visibility:"visible"})}}};var fxHideConsolidateEl=function(event){var recoCell=event.findElement("td");if(recoCell)recoCell.down(".consolidateTag").setStyle({visibility:"hidden"})};var recommendations=allTagsList.select("td.nameCol");for(var i=0,j=recommendations.length;i<j;i++){recommendations[i].observe("mouseover",fxShowConsolidateEl);recommendations[i].observe("mouseout",fxHideConsolidateEl)}window.setTimeout(function(){linkClicked.disabled=
false;allTagsList.show()},1)},wireAllTagsList:function(listHtml,linkClicked){var allTagsList=$("allTagsList");allTagsList.innerHTML=listHtml.HTML;var renameLinks=allTagsList.select("a.renameTag");var fxRenameLink=function(e){this.renameTag(e.element());e.stop()}.bind(this);for(var i=0,j=renameLinks.length;i<j;i++)renameLinks[i].observe("click",fxRenameLink);var deleteLinks=allTagsList.select("a.deleteTag");var fxDeleteLink=function(e){this.deleteTag(e.element());e.stop()}.bind(this);for(var i=0,j=
deleteLinks.length;i<j;i++)deleteLinks[i].observe("click",fxDeleteLink);window.setTimeout(function(){linkClicked.hide();allTagsList.show()},1)},renameTag:function(linkClicked){var oldName=linkClicked.rel;bsCommon.prompt({title:"Rename tag",text:"Enter new tag name:",width:450,currentValue:oldName,maxLength:95,confirmText:"Submit",cancelText:"Cancel",onConfirm:function(newName){this.onCommitRenameTag(oldName,newName,linkClicked)}.bind(this)})},consolidateTag:function(clickedEl){var triggerElem=$(clickedEl);
triggerElem.disable();var recommendationElem=triggerElem.up();var favoredTerm=recommendationElem.down(".favoredTerm");var similarTerms=recommendationElem.select(".similarTerm");var consolidationForm=new BrainstormJs.Forms.TenantProfile.TagConsolidationForm(this,{similarTags:similarTerms,favoredTag:favoredTerm.innerHTML,parentContainer:recommendationElem,afterClose:function(){var consolidateButton=recommendationElem.down(".consolidateTag");if(consolidateButton)consolidateButton.enable()}});consolidationForm.showForm({})},
wireArchiveList:function(allArchivedList,profileType){var fxUnarchiveLink=function(e){this.unarchiveItem(profileType,e.element())}.bind(this);var fxShowUnarchiveEl=function(event){var recoCell=event.findElement("td");if(recoCell){var unarchiveTrigger=recoCell.down(".unarchiveItem");if(unarchiveTrigger){if(!unarchiveTrigger.hasClassName("wired")){unarchiveTrigger.observe("click",fxUnarchiveLink);unarchiveTrigger.addClassName("wired")}unarchiveTrigger.setStyle({visibility:"visible"})}}};var fxHideUnarchiveEl=
function(event){var recoCell=event.findElement("td");if(recoCell)recoCell.down(".unarchiveItem").setStyle({visibility:"hidden"})};var recommendations=allArchivedList.select("td.nameCol");for(var i=0,j=recommendations.length;i<j;i++){recommendations[i].observe("mouseover",fxShowUnarchiveEl);recommendations[i].observe("mouseout",fxHideUnarchiveEl)}},unarchiveItem:function(profileType,linkClicked){var profileId=linkClicked.readAttribute("data-id");Brainstorm.Web.Services.TenantAdmin.TenantAdminToggleAdminFlag(profileType,
profileId,"Archived",this.afterUnarchiveItem.bind(this),bsCommon.ajaxCallError,{profileType:profileType,name:linkClicked.name,unarchiveLink:linkClicked})},afterUnarchiveItem:function(message,state){bsCommon.showSuccess("Successfully unarchived "+state.profileType+" '"+state.name+"'.");var row=state.unarchiveLink.up("tr");new Effect.Highlight(row);row.addClassName("removed");state.unarchiveLink.remove()},onCommitRenameTag:function(oldName,newName,linkClicked){Brainstorm.Web.Services.TenantAdmin.RenameTags(oldName,
newName,this.afterRenameTags.bind(this),bsCommon.ajaxCallError,{linkClicked:linkClicked,newName:newName})},afterRenameTags:function(message,state){var row=state.linkClicked.up("tr");var nameCol=row.down("td.nameCol");var actionsCol=row.down("td.actionsCol");row.addClassName("renamed");nameCol.innerHTML="<span>"+state.newName+"</span>";actionsCol.innerHTML="";new Effect.Highlight(nameCol.down("span"));bsCommon.showSuccess(message)},deleteTag:function(linkClicked){var tagName=linkClicked.rel;bsCommon.confirm({title:"Removal Confirmation",
text:"Are you sure you would like to completely remove all occurrences of the tag '"+tagName+"' from Brainstorm?",width:450,confirmText:"Yes, delete it!",cancelText:"No, keep it.",onConfirm:function(){this.onConfirmDeleteTag(tagName,linkClicked)}.bind(this)})},onConfirmDeleteTag:function(tagName,linkClicked){Brainstorm.Web.Services.TenantAdmin.DeleteTag(tagName,this.afterDeleteTag.bind(this),bsCommon.ajaxCallError,{tagName:tagName,deleteLink:linkClicked})},afterDeleteTag:function(tagsRemoved,state){bsCommon.showSuccess("Successfully removed "+
tagsRemoved+" instances of the tag '"+state.tagName+"'.");state.deleteLink.up("tr").addClassName("removed")},loadAllTagRelations:function(linkClicked){if(linkClicked.hasClassName("loading"))return;linkClicked.innerHTML="Please Wait ...";linkClicked.addClassName("loading");Brainstorm.Web.Services.TenantAdmin.GetAllTagRelations(this.wireAllTagRelationsList.bind(this),bsCommon.ajaxCallError,linkClicked)},wireAllTagRelationsList:function(listHtml,linkClicked){var allRelationsList=$("allTagRelationsList");
allRelationsList.innerHTML=listHtml.HTML;linkClicked.hide();allRelationsList.show();var deleteLinks=allRelationsList.select("a.delete");var fxDeleteLink=function(e){this.deleteRelation(e.element());e.stop()}.bind(this);for(var i=0,j=deleteLinks.length;i<j;i++)deleteLinks[i].observe("click",fxDeleteLink)},deleteRelation:function(linkClicked){var relationId=linkClicked.readAttribute("data-id");bsCommon.confirm({title:"Removal Confirmation",text:"Are you sure you would like to completely remove this tag suggestion?",
width:450,confirmText:"Yes, delete it!",cancelText:"No, keep it.",onConfirm:function(){this.onConfirmDeleteRelation(relationId,linkClicked)}.bind(this)})},onConfirmDeleteRelation:function(relationId,linkClicked){Brainstorm.Web.Services.TenantAdmin.DeleteTagRelation(relationId,this.afterDeleteRelation.bind(this),bsCommon.ajaxCallError,{relationId:relationId,deleteLink:linkClicked})},afterDeleteRelation:function(success,state){if(success){bsCommon.showSuccess("Successfully removed tag relation ...");
state.deleteLink.up("tr").addClassName("removed")}else bsCommon.alert("There was an error while removing this tag relation. Please refresh the page and try again.")}});BrainstormPages.register(BrainstormJs.Profiles.TenantProfile,"/Settings.aspx");
window.Bridge||(Bridge={}),function(){var a=Array.prototype.slice,b=Object.prototype.toString;Bridge.Shared={"break":{},Array:{_each:function(a,b){for(var c=0,d=a.length;c<d;c++)b(a[c])},each:function(a,b,c){var d=0;try{this._each(a,function(a){b.call(c,a,d++)})}catch(e){if(e!=Bridge.Shared["break"])throw e;}}},Function:{bind:function(b,c){var d=a.call(arguments,2);return function(){return b.apply(c,d.concat(a.call(arguments)))}},bindAsEventListener:function(b,c){return function(d){return b.apply(c,
[d||window.event].concat(a.call(arguments)))}},wrap:function(b,c){var d=b;return function(){var b=[Bridge.Shared.Function.bind(d,this)].concat(a.call(arguments));return c.apply(this,b)}},curry:function(b){if(arguments.length===1)return b;var c=a.call(arguments,1);return function(){return b.apply(this,c.concat(a.call(arguments)))}},delay:function(b,c){var d=a.call(arguments,2);return setTimeout(function(){return b.apply(b,d)},c*1E3)},defer:function(b){return this.delay.apply(this,[b,0.01].concat(a.call(arguments,
1)))}},Object:{extend:function(a,b){for(var c in b)a[c]=b[c];return a},clone:function(a){return this.extend({},a)},isBoolean:function(a){return b.call(a)=="[object Boolean]"}},String:{capitalize:function(a){return a.charAt(0).toUpperCase()+a.substring(1).toLowerCase()},times:function(a,b){return b<1?"":Array(b+1).join(a)},strip:function(a){return a.replace(/^\s+/,"").replace(/\s+$/,"")}}}}();window.Bridge||(Bridge={});
Object.extend(Bridge,function(){function h(a){if(a.constructor&&a.constructor==i)return a;a=new i(a);return a.source&&a}var c=window.Array.prototype.slice,d=window.Object,f=d.extend({isArray:d.isArray,isFunction:d.isFunction,isNumber:d.isNumber,isString:d.isString,isUndefined:d.isUndefined,isElement:d.isElement,keys:d.keys},Bridge.Shared.Object),l=window.$,m=window.$$,e=window.Element,i=Class.create({initialize:function(a){this.source=l(a)},addClassName:function(a){this.source.addClassName(a);return this},
removeClassName:function(a){this.source.removeClassName(a);return this},getWidth:function(){return this.source.getWidth()},getHeight:function(){return this.source.getHeight()},getDimensions:function(){return this.source.getDimensions()},cumulativeOffset:function(){return this.source.cumulativeOffset()},cumulativeScrollOffset:function(){return this.source.cumulativeScrollOffset()},hide:function(){this.source.hide();return this},show:function(){this.source.show();return this},toggle:function(){this.source.toggle();
return this},remove:function(){this.source.remove()},insert:function(a){var b={};if(a.source||f.isElement(a)||f.isString(a))b.bottom=a.source||a;else for(var c in a)b[c]=a[c].source||a[c];this.source.insert(b);return this},update:function(a){this.source.update(a.source||a);return this},writeAttribute:function(a){this.source.writeAttribute(a);return this},setStyle:function(){e.setStyle.apply(this,[this.source].concat(c.call(arguments)));return this},getStyle:function(){return e.getStyle.apply(this,
[this.source].concat(c.call(arguments)))},setOpacity:function(a){this.source.setOpacity(a);return this},select:function(a){a=this.source.select(a);return new k(a)},match:function(a){return this.source.match(a)},up:function(){return e.up.apply(this,[this.source].concat(c.call(arguments)))},down:function(){return e.down.apply(this,[this.source].concat(c.call(arguments)))},previous:function(){return e.previous.apply(this,[this.source].concat(c.call(arguments)))},next:function(){return e.next.apply(this,
[this.source].concat(c.call(arguments)))},store:function(a,b){this.source.store(a,b);return this},retrieve:function(a){return this.source.retrieve(a)},eliminate:function(a){this.store(a,null);return this},observe:function(){var a=[this.source].concat(c.call(arguments));e.observe.apply(null,a);return this},stopObserving:function(){var a=[this.source].concat(c.call(arguments));e.stopObserving.apply(null,a);return this}}),k=Class.create({initialize:function(a){var b=[],a=f.isArray(a)?a:m(a);g._each(a,
function(a){b.push(new i(a))});this.source=b},invoke:function(){var a=c.call(arguments),b=a.shift();g._each(this.source,function(c){c[b].apply(c,a)});return this},each:function(a,b){var c=0;g._each(this.source,function(d){a.call(b,d,c++)});return this}}),g=f.extend({find:function(a,b){return a.find(b)},without:function(a,b){return a.without(b)},include:function(a,b){return a.include(b)}},Bridge.Shared.Array),j=window.Event,d=f.extend({observe:function(a){var a=h(a),b=[a.source].concat(c.call(arguments,
1));j.observe.apply(null,b)},stopObserving:function(a){var a=h(a),b=[a.source].concat(c.call(arguments,1));j.stopObserving.apply(null,b)}},j);return{Array:g,Ajax:Ajax,each:g.each,_each:g._each,Element:function(a,b){b=b||{};return h(document.createElement(a)).writeAttribute(b)},Event:d,Function:Bridge.Shared.Function,String:Bridge.Shared.String,Object:f,domloaded:function(a){document.loaded?a.call(document):document.observe("dom:loaded",a)},$:h,$$:function(a){return new k(a)},emptyFunction:Prototype.emptyFunction,
K:Prototype.K,Viewport:document.viewport}}(Bridge));
(function(){window.Bridge||(window.Bridge={});var a=window.Bridge,b={Version:"1.1.2",options:{adapter:"auto",path:!1},Framework:{Prototype:{included:!!window.Prototype&&Prototype.Version,required:"1.7"},jQuery:{included:!!window.jQuery&&jQuery.fn.jquery,required:"1.5"}},insertScript:function(a){try{document.write("<script type='text/javascript' src='"+a+"'><\/script>")}catch(b){var c=document.head||document.getElementsByTagName("head")[0],d=document.createElement("script");d.type="text/javascript",
d.src=a,c.appendChild(d)}},start:function(){function e(a,b){return d(a)>=d(b)}function d(a){var b=a.match(c),d=b&&b[1]&&b[1].split(".")||[],e=0;for(var f=0,g=d.length;f<g;f++)e+=parseInt(d[f]*Math.pow(10,6-f*2));return b&&b[3]?e-1:e}var c=/^(\d+(\.?\d+){0,3})([_-]+[A-Za-z0-9]+)?/;if(a.options)for(var f in a.options)b.options[f]=a.options[f];var g=this.options.adapter=="auto";if(g||!g&&this.Framework[this.options.adapter]&&!this.Framework[this.options.adapter].included){this.options.adapter=null;for(var h in this.Framework){var i=
this.Framework[h];i.included&&e(i.included,i.required)&&(this.options.adapter=h)}if(!this.options.adapter||this.options.adapter=="auto"){var j=[];for(h in this.Framework)j.push(h+" >= "+this.Framework[h].required);var k=j.join(", "),l=k.lastIndexOf(", ");l&&(k=k.substring(0,l)+" or "+k.substring(l+2)),alert("BridgeJS requires "+k+" included before bridge.js")}}if(this.options.path)this.path=this.options.path||"",this.path.substr(this.path.length-1)!="/"&&(this.path+="/");else{var m=document.getElementsByTagName("script"),
n=/bridge([\w\d-_.]+)?\.js(.*)/;for(var o=0,p=m.length;o<p;o++){var q=m[o];q.src.match(n)&&(this.path=q.src.replace(n,""))}}a.Shared||this.insertScript(this.path+"adapters/shared.js"),a.$||this.insertScript(this.path+"adapters/"+this.options.adapter.toLowerCase()+".js")}};for(var c in b)a[c]=b[c];a.start()})();
Date.CultureInfo={name:"en-US",englishName:"English (United States)",nativeName:"English (United States)",dayNames:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],abbreviatedDayNames:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],shortestDayNames:["Su","Mo","Tu","We","Th","Fr","Sa"],firstLetterDayNames:["S","M","T","W","T","F","S"],monthNames:["January","February","March","April","May","June","July","August","September","October","November","December"],abbreviatedMonthNames:["Jan",
"Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],amDesignator:"AM",pmDesignator:"PM",firstDayOfWeek:0,twoDigitYearMax:2029,dateElementOrder:"mdy",formatPatterns:{shortDate:"M/d/yyyy",longDate:"dddd, MMMM dd, yyyy",shortTime:"h:mm tt",longTime:"h:mm:ss tt",fullDateTime:"dddd, MMMM dd, yyyy h:mm:ss tt",sortableDateTime:"yyyy-MM-ddTHH:mm:ss",universalSortableDateTime:"yyyy-MM-dd HH:mm:ssZ",rfc1123:"ddd, dd MMM yyyy HH:mm:ss GMT",monthDay:"MMMM dd",yearMonth:"MMMM, yyyy"},regexPatterns:{jan:/^jan(uary)?/i,
feb:/^feb(ruary)?/i,mar:/^mar(ch)?/i,apr:/^apr(il)?/i,may:/^may/i,jun:/^jun(e)?/i,jul:/^jul(y)?/i,aug:/^aug(ust)?/i,sep:/^sep(t(ember)?)?/i,oct:/^oct(ober)?/i,nov:/^nov(ember)?/i,dec:/^dec(ember)?/i,sun:/^su(n(day)?)?/i,mon:/^mo(n(day)?)?/i,tue:/^tu(e(s(day)?)?)?/i,wed:/^we(d(nesday)?)?/i,thu:/^th(u(r(s(day)?)?)?)?/i,fri:/^fr(i(day)?)?/i,sat:/^sa(t(urday)?)?/i,future:/^next/i,past:/^last|past|prev(ious)?/i,add:/^(\+|after|from)/i,subtract:/^(\-|before|ago)/i,yesterday:/^yesterday/i,today:/^t(oday)?/i,
tomorrow:/^tomorrow/i,now:/^n(ow)?/i,millisecond:/^ms|milli(second)?s?/i,second:/^sec(ond)?s?/i,minute:/^min(ute)?s?/i,hour:/^h(ou)?rs?/i,week:/^w(ee)?k/i,month:/^m(o(nth)?s?)?/i,day:/^d(ays?)?/i,year:/^y((ea)?rs?)?/i,shortMeridian:/^(a|p)/i,longMeridian:/^(a\.?m?\.?|p\.?m?\.?)/i,timezone:/^((e(s|d)t|c(s|d)t|m(s|d)t|p(s|d)t)|((gmt)?\s*(\+|\-)\s*\d\d\d\d?)|gmt)/i,ordinalSuffix:/^\s*(st|nd|rd|th)/i,timeContext:/^\s*(\:|a|p)/i},abbreviatedTimeZoneStandard:{GMT:"-000",EST:"-0400",CST:"-0500",MST:"-0600",
PST:"-0700"},abbreviatedTimeZoneDST:{GMT:"-000",EDT:"-0500",CDT:"-0600",MDT:"-0700",PDT:"-0800"}};Date.getMonthNumberFromName=function(name){var n=Date.CultureInfo.monthNames,m=Date.CultureInfo.abbreviatedMonthNames,s=name.toLowerCase();for(var i=0;i<n.length;i++)if(n[i].toLowerCase()==s||m[i].toLowerCase()==s)return i;return-1};
Date.getDayNumberFromName=function(name){var n=Date.CultureInfo.dayNames,m=Date.CultureInfo.abbreviatedDayNames,o=Date.CultureInfo.shortestDayNames,s=name.toLowerCase();for(var i=0;i<n.length;i++)if(n[i].toLowerCase()==s||m[i].toLowerCase()==s)return i;return-1};Date.isLeapYear=function(year){return year%4===0&&year%100!==0||year%400===0};Date.getDaysInMonth=function(year,month){return[31,Date.isLeapYear(year)?29:28,31,30,31,30,31,31,30,31,30,31][month]};
Date.getTimezoneOffset=function(s,dst){return dst||false?Date.CultureInfo.abbreviatedTimeZoneDST[s.toUpperCase()]:Date.CultureInfo.abbreviatedTimeZoneStandard[s.toUpperCase()]};Date.getTimezoneAbbreviation=function(offset,dst){var n=dst||false?Date.CultureInfo.abbreviatedTimeZoneDST:Date.CultureInfo.abbreviatedTimeZoneStandard,p;for(p in n)if(n[p]===offset)return p;return null};Date.prototype.clone=function(){return new Date(this.getTime())};
Date.prototype.compareTo=function(date){if(isNaN(this))throw new Error(this);if(date instanceof Date&&!isNaN(date))return this>date?1:this<date?-1:0;else throw new TypeError(date);};Date.prototype.equals=function(date){return this.compareTo(date)===0};Date.prototype.between=function(start,end){var t=this.getTime();return t>=start.getTime()&&t<=end.getTime()};Date.prototype.addMilliseconds=function(value){this.setMilliseconds(this.getMilliseconds()+value);return this};
Date.prototype.addSeconds=function(value){return this.addMilliseconds(value*1E3)};Date.prototype.addMinutes=function(value){return this.addMilliseconds(value*6E4)};Date.prototype.addHours=function(value){return this.addMilliseconds(value*36E5)};Date.prototype.addDays=function(value){return this.addMilliseconds(value*864E5)};Date.prototype.addWeeks=function(value){return this.addMilliseconds(value*6048E5)};
Date.prototype.addMonths=function(value){var n=this.getDate();this.setDate(1);this.setMonth(this.getMonth()+value);this.setDate(Math.min(n,this.getDaysInMonth()));return this};Date.prototype.addYears=function(value){return this.addMonths(value*12)};
Date.prototype.add=function(config){if(typeof config=="number"){this._orient=config;return this}var x=config;if(x.millisecond||x.milliseconds)this.addMilliseconds(x.millisecond||x.milliseconds);if(x.second||x.seconds)this.addSeconds(x.second||x.seconds);if(x.minute||x.minutes)this.addMinutes(x.minute||x.minutes);if(x.hour||x.hours)this.addHours(x.hour||x.hours);if(x.month||x.months)this.addMonths(x.month||x.months);if(x.year||x.years)this.addYears(x.year||x.years);if(x.day||x.days)this.addDays(x.day||
x.days);return this};Date._validate=function(value,min,max,name){if(typeof value!="number")throw new TypeError(value+" is not a Number.");else if(value<min||value>max)throw new RangeError(value+" is not a valid value for "+name+".");return true};Date.validateMillisecond=function(n){return Date._validate(n,0,999,"milliseconds")};Date.validateSecond=function(n){return Date._validate(n,0,59,"seconds")};Date.validateMinute=function(n){return Date._validate(n,0,59,"minutes")};
Date.validateHour=function(n){return Date._validate(n,0,23,"hours")};Date.validateDay=function(n,year,month){return Date._validate(n,1,Date.getDaysInMonth(year,month),"days")};Date.validateMonth=function(n){return Date._validate(n,0,11,"months")};Date.validateYear=function(n){return Date._validate(n,1,9999,"seconds")};
Date.prototype.set=function(config){var x=config;if(!x.millisecond&&x.millisecond!==0)x.millisecond=-1;if(!x.second&&x.second!==0)x.second=-1;if(!x.minute&&x.minute!==0)x.minute=-1;if(!x.hour&&x.hour!==0)x.hour=-1;if(!x.day&&x.day!==0)x.day=-1;if(!x.month&&x.month!==0)x.month=-1;if(!x.year&&x.year!==0)x.year=-1;if(x.millisecond!=-1&&Date.validateMillisecond(x.millisecond))this.addMilliseconds(x.millisecond-this.getMilliseconds());if(x.second!=-1&&Date.validateSecond(x.second))this.addSeconds(x.second-
this.getSeconds());if(x.minute!=-1&&Date.validateMinute(x.minute))this.addMinutes(x.minute-this.getMinutes());if(x.hour!=-1&&Date.validateHour(x.hour))this.addHours(x.hour-this.getHours());if(x.month!==-1&&Date.validateMonth(x.month))this.addMonths(x.month-this.getMonth());if(x.year!=-1&&Date.validateYear(x.year))this.addYears(x.year-this.getFullYear());if(x.day!=-1&&Date.validateDay(x.day,this.getFullYear(),this.getMonth()))this.addDays(x.day-this.getDate());if(x.timezone)this.setTimezone(x.timezone);
if(x.timezoneOffset)this.setTimezoneOffset(x.timezoneOffset);return this};Date.prototype.clearTime=function(){this.setHours(0);this.setMinutes(0);this.setSeconds(0);this.setMilliseconds(0);return this};Date.prototype.isLeapYear=function(){var y=this.getFullYear();return y%4===0&&y%100!==0||y%400===0};Date.prototype.isWeekday=function(){return!(this.is().sat()||this.is().sun())};Date.prototype.getDaysInMonth=function(){return Date.getDaysInMonth(this.getFullYear(),this.getMonth())};
Date.prototype.moveToFirstDayOfMonth=function(){return this.set({day:1})};Date.prototype.moveToLastDayOfMonth=function(){return this.set({day:this.getDaysInMonth()})};Date.prototype.moveToDayOfWeek=function(day,orient){var diff=(day-this.getDay()+7*(orient||+1))%7;return this.addDays(diff===0?diff+=7*(orient||+1):diff)};Date.prototype.moveToMonth=function(month,orient){var diff=(month-this.getMonth()+12*(orient||+1))%12;return this.addMonths(diff===0?diff+=12*(orient||+1):diff)};
Date.prototype.getDayOfYear=function(){return Math.floor((this-new Date(this.getFullYear(),0,1))/864E5)};
Date.prototype.getWeekOfYear=function(firstDayOfWeek){var y=this.getFullYear(),m=this.getMonth(),d=this.getDate();var dow=firstDayOfWeek||Date.CultureInfo.firstDayOfWeek;var offset=7+1-(new Date(y,0,1)).getDay();if(offset==8)offset=1;var daynum=(Date.UTC(y,m,d,0,0,0)-Date.UTC(y,0,1,0,0,0))/864E5+1;var w=Math.floor((daynum-offset+7)/7);if(w===dow){y--;var prevOffset=7+1-(new Date(y,0,1)).getDay();if(prevOffset==2||prevOffset==8)w=53;else w=52}return w};
Date.prototype.isDST=function(){console.log("isDST");return this.toString().match(/(E|C|M|P)(S|D)T/)[2]=="D"};Date.prototype.getTimezone=function(){return Date.getTimezoneAbbreviation(this.getUTCOffset,this.isDST())};Date.prototype.setTimezoneOffset=function(s){var here=this.getTimezoneOffset(),there=Number(s)*-6/10;this.addMinutes(there-here);return this};Date.prototype.setTimezone=function(s){return this.setTimezoneOffset(Date.getTimezoneOffset(s))};
Date.prototype.getUTCOffset=function(){var n=this.getTimezoneOffset()*-10/6,r;if(n<0){r=(n-1E4).toString();return r[0]+r.substr(2)}else{r=(n+1E4).toString();return"+"+r.substr(1)}};Date.prototype.getDayName=function(abbrev){return abbrev?Date.CultureInfo.abbreviatedDayNames[this.getDay()]:Date.CultureInfo.dayNames[this.getDay()]};Date.prototype.getMonthName=function(abbrev){return abbrev?Date.CultureInfo.abbreviatedMonthNames[this.getMonth()]:Date.CultureInfo.monthNames[this.getMonth()]};
Date.prototype._toString=Date.prototype.toString;
Date.prototype.toString=function(format){var self=this;var p=function p(s){return s.toString().length==1?"0"+s:s};return format?format.replace(/dd?d?d?|MM?M?M?|yy?y?y?|hh?|HH?|mm?|ss?|tt?|zz?z?/g,function(format){switch(format){case "hh":return p(self.getHours()<13?self.getHours():self.getHours()-12);case "h":return self.getHours()<13?self.getHours():self.getHours()-12;case "HH":return p(self.getHours());case "H":return self.getHours();case "mm":return p(self.getMinutes());case "m":return self.getMinutes();
case "ss":return p(self.getSeconds());case "s":return self.getSeconds();case "yyyy":return self.getFullYear();case "yy":return self.getFullYear().toString().substring(2,4);case "dddd":return self.getDayName();case "ddd":return self.getDayName(true);case "dd":return p(self.getDate());case "d":return self.getDate().toString();case "MMMM":return self.getMonthName();case "MMM":return self.getMonthName(true);case "MM":return p(self.getMonth()+1);case "M":return self.getMonth()+1;case "t":return self.getHours()<
12?Date.CultureInfo.amDesignator.substring(0,1):Date.CultureInfo.pmDesignator.substring(0,1);case "tt":return self.getHours()<12?Date.CultureInfo.amDesignator:Date.CultureInfo.pmDesignator;case "zzz":case "zz":case "z":return""}}):this._toString()};Date.now=function(){return new Date};Date.today=function(){return Date.now().clearTime()};Date.prototype._orient=+1;Date.prototype.next=function(){this._orient=+1;return this};
Date.prototype.last=Date.prototype.prev=Date.prototype.previous=function(){this._orient=-1;return this};Date.prototype._is=false;Date.prototype.is=function(){this._is=true;return this};Number.prototype._dateElement="day";Number.prototype.fromNow=function(){var c={};c[this._dateElement]=this;return Date.now().add(c)};Number.prototype.ago=function(){var c={};c[this._dateElement]=this*-1;return Date.now().add(c)};
(function(){var $D=Date.prototype,$N=Number.prototype;var dx="sunday monday tuesday wednesday thursday friday saturday".split(/\s/),mx="january february march april may june july august september october november december".split(/\s/),px="Millisecond Second Minute Hour Day Week Month Year".split(/\s/),de;var df=function(n){return function(){if(this._is){this._is=false;return this.getDay()==n}return this.moveToDayOfWeek(n,this._orient)}};for(var i=0;i<dx.length;i++)$D[dx[i]]=$D[dx[i].substring(0,3)]=
df(i);var mf=function(n){return function(){if(this._is){this._is=false;return this.getMonth()===n}return this.moveToMonth(n,this._orient)}};for(var j=0;j<mx.length;j++)$D[mx[j]]=$D[mx[j].substring(0,3)]=mf(j);var ef=function(j){return function(){if(j.substring(j.length-1)!="s")j+="s";return this["add"+j](this._orient)}};var nf=function(n){return function(){this._dateElement=n;return this}};for(var k=0;k<px.length;k++){de=px[k].toLowerCase();$D[de]=$D[de+"s"]=ef(px[k]);$N[de]=$N[de+"s"]=nf(de)}})();
Date.prototype.toJSONString=function(){return this.toString("yyyy-MM-ddThh:mm:ssZ")};Date.prototype.toShortDateString=function(){return this.toString(Date.CultureInfo.formatPatterns.shortDatePattern)};Date.prototype.toLongDateString=function(){return this.toString(Date.CultureInfo.formatPatterns.longDatePattern)};Date.prototype.toShortTimeString=function(){return this.toString(Date.CultureInfo.formatPatterns.shortTimePattern)};Date.prototype.toLongTimeString=function(){return this.toString(Date.CultureInfo.formatPatterns.longTimePattern)};
Date.prototype.getOrdinal=function(){switch(this.getDate()){case 1:case 21:case 31:return"st";case 2:case 22:return"nd";case 3:case 23:return"rd";default:return"th"}};
(function(){Date.Parsing={Exception:function(s){this.message="Parse error at '"+s.substring(0,10)+" ...'"}};var $P=Date.Parsing;var _=$P.Operators={rtoken:function(r){return function(s){var mx=s.match(r);if(mx)return[mx[0],s.substring(mx[0].length)];else throw new $P.Exception(s);}},token:function(s){return function(s){return _.rtoken(new RegExp("^s*"+s+"s*"))(s)}},stoken:function(s){return _.rtoken(new RegExp("^"+s))},until:function(p){return function(s){var qx=[],rx=null;while(s.length){try{rx=
p.call(this,s)}catch(e){qx.push(rx[0]);s=rx[1];continue}break}return[qx,s]}},many:function(p){return function(s){var rx=[],r=null;while(s.length){try{r=p.call(this,s)}catch(e){return[rx,s]}rx.push(r[0]);s=r[1]}return[rx,s]}},optional:function(p){return function(s){var r=null;try{r=p.call(this,s)}catch(e){return[null,s]}return[r[0],r[1]]}},not:function(p){return function(s){try{p.call(this,s)}catch(e){return[null,s]}throw new $P.Exception(s);}},ignore:function(p){return p?function(s){var r=null;r=
p.call(this,s);return[null,r[1]]}:null},product:function(){var px=arguments[0],qx=Array.prototype.slice.call(arguments,1),rx=[];for(var i=0;i<px.length;i++)rx.push(_.each(px[i],qx));return rx},cache:function(rule){var cache={},r=null;return function(s){try{r=cache[s]=cache[s]||rule.call(this,s)}catch(e){r=cache[s]=e}if(r instanceof $P.Exception)throw r;else return r}},any:function(){var px=arguments;return function(s){var r=null;for(var i=0;i<px.length;i++){if(px[i]==null)continue;try{r=px[i].call(this,
s)}catch(e){r=null}if(r)return r}throw new $P.Exception(s);}},each:function(){var px=arguments;return function(s){var rx=[],r=null;for(var i=0;i<px.length;i++){if(px[i]==null)continue;try{r=px[i].call(this,s)}catch(e){throw new $P.Exception(s);}rx.push(r[0]);s=r[1]}return[rx,s]}},all:function(){var px=arguments,_=_;return _.each(_.optional(px))},sequence:function(px,d,c){d=d||_.rtoken(/^\s*/);c=c||null;if(px.length==1)return px[0];return function(s){var r=null,q=null;var rx=[];for(var i=0;i<px.length;i++){try{r=
px[i].call(this,s)}catch(e){break}rx.push(r[0]);try{q=d.call(this,r[1])}catch(ex){q=null;break}s=q[1]}if(!r)throw new $P.Exception(s);if(q)throw new $P.Exception(q[1]);if(c)try{r=c.call(this,r[1])}catch(ey){throw new $P.Exception(r[1]);}return[rx,r?r[1]:s]}},between:function(d1,p,d2){d2=d2||d1;var _fn=_.each(_.ignore(d1),p,_.ignore(d2));return function(s){var rx=_fn.call(this,s);return[[rx[0][0],r[0][2]],rx[1]]}},list:function(p,d,c){d=d||_.rtoken(/^\s*/);c=c||null;return p instanceof Array?_.each(_.product(p.slice(0,
-1),_.ignore(d)),p.slice(-1),_.ignore(c)):_.each(_.many(_.each(p,_.ignore(d))),px,_.ignore(c))},set:function(px,d,c){d=d||_.rtoken(/^\s*/);c=c||null;return function(s){var r=null,p=null,q=null,rx=null,best=[[],s],last=false;for(var i=0;i<px.length;i++){q=null;p=null;r=null;last=px.length==1;try{r=px[i].call(this,s)}catch(e){continue}rx=[[r[0]],r[1]];if(r[1].length>0&&!last)try{q=d.call(this,r[1])}catch(ex){last=true}else last=true;if(!last&&q[1].length===0)last=true;if(!last){var qx=[];for(var j=
0;j<px.length;j++)if(i!=j)qx.push(px[j]);p=_.set(qx,d).call(this,q[1]);if(p[0].length>0){rx[0]=rx[0].concat(p[0]);rx[1]=p[1]}}if(rx[1].length<best[1].length)best=rx;if(best[1].length===0)break}if(best[0].length===0)return best;if(c){try{q=c.call(this,best[1])}catch(ey){throw new $P.Exception(best[1]);}best[1]=q[1]}return best}},forward:function(gr,fname){return function(s){return gr[fname].call(this,s)}},replace:function(rule,repl){return function(s){var r=rule.call(this,s);return[repl,r[1]]}},process:function(rule,
fn){return function(s){var r=rule.call(this,s);return[fn.call(this,r[0]),r[1]]}},min:function(min,rule){return function(s){var rx=rule.call(this,s);if(rx[0].length<min)throw new $P.Exception(s);return rx}}};var _generator=function(op){return function(){var args=null,rx=[];if(arguments.length>1)args=Array.prototype.slice.call(arguments);else if(arguments[0]instanceof Array)args=arguments[0];if(args)for(var i=0,px=args.shift();i<px.length;i++){args.unshift(px[i]);rx.push(op.apply(null,args));args.shift();
return rx}else return op.apply(null,arguments)}};var gx="optional not ignore cache".split(/\s/);for(var i=0;i<gx.length;i++)_[gx[i]]=_generator(_[gx[i]]);var _vector=function(op){return function(){if(arguments[0]instanceof Array)return op.apply(null,arguments[0]);else return op.apply(null,arguments)}};var vx="each any all".split(/\s/);for(var j=0;j<vx.length;j++)_[vx[j]]=_vector(_[vx[j]])})();
(function(){var flattenAndCompact=function(ax){var rx=[];for(var i=0;i<ax.length;i++)if(ax[i]instanceof Array)rx=rx.concat(flattenAndCompact(ax[i]));else if(ax[i])rx.push(ax[i]);return rx};Date.Grammar={};Date.Translator={hour:function(s){return function(){this.hour=Number(s)}},minute:function(s){return function(){this.minute=Number(s)}},second:function(s){return function(){this.second=Number(s)}},meridian:function(s){return function(){this.meridian=s.slice(0,1).toLowerCase()}},timezone:function(s){return function(){var n=
s.replace(/[^\d\+\-]/g,"");if(n.length)this.timezoneOffset=Number(n);else this.timezone=s.toLowerCase()}},day:function(x){var s=x[0];return function(){this.day=Number(s.match(/\d+/)[0])}},month:function(s){return function(){this.month=s.length==3?Date.getMonthNumberFromName(s):Number(s)-1}},year:function(s){return function(){var n=Number(s);this.year=s.length>2?n:n+(n+2E3<Date.CultureInfo.twoDigitYearMax?2E3:1900)}},rday:function(s){return function(){switch(s){case "yesterday":this.days=-1;break;
case "tomorrow":this.days=1;break;case "today":this.days=0;break;case "now":this.days=0;this.now=true;break}}},finishExact:function(x){x=x instanceof Array?x:[x];var now=new Date;this.year=now.getFullYear();this.month=now.getMonth();this.day=1;this.hour=0;this.minute=0;this.second=0;for(var i=0;i<x.length;i++)if(x[i])x[i].call(this);this.hour=this.meridian=="p"&&this.hour<13?this.hour+12:this.hour;if(this.day>Date.getDaysInMonth(this.year,this.month))throw new RangeError(this.day+" is not a valid value for days.");
var r=new Date(this.year,this.month,this.day,this.hour,this.minute,this.second);if(this.timezone)r.set({timezone:this.timezone});else if(this.timezoneOffset)r.set({timezoneOffset:this.timezoneOffset});return r},finish:function(x){x=x instanceof Array?flattenAndCompact(x):[x];if(x.length===0)return null;for(var i=0;i<x.length;i++)if(typeof x[i]=="function")x[i].call(this);if(this.now)return new Date;var today=Date.today();var method=null;var expression=!!(this.days!=null||this.orient||this.operator);
if(expression){var gap,mod,orient;orient=this.orient=="past"||this.operator=="subtract"?-1:1;if(this.weekday){this.unit="day";gap=Date.getDayNumberFromName(this.weekday)-today.getDay();mod=7;this.days=gap?(gap+orient*mod)%mod:orient*mod}if(this.month){this.unit="month";gap=this.month-today.getMonth();mod=12;this.months=gap?(gap+orient*mod)%mod:orient*mod;this.month=null}if(!this.unit)this.unit="day";if(this[this.unit+"s"]==null||this.operator!=null){if(!this.value)this.value=1;if(this.unit=="week"){this.unit=
"day";this.value=this.value*7}this[this.unit+"s"]=this.value*orient}return today.add(this)}else{if(this.meridian&&this.hour)this.hour=this.hour<13&&this.meridian=="p"?this.hour+12:this.hour;if(this.weekday&&!this.day)this.day=today.addDays(Date.getDayNumberFromName(this.weekday)-today.getDay()).getDate();if(this.month&&!this.day)this.day=1;return today.set(this)}}};var _=Date.Parsing.Operators,g=Date.Grammar,t=Date.Translator,_fn;g.datePartDelimiter=_.rtoken(/^([\s\-\.\,\/\x27]+)/);g.timePartDelimiter=
_.stoken(":");g.whiteSpace=_.rtoken(/^\s*/);g.generalDelimiter=_.rtoken(/^(([\s\,]|at|on)+)/);var _C={};g.ctoken=function(keys){var fn=_C[keys];if(!fn){var c=Date.CultureInfo.regexPatterns;var kx=keys.split(/\s+/),px=[];for(var i=0;i<kx.length;i++)px.push(_.replace(_.rtoken(c[kx[i]]),kx[i]));fn=_C[keys]=_.any.apply(null,px)}return fn};g.ctoken2=function(key){return _.rtoken(Date.CultureInfo.regexPatterns[key])};g.h=_.cache(_.process(_.rtoken(/^(0[0-9]|1[0-2]|[1-9])/),t.hour));g.hh=_.cache(_.process(_.rtoken(/^(0[0-9]|1[0-2])/),
t.hour));g.H=_.cache(_.process(_.rtoken(/^([0-1][0-9]|2[0-3]|[0-9])/),t.hour));g.HH=_.cache(_.process(_.rtoken(/^([0-1][0-9]|2[0-3])/),t.hour));g.m=_.cache(_.process(_.rtoken(/^([0-5][0-9]|[0-9])/),t.minute));g.mm=_.cache(_.process(_.rtoken(/^[0-5][0-9]/),t.minute));g.s=_.cache(_.process(_.rtoken(/^([0-5][0-9]|[0-9])/),t.second));g.ss=_.cache(_.process(_.rtoken(/^[0-5][0-9]/),t.second));g.hms=_.cache(_.sequence([g.H,g.mm,g.ss],g.timePartDelimiter));g.t=_.cache(_.process(g.ctoken2("shortMeridian"),
t.meridian));g.tt=_.cache(_.process(g.ctoken2("longMeridian"),t.meridian));g.z=_.cache(_.process(_.rtoken(/^(\+|\-)?\s*\d\d\d\d?/),t.timezone));g.zz=_.cache(_.process(_.rtoken(/^(\+|\-)\s*\d\d\d\d/),t.timezone));g.zzz=_.cache(_.process(g.ctoken2("timezone"),t.timezone));g.timeSuffix=_.each(_.ignore(g.whiteSpace),_.set([g.tt,g.zzz]));g.time=_.each(_.optional(_.ignore(_.stoken("T"))),g.hms,g.timeSuffix);g.d=_.cache(_.process(_.each(_.rtoken(/^([0-2]\d|3[0-1]|\d)/),_.optional(g.ctoken2("ordinalSuffix"))),
t.day));g.dd=_.cache(_.process(_.each(_.rtoken(/^([0-2]\d|3[0-1])/),_.optional(g.ctoken2("ordinalSuffix"))),t.day));g.ddd=g.dddd=_.cache(_.process(g.ctoken("sun mon tue wed thu fri sat"),function(s){return function(){this.weekday=s}}));g.M=_.cache(_.process(_.rtoken(/^(1[0-2]|0\d|\d)/),t.month));g.MM=_.cache(_.process(_.rtoken(/^(1[0-2]|0\d)/),t.month));g.MMM=g.MMMM=_.cache(_.process(g.ctoken("jan feb mar apr may jun jul aug sep oct nov dec"),t.month));g.y=_.cache(_.process(_.rtoken(/^(\d\d?)/),t.year));
g.yy=_.cache(_.process(_.rtoken(/^(\d\d)/),t.year));g.yyy=_.cache(_.process(_.rtoken(/^(\d\d?\d?\d?)/),t.year));g.yyyy=_.cache(_.process(_.rtoken(/^(\d\d\d\d)/),t.year));_fn=function(){return _.each(_.any.apply(null,arguments),_.not(g.ctoken2("timeContext")))};g.day=_fn(g.d,g.dd);g.month=_fn(g.M,g.MMM);g.year=_fn(g.yyyy,g.yy);g.orientation=_.process(g.ctoken("past future"),function(s){return function(){this.orient=s}});g.operator=_.process(g.ctoken("add subtract"),function(s){return function(){this.operator=
s}});g.rday=_.process(g.ctoken("yesterday tomorrow today now"),t.rday);g.unit=_.process(g.ctoken("minute hour day week month year"),function(s){return function(){this.unit=s}});g.value=_.process(_.rtoken(/^\d\d?(st|nd|rd|th)?/),function(s){return function(){this.value=s.replace(/\D/g,"")}});g.expression=_.set([g.rday,g.operator,g.value,g.unit,g.orientation,g.ddd,g.MMM]);_fn=function(){return _.set(arguments,g.datePartDelimiter)};g.mdy=_fn(g.ddd,g.month,g.day,g.year);g.ymd=_fn(g.ddd,g.year,g.month,
g.day);g.dmy=_fn(g.ddd,g.day,g.month,g.year);g.date=function(s){return(g[Date.CultureInfo.dateElementOrder]||g.mdy).call(this,s)};g.format=_.process(_.many(_.any(_.process(_.rtoken(/^(dd?d?d?|MM?M?M?|yy?y?y?|hh?|HH?|mm?|ss?|tt?|zz?z?)/),function(fmt){if(g[fmt])return g[fmt];else throw Date.Parsing.Exception(fmt);}),_.process(_.rtoken(/^[^dMyhHmstz]+/),function(s){return _.ignore(_.stoken(s))}))),function(rules){return _.process(_.each.apply(null,rules),t.finishExact)});var _F={};var _get=function(f){return _F[f]=
_F[f]||g.format(f)[0]};g.formats=function(fx){if(fx instanceof Array){var rx=[];for(var i=0;i<fx.length;i++)rx.push(_get(fx[i]));return _.any.apply(null,rx)}else return _get(fx)};g._formats=g.formats(["yyyy-MM-ddTHH:mm:ss","ddd, MMM dd, yyyy H:mm:ss tt","ddd MMM d yyyy HH:mm:ss zzz","d"]);g._start=_.process(_.set([g.date,g.time,g.expression],g.generalDelimiter,g.whiteSpace),t.finish);g.start=function(s){try{var r=g._formats.call({},s);if(r[1].length===0)return r}catch(e){}return g._start.call({},
s)}})();Date._parse=Date.parse;Date.parse=function(s){var r=null;if(!s)return null;try{r=Date.Grammar.start.call({},s)}catch(e){return null}return r[1].length===0?r[0]:null};Date.getParseFunction=function(fx){var fn=Date.Grammar.formats(fx);return function(s){var r=null;try{r=fn.call({},s)}catch(e){return null}return r[1].length===0?r[0]:null}};Date.parseExact=function(s,fx){return Date.getParseFunction(fx)(s)};
document.createElement("canvas").getContext||function(){function C(){}function B(a){this.type_=a,this.r1_=this.y1_=this.x1_=this.r0_=this.y0_=this.x0_=0,this.colors_=[]}function A(a,b,c){!z(b)||(a.m_=b,c&&(a.lineScale_=f(e(b[0][0]*b[1][1]-b[0][1]*b[1][0]))))}function z(a){var b=0;for(;b<3;b++){var c=0;for(;c<2;c++)if(!isFinite(a[b][c])||isNaN(a[b][c]))return!1}return!0}function y(a,b,c,d){a.currentPath_.push({type:"bezierCurveTo",cp1x:b.x,cp1y:b.y,cp2x:c.x,cp2y:c.y,x:d.x,y:d.y}),a.currentX_=d.x,a.currentY_=
d.y}function w(a){this.m_=r(),this.mStack_=[],this.aStack_=[],this.currentPath_=[],this.fillStyle=this.strokeStyle="#000",this.lineWidth=1,this.lineJoin="miter",this.lineCap="butt",this.miterLimit=g*1,this.globalAlpha=1,this.canvas=a;var b=a.ownerDocument.createElement("div");b.style.width=a.clientWidth+"px",b.style.height=a.clientHeight+"px",b.style.overflow="hidden",b.style.position="absolute",a.appendChild(b),this.element_=b,this.lineScale_=this.arcScaleY_=this.arcScaleX_=1}function v(a){switch(a){case "butt":return"flat";
case "round":return"round";case "square":default:return"square"}}function u(a){var b,c=1;a=String(a);if(a.substring(0,3)=="rgb"){var d=a.indexOf("(",3),e=a.indexOf(")",d+1),f=a.substring(d+1,e).split(",");b="#";var g=0;for(;g<3;g++)b+=o[Number(f[g])];f.length==4&&a.substr(3,1)=="a"&&(c=f[3])}else b=a;return{color:b,alpha:c}}function t(a,b){b.fillStyle=a.fillStyle,b.lineCap=a.lineCap,b.lineJoin=a.lineJoin,b.lineWidth=a.lineWidth,b.miterLimit=a.miterLimit,b.shadowBlur=a.shadowBlur,b.shadowColor=a.shadowColor,
b.shadowOffsetX=a.shadowOffsetX,b.shadowOffsetY=a.shadowOffsetY,b.strokeStyle=a.strokeStyle,b.globalAlpha=a.globalAlpha,b.arcScaleX_=a.arcScaleX_,b.arcScaleY_=a.arcScaleY_,b.lineScale_=a.lineScale_}function s(a,b){var c=r(),d=0;for(;d<3;d++){var e=0;for(;e<3;e++){var f=0,g=0;for(;g<3;g++)f+=a[d][g]*b[g][e];c[d][e]=f}}return c}function r(){return[[1,0,0],[0,1,0],[0,0,1]]}function n(a){var b=a.srcElement;b.firstChild&&(b.firstChild.style.width=b.clientWidth+"px",b.firstChild.style.height=b.clientHeight+
"px")}function m(a){var b=a.srcElement;switch(a.propertyName){case "width":b.style.width=b.attributes.width.nodeValue+"px",b.getContext().clearRect();break;case "height":b.style.height=b.attributes.height.nodeValue+"px",b.getContext().clearRect()}}function k(a,b){var c=j.call(arguments,2);return function(){return a.apply(b,c.concat(j.call(arguments)))}}function i(){return this.context_||(this.context_=new w(this))}var a=Math,b=a.round,c=a.sin,d=a.cos,e=a.abs,f=a.sqrt,g=10,h=g/2,j=Array.prototype.slice,
l={init:function(a){if(/MSIE/.test(navigator.userAgent)&&!window.opera){var b=a||document;b.createElement("canvas"),b.attachEvent("onreadystatechange",k(this.init_,this,b))}},init_:function(a){a.namespaces.g_vml_||a.namespaces.add("g_vml_","urn:schemas-microsoft-com:vml","#default#VML"),a.namespaces.g_o_||a.namespaces.add("g_o_","urn:schemas-microsoft-com:office:office","#default#VML");if(!a.styleSheets.ex_canvas_){var b=a.createStyleSheet();b.owningElement.id="ex_canvas_",b.cssText="canvas{display:inline-block;overflow:hidden;text-align:left;width:300px;height:150px}g_vml_\\:*{behavior:url(#default#VML)}g_o_\\:*{behavior:url(#default#VML)}"}var c=
a.getElementsByTagName("canvas"),d=0;for(;d<c.length;d++)this.initElement(c[d])},initElement:function(a){if(!a.getContext){a.getContext=i,a.innerHTML="",a.attachEvent("onpropertychange",m),a.attachEvent("onresize",n);var b=a.attributes;b.width&&b.width.specified?a.style.width=b.width.nodeValue+"px":a.width=a.clientWidth,b.height&&b.height.specified?a.style.height=b.height.nodeValue+"px":a.height=a.clientHeight}return a}};l.init();var o=[],p=0;for(;p<16;p++){var q=0;for(;q<16;q++)o[p*16+q]=p.toString(16)+
q.toString(16)}var x=w.prototype;x.clearRect=function(){this.element_.innerHTML=""},x.beginPath=function(){this.currentPath_=[]},x.moveTo=function(a,b){var c=this.getCoords_(a,b);this.currentPath_.push({type:"moveTo",x:c.x,y:c.y}),this.currentX_=c.x,this.currentY_=c.y},x.lineTo=function(a,b){var c=this.getCoords_(a,b);this.currentPath_.push({type:"lineTo",x:c.x,y:c.y}),this.currentX_=c.x,this.currentY_=c.y},x.bezierCurveTo=function(a,b,c,d,e,f){var g=this.getCoords_(e,f),h=this.getCoords_(a,b),i=
this.getCoords_(c,d);y(this,h,i,g)},x.quadraticCurveTo=function(a,b,c,d){var e=this.getCoords_(a,b),f=this.getCoords_(c,d),g={x:this.currentX_+0.6666666666666666*(e.x-this.currentX_),y:this.currentY_+0.6666666666666666*(e.y-this.currentY_)};y(this,g,{x:g.x+(f.x-this.currentX_)/3,y:g.y+(f.y-this.currentY_)/3},f)},x.arc=function(a,b,e,f,i,j){e*=g;var k=j?"at":"wa",l=a+d(f)*e-h,m=b+c(f)*e-h,n=a+d(i)*e-h,o=b+c(i)*e-h;l==n&&!j&&(l+=0.125);var p=this.getCoords_(a,b),q=this.getCoords_(l,m),r=this.getCoords_(n,
o);this.currentPath_.push({type:k,x:p.x,y:p.y,radius:e,xStart:q.x,yStart:q.y,xEnd:r.x,yEnd:r.y})},x.rect=function(a,b,c,d){this.moveTo(a,b),this.lineTo(a+c,b),this.lineTo(a+c,b+d),this.lineTo(a,b+d),this.closePath()},x.strokeRect=function(a,b,c,d){var e=this.currentPath_;this.beginPath(),this.moveTo(a,b),this.lineTo(a+c,b),this.lineTo(a+c,b+d),this.lineTo(a,b+d),this.closePath(),this.stroke(),this.currentPath_=e},x.fillRect=function(a,b,c,d){var e=this.currentPath_;this.beginPath(),this.moveTo(a,
b),this.lineTo(a+c,b),this.lineTo(a+c,b+d),this.lineTo(a,b+d),this.closePath(),this.fill(),this.currentPath_=e},x.createLinearGradient=function(a,b,c,d){var e=new B("gradient");e.x0_=a,e.y0_=b,e.x1_=c,e.y1_=d;return e},x.createRadialGradient=function(a,b,c,d,e,f){var g=new B("gradientradial");g.x0_=a,g.y0_=b,g.r0_=c,g.x1_=d,g.y1_=e,g.r1_=f;return g},x.drawImage=function(c){var d,e,f,h,i,j,k,l,m=c.runtimeStyle.width,n=c.runtimeStyle.height;c.runtimeStyle.width="auto",c.runtimeStyle.height="auto";var o=
c.width,p=c.height;c.runtimeStyle.width=m,c.runtimeStyle.height=n;if(arguments.length==3)d=arguments[1],e=arguments[2],i=j=0,k=f=o,l=h=p;else if(arguments.length==5)d=arguments[1],e=arguments[2],f=arguments[3],h=arguments[4],i=j=0,k=o,l=p;else if(arguments.length==9)i=arguments[1],j=arguments[2],k=arguments[3],l=arguments[4],d=arguments[5],e=arguments[6],f=arguments[7],h=arguments[8];else throw Error("Invalid number of arguments");var q=this.getCoords_(d,e),r=[];r.push(" <g_vml_:group",' coordsize="',
g*10,",",g*10,'"',' coordorigin="0,0"',' style="width:',10,"px;height:",10,"px;position:absolute;");if(this.m_[0][0]!=1||this.m_[0][1]){var s=[];s.push("M11=",this.m_[0][0],",","M12=",this.m_[1][0],",","M21=",this.m_[0][1],",","M22=",this.m_[1][1],",","Dx=",b(q.x/g),",","Dy=",b(q.y/g),"");var t=q,u=this.getCoords_(d+f,e),v=this.getCoords_(d,e+h),w=this.getCoords_(d+f,e+h);t.x=a.max(t.x,u.x,v.x,w.x),t.y=a.max(t.y,u.y,v.y,w.y),r.push("padding:0 ",b(t.x/g),"px ",b(t.y/g),"px 0;filter:progid:DXImageTransform.Microsoft.Matrix(",
s.join(""),", sizingmethod='clip');")}else r.push("top:",b(q.y/g),"px;left:",b(q.x/g),"px;");r.push(' ">','<g_vml_:image src="',c.src,'"',' style="width:',g*f,"px;"," height:",g*h,'px;"',' cropleft="',i/o,'"',' croptop="',j/p,'"',' cropright="',(o-i-k)/o,'"',' cropbottom="',(p-j-l)/p,'"'," />","</g_vml_:group>"),this.element_.insertAdjacentHTML("BeforeEnd",r.join(""))},x.stroke=function(c){var d=[],e=u(c?this.fillStyle:this.strokeStyle),f=e.color,h=e.alpha*this.globalAlpha;d.push("<g_vml_:shape",
' filled="',!!c,'"',' style="position:absolute;width:',10,"px;height:",10,'px;"',' coordorigin="0 0" coordsize="',g*10," ",g*10,'"',' stroked="',!c,'"',' path="');var i={x:null,y:null},j={x:null,y:null},k=0;for(;k<this.currentPath_.length;k++){var l=this.currentPath_[k];switch(l.type){case "moveTo":d.push(" m ",b(l.x),",",b(l.y));break;case "lineTo":d.push(" l ",b(l.x),",",b(l.y));break;case "close":d.push(" x "),l=null;break;case "bezierCurveTo":d.push(" c ",b(l.cp1x),",",b(l.cp1y),",",b(l.cp2x),
",",b(l.cp2y),",",b(l.x),",",b(l.y));break;case "at":case "wa":d.push(" ",l.type," ",b(l.x-this.arcScaleX_*l.radius),",",b(l.y-this.arcScaleY_*l.radius)," ",b(l.x+this.arcScaleX_*l.radius),",",b(l.y+this.arcScaleY_*l.radius)," ",b(l.xStart),",",b(l.yStart)," ",b(l.xEnd),",",b(l.yEnd))}if(l){if(i.x==null||l.x<i.x)i.x=l.x;if(j.x==null||l.x>j.x)j.x=l.x;if(i.y==null||l.y<i.y)i.y=l.y;if(j.y==null||l.y>j.y)j.y=l.y}}d.push(' ">');if(c)if(typeof this.fillStyle=="object"){var m=this.fillStyle,n=0,o={x:0,y:0},
p=0,q=1;if(m.type_=="gradient"){var r=m.x1_/this.arcScaleX_,s=m.y1_/this.arcScaleY_,t=this.getCoords_(m.x0_/this.arcScaleX_,m.y0_/this.arcScaleY_),w=this.getCoords_(r,s);n=Math.atan2(w.x-t.x,w.y-t.y)*180/Math.PI,n<0&&(n+=360),n<1.0E-6&&(n=0)}else{var t=this.getCoords_(m.x0_,m.y0_),x=j.x-i.x,y=j.y-i.y;o={x:(t.x-i.x)/x,y:(t.y-i.y)/y},x/=this.arcScaleX_*g,y/=this.arcScaleY_*g;var z=a.max(x,y);p=2*m.r0_/z,q=2*m.r1_/z-p}var A=m.colors_;A.sort(function(a,b){return a.offset-b.offset});var B=A.length,C=A[0].color,
D=A[B-1].color,E=A[0].alpha*this.globalAlpha,F=A[B-1].alpha*this.globalAlpha,G=[],k=0;for(;k<B;k++){var H=A[k];G.push(H.offset*q+p+" "+H.color)}d.push('<g_vml_:fill type="',m.type_,'"',' method="none" focus="100%"',' color="',C,'"',' color2="',D,'"',' colors="',G.join(","),'"',' opacity="',F,'"',' g_o_:opacity2="',E,'"',' angle="',n,'"',' focusposition="',o.x,",",o.y,'" />')}else d.push('<g_vml_:fill color="',f,'" opacity="',h,'" />');else{var I=this.lineScale_*this.lineWidth;I<1&&(h*=I),d.push("<g_vml_:stroke",
' opacity="',h,'"',' joinstyle="',this.lineJoin,'"',' miterlimit="',this.miterLimit,'"',' endcap="',v(this.lineCap),'"',' weight="',I,'px"',' color="',f,'" />')}d.push("</g_vml_:shape>"),this.element_.insertAdjacentHTML("beforeEnd",d.join(""))},x.fill=function(){this.stroke(!0)},x.closePath=function(){this.currentPath_.push({type:"close"})},x.getCoords_=function(a,b){var c=this.m_;return{x:g*(a*c[0][0]+b*c[1][0]+c[2][0])-h,y:g*(a*c[0][1]+b*c[1][1]+c[2][1])-h}},x.save=function(){var a={};t(this,a),
this.aStack_.push(a),this.mStack_.push(this.m_),this.m_=s(r(),this.m_)},x.restore=function(){t(this.aStack_.pop(),this),this.m_=this.mStack_.pop()},x.translate=function(a,b){A(this,s([[1,0,0],[0,1,0],[a,b,1]],this.m_),!1)},x.rotate=function(a){var b=d(a),e=c(a);A(this,s([[b,e,0],[-e,b,0],[0,0,1]],this.m_),!1)},x.scale=function(a,b){this.arcScaleX_*=a,this.arcScaleY_*=b,A(this,s([[a,0,0],[0,b,0],[0,0,1]],this.m_),!0)},x.transform=function(a,b,c,d,e,f){A(this,s([[a,b,0],[c,d,0],[e,f,1]],this.m_),!0)},
x.setTransform=function(a,b,c,d,e,f){A(this,[[a,b,0],[c,d,0],[e,f,1]],!0)},x.clip=function(){},x.arcTo=function(){},x.createPattern=function(){return new C},B.prototype.addColorStop=function(a,b){b=u(b),this.colors_.push({offset:a,color:b.color,alpha:b.alpha})},G_vmlCanvasManager=l,CanvasRenderingContext2D=w,CanvasGradient=B,CanvasPattern=C}();
Prototip.Styles={"default":{border:6,borderColor:"#c7c7c7",className:"default",closeButton:false,hideAfter:false,hideOn:"mouseleave",hook:false,radius:6,showOn:"mousemove",stem:{height:12,width:15}},"protoblue":{className:"protoblue",border:6,borderColor:"#116497",radius:6,stem:{height:12,width:15}},"darkgrey":{className:"darkgrey",border:6,borderColor:"#363636",radius:6,stem:{height:12,width:15}},"creamy":{className:"creamy",border:6,borderColor:"#ebe4b4",radius:6,stem:{height:12,width:15}},"protogrey":{className:"protogrey",
border:6,borderColor:"#606060",radius:6,stem:{height:12,width:15}}};if(typeof Effect=="undefined")throw"controls.js requires including script.aculo.us' effects.js library";var Autocompleter={};
Autocompleter.Base=Class.create({baseInitialize:function(element,update,options){element=$(element);this.element=element;this.update=$(update);this.hasFocus=false;this.changed=false;this.active=false;this.index=0;this.entryCount=0;this.oldElementValue=this.element.value;if(this.setOptions)this.setOptions(options);else this.options=options||{};this.options.paramName=this.options.paramName||this.element.name;this.options.tokens=this.options.tokens||[];this.options.frequency=this.options.frequency||
0.4;this.options.minChars=this.options.minChars||1;this.options.onShow=this.options.onShow||function(element,update){if(!update.style.position||update.style.position=="absolute"){update.style.position="absolute";Position.clone(element,update,{setHeight:false,offsetTop:element.offsetHeight})}Effect.Appear(update,{duration:0.15})};this.options.onHide=this.options.onHide||function(element,update){new Effect.Fade(update,{duration:0.15})};if(typeof this.options.tokens=="string")this.options.tokens=new Array(this.options.tokens);
if(!this.options.tokens.include("\n"))this.options.tokens.push("\n");this.observer=null;this.element.setAttribute("autocomplete","off");Element.hide(this.update);Event.observe(this.element,"blur",this.onBlur.bindAsEventListener(this));Event.observe(this.element,"keydown",this.onKeyPress.bindAsEventListener(this))},show:function(){if(Element.getStyle(this.update,"display")=="none")this.options.onShow(this.element,this.update);if(!this.iefix&&Prototype.Browser.IE&&Element.getStyle(this.update,"position")==
"absolute"){new Insertion.After(this.update,'<iframe id="'+this.update.id+'_iefix" '+'style="display:none;position:absolute;filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0);" '+'src="javascript:false;" frameborder="0" scrolling="no"></iframe>');this.iefix=$(this.update.id+"_iefix")}if(this.iefix)setTimeout(this.fixIEOverlapping.bind(this),50)},fixIEOverlapping:function(){Position.clone(this.update,this.iefix,{setTop:!this.update.style.height});this.iefix.style.zIndex=1;this.update.style.zIndex=
2;Element.show(this.iefix)},hide:function(){this.stopIndicator();if(Element.getStyle(this.update,"display")!="none")this.options.onHide(this.element,this.update);if(this.iefix)Element.hide(this.iefix)},startIndicator:function(){if(this.options.indicator)Element.show(this.options.indicator)},stopIndicator:function(){if(this.options.indicator)Element.hide(this.options.indicator)},onKeyPress:function(event){if(this.active)switch(event.keyCode){case Event.KEY_TAB:case Event.KEY_RETURN:this.selectEntry();
Event.stop(event);case Event.KEY_ESC:this.hide();this.active=false;Event.stop(event);return;case Event.KEY_LEFT:case Event.KEY_RIGHT:return;case Event.KEY_UP:this.markPrevious();this.render();Event.stop(event);return;case Event.KEY_DOWN:this.markNext();this.render();Event.stop(event);return}else if(event.keyCode==Event.KEY_TAB||event.keyCode==Event.KEY_RETURN||Prototype.Browser.WebKit>0&&event.keyCode==0)return;this.changed=true;this.hasFocus=true;if(this.observer)clearTimeout(this.observer);this.observer=
setTimeout(this.onObserverEvent.bind(this),this.options.frequency*1E3)},activate:function(){this.changed=false;this.hasFocus=true;this.getUpdatedChoices()},onHover:function(event){var element=Event.findElement(event,"LI");if(this.index!=element.autocompleteIndex){this.index=element.autocompleteIndex;this.render()}Event.stop(event)},onClick:function(event){var element=Event.findElement(event,"LI");this.index=element.autocompleteIndex;this.selectEntry();this.hide()},onBlur:function(event){setTimeout(this.hide.bind(this),
250);this.hasFocus=false;this.active=false},render:function(){if(this.entryCount>0){for(var i=0;i<this.entryCount;i++)this.index==i?Element.addClassName(this.getEntry(i),"selected"):Element.removeClassName(this.getEntry(i),"selected");if(this.hasFocus){this.show();this.active=true}}else{this.active=false;this.hide()}},markPrevious:function(){if(this.index>0)this.index--;else this.index=this.entryCount-1;this.getEntry(this.index).scrollIntoView(true)},markNext:function(){if(this.index<this.entryCount-
1)this.index++;else this.index=0;this.getEntry(this.index).scrollIntoView(false)},getEntry:function(index){return this.update.firstChild.childNodes[index]},getCurrentEntry:function(){return this.getEntry(this.index)},selectEntry:function(){this.active=false;this.updateElement(this.getCurrentEntry())},updateElement:function(selectedElement){if(this.options.updateElement){this.options.updateElement(selectedElement);return}var value="";if(this.options.select){var nodes=$(selectedElement).select("."+
this.options.select)||[];if(nodes.length>0)value=Element.collectTextNodes(nodes[0],this.options.select)}else value=Element.collectTextNodesIgnoreClass(selectedElement,"informal");var bounds=this.getTokenBounds();if(bounds[0]!=-1){var newValue=this.element.value.substr(0,bounds[0]);var whitespace=this.element.value.substr(bounds[0]).match(/^\s+/);if(whitespace)newValue+=whitespace[0];this.element.value=newValue+value+this.element.value.substr(bounds[1])}else this.element.value=value;this.oldElementValue=
this.element.value;this.element.focus();if(this.options.afterUpdateElement)this.options.afterUpdateElement(this.element,selectedElement)},updateChoices:function(choices){if(!this.changed&&this.hasFocus){this.update.innerHTML=choices;Element.cleanWhitespace(this.update);Element.cleanWhitespace(this.update.down());if(this.update.firstChild&&this.update.down().childNodes){this.entryCount=this.update.down().childNodes.length;for(var i=0;i<this.entryCount;i++){var entry=this.getEntry(i);entry.autocompleteIndex=
i;this.addObservers(entry)}}else this.entryCount=0;this.stopIndicator();this.index=0;if(this.entryCount==1&&this.options.autoSelect){this.selectEntry();this.hide()}else this.render()}},addObservers:function(element){Event.observe(element,"mouseover",this.onHover.bindAsEventListener(this));Event.observe(element,"click",this.onClick.bindAsEventListener(this))},onObserverEvent:function(){this.changed=false;this.tokenBounds=null;if(this.getToken().length>=this.options.minChars)this.getUpdatedChoices();
else{this.active=false;this.hide()}this.oldElementValue=this.element.value},getToken:function(){var bounds=this.getTokenBounds();return this.element.value.substring(bounds[0],bounds[1]).strip()},getTokenBounds:function(){if(null!=this.tokenBounds)return this.tokenBounds;var value=this.element.value;if(value.strip().empty())return[-1,0];var diff=arguments.callee.getFirstDifferencePos(value,this.oldElementValue);var offset=diff==this.oldElementValue.length?1:0;var prevTokenPos=-1,nextTokenPos=value.length;
var tp;for(var index=0,l=this.options.tokens.length;index<l;++index){tp=value.lastIndexOf(this.options.tokens[index],diff+offset-1);if(tp>prevTokenPos)prevTokenPos=tp;tp=value.indexOf(this.options.tokens[index],diff+offset);if(-1!=tp&&tp<nextTokenPos)nextTokenPos=tp}return this.tokenBounds=[prevTokenPos+1,nextTokenPos]}});
Autocompleter.Base.prototype.getTokenBounds.getFirstDifferencePos=function(newS,oldS){var boundary=Math.min(newS.length,oldS.length);for(var index=0;index<boundary;++index)if(newS[index]!=oldS[index])return index;return boundary};
Ajax.Autocompleter=Class.create(Autocompleter.Base,{initialize:function(element,update,url,options){this.baseInitialize(element,update,options);this.options.asynchronous=true;this.options.onComplete=this.onComplete.bind(this);this.options.defaultParams=this.options.parameters||null;this.url=url},getUpdatedChoices:function(){this.startIndicator();var entry=encodeURIComponent(this.options.paramName)+"="+encodeURIComponent(this.getToken());this.options.parameters=this.options.callback?this.options.callback(this.element,
entry):entry;if(this.options.defaultParams)this.options.parameters+="&"+this.options.defaultParams;new Ajax.Request(this.url,this.options)},onComplete:function(request){this.updateChoices(request.responseText)}});
Autocompleter.Local=Class.create(Autocompleter.Base,{initialize:function(element,update,array,options){this.baseInitialize(element,update,options);this.options.array=array},getUpdatedChoices:function(){this.updateChoices(this.options.selector(this))},setOptions:function(options){this.options=Object.extend({choices:10,partialSearch:true,partialChars:2,ignoreCase:true,fullSearch:false,selector:function(instance){var ret=[];var partial=[];var entry=instance.getToken();var count=0;for(var i=0;i<instance.options.array.length&&
ret.length<instance.options.choices;i++){var elem=instance.options.array[i];var foundPos=instance.options.ignoreCase?elem.toLowerCase().indexOf(entry.toLowerCase()):elem.indexOf(entry);while(foundPos!=-1){if(foundPos==0&&elem.length!=entry.length){ret.push("<li><strong>"+elem.substr(0,entry.length)+"</strong>"+elem.substr(entry.length)+"</li>");break}else if(entry.length>=instance.options.partialChars&&instance.options.partialSearch&&foundPos!=-1)if(instance.options.fullSearch||/\s/.test(elem.substr(foundPos-
1,1))){partial.push("<li>"+elem.substr(0,foundPos)+"<strong>"+elem.substr(foundPos,entry.length)+"</strong>"+elem.substr(foundPos+entry.length)+"</li>");break}foundPos=instance.options.ignoreCase?elem.toLowerCase().indexOf(entry.toLowerCase(),foundPos+1):elem.indexOf(entry,foundPos+1)}}if(partial.length)ret=ret.concat(partial.slice(0,instance.options.choices-ret.length));return"<ul>"+ret.join("")+"</ul>"}},options||{})}});
Field.scrollFreeActivate=function(field){setTimeout(function(){Field.activate(field)},1)};
Ajax.InPlaceEditor=Class.create({initialize:function(element,url,options){this.url=url;this.element=element=$(element);this.prepareOptions();this._controls={};arguments.callee.dealWithDeprecatedOptions(options);Object.extend(this.options,options||{});if(!this.options.formId&&this.element.id){this.options.formId=this.element.id+"-inplaceeditor";if($(this.options.formId))this.options.formId=""}if(this.options.externalControl)this.options.externalControl=$(this.options.externalControl);if(!this.options.externalControl)this.options.externalControlOnly=
false;this._originalBackground=this.element.getStyle("background-color")||"transparent";this.element.title=this.options.clickToEditText;this._boundCancelHandler=this.handleFormCancellation.bind(this);this._boundComplete=(this.options.onComplete||Prototype.emptyFunction).bind(this);this._boundFailureHandler=this.handleAJAXFailure.bind(this);this._boundSubmitHandler=this.handleFormSubmission.bind(this);this._boundWrapperHandler=this.wrapUp.bind(this);this.registerListeners()},checkForEscapeOrReturn:function(e){if(!this._editing||
e.ctrlKey||e.altKey||e.shiftKey)return;if(Event.KEY_ESC==e.keyCode)this.handleFormCancellation(e);else if(Event.KEY_RETURN==e.keyCode)this.handleFormSubmission(e)},createControl:function(mode,handler,extraClasses){var control=this.options[mode+"Control"];var text=this.options[mode+"Text"];if("button"==control){var btn=document.createElement("input");btn.type="submit";btn.value=text;btn.className="editor_"+mode+"_button";if("cancel"==mode)btn.onclick=this._boundCancelHandler;this._form.appendChild(btn);
this._controls[mode]=btn}else if("link"==control){var link=document.createElement("a");link.href="#";link.appendChild(document.createTextNode(text));link.onclick="cancel"==mode?this._boundCancelHandler:this._boundSubmitHandler;link.className="editor_"+mode+"_link";if(extraClasses)link.className+=" "+extraClasses;this._form.appendChild(link);this._controls[mode]=link}},createEditField:function(){var text=this.options.loadTextURL?this.options.loadingText:this.getText();var fld;if(1>=this.options.rows&&
!/\r|\n/.test(this.getText())){fld=document.createElement("input");fld.type="text";var size=this.options.size||this.options.cols||0;if(0<size)fld.size=size}else{fld=document.createElement("textarea");fld.rows=1>=this.options.rows?this.options.autoRows:this.options.rows;fld.cols=this.options.cols||40}fld.name=this.options.paramName;fld.value=text;fld.className="editor_field";if(this.options.submitOnBlur)fld.onblur=this._boundSubmitHandler;this._controls.editor=fld;if(this.options.loadTextURL)this.loadExternalText();
this._form.appendChild(this._controls.editor)},createForm:function(){var ipe=this;function addText(mode,condition){var text=ipe.options["text"+mode+"Controls"];if(!text||condition===false)return;ipe._form.appendChild(document.createTextNode(text))}this._form=$(document.createElement("form"));this._form.id=this.options.formId;this._form.addClassName(this.options.formClassName);this._form.onsubmit=this._boundSubmitHandler;this.createEditField();if("textarea"==this._controls.editor.tagName.toLowerCase())this._form.appendChild(document.createElement("br"));
if(this.options.onFormCustomization)this.options.onFormCustomization(this,this._form);addText("Before",this.options.okControl||this.options.cancelControl);this.createControl("ok",this._boundSubmitHandler);addText("Between",this.options.okControl&&this.options.cancelControl);this.createControl("cancel",this._boundCancelHandler,"editor_cancel");addText("After",this.options.okControl||this.options.cancelControl)},destroy:function(){if(this._oldInnerHTML)this.element.innerHTML=this._oldInnerHTML;this.leaveEditMode();
this.unregisterListeners()},enterEditMode:function(e){if(this._saving||this._editing)return;this._editing=true;this.triggerCallback("onEnterEditMode");if(this.options.externalControl)this.options.externalControl.hide();this.element.hide();this.createForm();this.element.parentNode.insertBefore(this._form,this.element);if(!this.options.loadTextURL)this.postProcessEditField();if(e)Event.stop(e)},enterHover:function(e){if(this.options.hoverClassName)this.element.addClassName(this.options.hoverClassName);
if(this._saving)return;this.triggerCallback("onEnterHover")},getText:function(){return this.element.innerHTML.unescapeHTML()},handleAJAXFailure:function(transport){this.triggerCallback("onFailure",transport);if(this._oldInnerHTML){this.element.innerHTML=this._oldInnerHTML;this._oldInnerHTML=null}},handleFormCancellation:function(e){this.wrapUp();if(e)Event.stop(e)},handleFormSubmission:function(e){var form=this._form;var value=$F(this._controls.editor);this.prepareSubmission();var params=this.options.callback(form,
value)||"";if(Object.isString(params))params=params.toQueryParams();params.editorId=this.element.id;if(this.options.htmlResponse){var options=Object.extend({evalScripts:true},this.options.ajaxOptions);Object.extend(options,{parameters:params,onComplete:this._boundWrapperHandler,onFailure:this._boundFailureHandler});new Ajax.Updater({success:this.element},this.url,options)}else{var options=Object.extend({method:"get"},this.options.ajaxOptions);Object.extend(options,{parameters:params,onComplete:this._boundWrapperHandler,
onFailure:this._boundFailureHandler});new Ajax.Request(this.url,options)}if(e)Event.stop(e)},leaveEditMode:function(){this.element.removeClassName(this.options.savingClassName);this.removeForm();this.leaveHover();this.element.style.backgroundColor=this._originalBackground;this.element.show();if(this.options.externalControl)this.options.externalControl.show();this._saving=false;this._editing=false;this._oldInnerHTML=null;this.triggerCallback("onLeaveEditMode")},leaveHover:function(e){if(this.options.hoverClassName)this.element.removeClassName(this.options.hoverClassName);
if(this._saving)return;this.triggerCallback("onLeaveHover")},loadExternalText:function(){this._form.addClassName(this.options.loadingClassName);this._controls.editor.disabled=true;var options=Object.extend({method:"get"},this.options.ajaxOptions);Object.extend(options,{parameters:"editorId="+encodeURIComponent(this.element.id),onComplete:Prototype.emptyFunction,onSuccess:function(transport){this._form.removeClassName(this.options.loadingClassName);var text=transport.responseText;if(this.options.stripLoadedTextTags)text=
text.stripTags();this._controls.editor.value=text;this._controls.editor.disabled=false;this.postProcessEditField()}.bind(this),onFailure:this._boundFailureHandler});new Ajax.Request(this.options.loadTextURL,options)},postProcessEditField:function(){var fpc=this.options.fieldPostCreation;if(fpc)$(this._controls.editor)["focus"==fpc?"focus":"activate"]()},prepareOptions:function(){this.options=Object.clone(Ajax.InPlaceEditor.DefaultOptions);Object.extend(this.options,Ajax.InPlaceEditor.DefaultCallbacks);
[this._extraDefaultOptions].flatten().compact().each(function(defs){Object.extend(this.options,defs)}.bind(this))},prepareSubmission:function(){this._saving=true;this.removeForm();this.leaveHover();this.showSaving()},registerListeners:function(){this._listeners={};var listener;$H(Ajax.InPlaceEditor.Listeners).each(function(pair){listener=this[pair.value].bind(this);this._listeners[pair.key]=listener;if(!this.options.externalControlOnly)this.element.observe(pair.key,listener);if(this.options.externalControl)this.options.externalControl.observe(pair.key,
listener)}.bind(this))},removeForm:function(){if(!this._form)return;this._form.remove();this._form=null;this._controls={}},showSaving:function(){this._oldInnerHTML=this.element.innerHTML;this.element.innerHTML=this.options.savingText;this.element.addClassName(this.options.savingClassName);this.element.style.backgroundColor=this._originalBackground;this.element.show()},triggerCallback:function(cbName,arg){if("function"==typeof this.options[cbName])this.options[cbName](this,arg)},unregisterListeners:function(){$H(this._listeners).each(function(pair){if(!this.options.externalControlOnly)this.element.stopObserving(pair.key,
pair.value);if(this.options.externalControl)this.options.externalControl.stopObserving(pair.key,pair.value)}.bind(this))},wrapUp:function(transport){this.leaveEditMode();this._boundComplete(transport,this.element)}});Object.extend(Ajax.InPlaceEditor.prototype,{dispose:Ajax.InPlaceEditor.prototype.destroy});
Ajax.InPlaceCollectionEditor=Class.create(Ajax.InPlaceEditor,{initialize:function($super,element,url,options){this._extraDefaultOptions=Ajax.InPlaceCollectionEditor.DefaultOptions;$super(element,url,options)},createEditField:function(){var list=document.createElement("select");list.name=this.options.paramName;list.size=1;this._controls.editor=list;this._collection=this.options.collection||[];if(this.options.loadCollectionURL)this.loadCollection();else this.checkForExternalText();this._form.appendChild(this._controls.editor)},
loadCollection:function(){this._form.addClassName(this.options.loadingClassName);this.showLoadingText(this.options.loadingCollectionText);var options=Object.extend({method:"get"},this.options.ajaxOptions);Object.extend(options,{parameters:"editorId="+encodeURIComponent(this.element.id),onComplete:Prototype.emptyFunction,onSuccess:function(transport){var js=transport.responseText.strip();if(!/^\[.*\]$/.test(js))throw"Server returned an invalid collection representation.";this._collection=eval(js);
this.checkForExternalText()}.bind(this),onFailure:this.onFailure});new Ajax.Request(this.options.loadCollectionURL,options)},showLoadingText:function(text){this._controls.editor.disabled=true;var tempOption=this._controls.editor.firstChild;if(!tempOption){tempOption=document.createElement("option");tempOption.value="";this._controls.editor.appendChild(tempOption);tempOption.selected=true}tempOption.update((text||"").stripScripts().stripTags())},checkForExternalText:function(){this._text=this.getText();
if(this.options.loadTextURL)this.loadExternalText();else this.buildOptionList()},loadExternalText:function(){this.showLoadingText(this.options.loadingText);var options=Object.extend({method:"get"},this.options.ajaxOptions);Object.extend(options,{parameters:"editorId="+encodeURIComponent(this.element.id),onComplete:Prototype.emptyFunction,onSuccess:function(transport){this._text=transport.responseText.strip();this.buildOptionList()}.bind(this),onFailure:this.onFailure});new Ajax.Request(this.options.loadTextURL,
options)},buildOptionList:function(){this._form.removeClassName(this.options.loadingClassName);this._collection=this._collection.map(function(entry){return 2===entry.length?entry:[entry,entry].flatten()});var marker="value"in this.options?this.options.value:this._text;var textFound=this._collection.any(function(entry){return entry[0]==marker}.bind(this));this._controls.editor.update("");var option;this._collection.each(function(entry,index){option=document.createElement("option");option.value=entry[0];
option.selected=textFound?entry[0]==marker:0==index;option.appendChild(document.createTextNode(entry[1]));this._controls.editor.appendChild(option)}.bind(this));this._controls.editor.disabled=false;Field.scrollFreeActivate(this._controls.editor)}});
Ajax.InPlaceEditor.prototype.initialize.dealWithDeprecatedOptions=function(options){if(!options)return;function fallback(name,expr){if(name in options||expr===undefined)return;options[name]=expr}fallback("cancelControl",options.cancelLink?"link":options.cancelButton?"button":options.cancelLink==options.cancelButton==false?false:undefined);fallback("okControl",options.okLink?"link":options.okButton?"button":options.okLink==options.okButton==false?false:undefined);fallback("highlightColor",options.highlightcolor);
fallback("highlightEndColor",options.highlightendcolor)};
Object.extend(Ajax.InPlaceEditor,{DefaultOptions:{ajaxOptions:{},autoRows:3,cancelControl:"link",cancelText:"cancel",clickToEditText:"Click to edit",externalControl:null,externalControlOnly:false,fieldPostCreation:"activate",formClassName:"inplaceeditor-form",formId:null,highlightColor:"#ffff99",highlightEndColor:"#ffffff",hoverClassName:"",htmlResponse:true,loadingClassName:"inplaceeditor-loading",loadingText:"Loading...",okControl:"button",okText:"ok",paramName:"value",rows:1,savingClassName:"inplaceeditor-saving",
savingText:"Saving...",size:0,stripLoadedTextTags:false,submitOnBlur:false,textAfterControls:"",textBeforeControls:"",textBetweenControls:""},DefaultCallbacks:{callback:function(form){return Form.serialize(form)},onComplete:function(transport,element){new Effect.Highlight(element,{startcolor:this.options.highlightColor,keepBackgroundImage:true})},onEnterEditMode:null,onEnterHover:function(ipe){ipe.element.style.backgroundColor=ipe.options.highlightColor;if(ipe._effect)ipe._effect.cancel()},onFailure:function(transport,
ipe){alert("Error communication with the server: "+transport.responseText.stripTags())},onFormCustomization:null,onLeaveEditMode:null,onLeaveHover:function(ipe){ipe._effect=new Effect.Highlight(ipe.element,{startcolor:ipe.options.highlightColor,endcolor:ipe.options.highlightEndColor,restorecolor:ipe._originalBackground,keepBackgroundImage:true})}},Listeners:{click:"enterEditMode",keydown:"checkForEscapeOrReturn",mouseover:"enterHover",mouseout:"leaveHover"}});
Ajax.InPlaceCollectionEditor.DefaultOptions={loadingCollectionText:"Loading options..."};
Form.Element.DelayedObserver=Class.create({initialize:function(element,delay,callback){this.delay=delay||0.5;this.element=$(element);this.callback=callback;this.timer=null;this.lastValue=$F(this.element);Event.observe(this.element,"keyup",this.delayedListener.bindAsEventListener(this))},delayedListener:function(event){if(this.lastValue==$F(this.element))return;if(this.timer)clearTimeout(this.timer);this.timer=setTimeout(this.onTimerEvent.bind(this),this.delay*1E3);this.lastValue=$F(this.element)},
onTimerEvent:function(){this.timer=null;this.callback(this.element,$F(this.element))}});if(!Control)var Control={};
Control.Slider=Class.create({initialize:function(handle,track,options){var slider=this;if(Object.isArray(handle))this.handles=handle.collect(function(e){return $(e)});else this.handles=[$(handle)];this.track=$(track);this.options=options||{};this.axis=this.options.axis||"horizontal";this.increment=this.options.increment||1;this.step=parseInt(this.options.step||"1");this.range=this.options.range||$R(0,1);this.value=0;this.values=this.handles.map(function(){return 0});this.spans=this.options.spans?
this.options.spans.map(function(s){return $(s)}):false;this.options.startSpan=$(this.options.startSpan||null);this.options.endSpan=$(this.options.endSpan||null);this.restricted=this.options.restricted||false;this.maximum=this.options.maximum||this.range.end;this.minimum=this.options.minimum||this.range.start;this.alignX=parseInt(this.options.alignX||"0");this.alignY=parseInt(this.options.alignY||"0");this.trackLength=this.maximumOffset()-this.minimumOffset();this.handleLength=this.isVertical()?this.handles[0].offsetHeight!=
0?this.handles[0].offsetHeight:this.handles[0].style.height.replace(/px$/,""):this.handles[0].offsetWidth!=0?this.handles[0].offsetWidth:this.handles[0].style.width.replace(/px$/,"");this.active=false;this.dragging=false;this.disabled=false;if(this.options.disabled)this.setDisabled();this.allowedValues=this.options.values?this.options.values.sortBy(Prototype.K):false;if(this.allowedValues){this.minimum=this.allowedValues.min();this.maximum=this.allowedValues.max()}this.eventMouseDown=this.startDrag.bindAsEventListener(this);
this.eventMouseUp=this.endDrag.bindAsEventListener(this);this.eventMouseMove=this.update.bindAsEventListener(this);this.handles.each(function(h,i){i=slider.handles.length-1-i;slider.setValue(parseFloat((Object.isArray(slider.options.sliderValue)?slider.options.sliderValue[i]:slider.options.sliderValue)||slider.range.start),i);h.makePositioned().observe("mousedown",slider.eventMouseDown)});this.track.observe("mousedown",this.eventMouseDown);document.observe("mouseup",this.eventMouseUp);document.observe("mousemove",
this.eventMouseMove);this.initialized=true},dispose:function(){var slider=this;Event.stopObserving(this.track,"mousedown",this.eventMouseDown);Event.stopObserving(document,"mouseup",this.eventMouseUp);Event.stopObserving(document,"mousemove",this.eventMouseMove);this.handles.each(function(h){Event.stopObserving(h,"mousedown",slider.eventMouseDown)})},setDisabled:function(){this.disabled=true},setEnabled:function(){this.disabled=false},getNearestValue:function(value){if(this.allowedValues){if(value>=
this.allowedValues.max())return this.allowedValues.max();if(value<=this.allowedValues.min())return this.allowedValues.min();var offset=Math.abs(this.allowedValues[0]-value);var newValue=this.allowedValues[0];this.allowedValues.each(function(v){var currentOffset=Math.abs(v-value);if(currentOffset<=offset){newValue=v;offset=currentOffset}});return newValue}if(value>this.range.end)return this.range.end;if(value<this.range.start)return this.range.start;return value},setValue:function(sliderValue,handleIdx){if(!this.active){this.activeHandleIdx=
handleIdx||0;this.activeHandle=this.handles[this.activeHandleIdx];this.updateStyles()}handleIdx=handleIdx||this.activeHandleIdx||0;if(this.initialized&&this.restricted){if(handleIdx>0&&sliderValue<this.values[handleIdx-1])sliderValue=this.values[handleIdx-1];if(handleIdx<this.handles.length-1&&sliderValue>this.values[handleIdx+1])sliderValue=this.values[handleIdx+1]}sliderValue=this.getNearestValue(sliderValue);this.values[handleIdx]=sliderValue;this.value=this.values[0];this.handles[handleIdx].style[this.isVertical()?
"top":"left"]=this.translateToPx(sliderValue);this.drawSpans();if(!this.dragging||!this.event)this.updateFinished()},setValueBy:function(delta,handleIdx){this.setValue(this.values[handleIdx||this.activeHandleIdx||0]+delta,handleIdx||this.activeHandleIdx||0)},translateToPx:function(value){return Math.round((this.trackLength-this.handleLength)/(this.range.end-this.range.start)*(value-this.range.start))+"px"},translateToValue:function(offset){return offset/(this.trackLength-this.handleLength)*(this.range.end-
this.range.start)+this.range.start},getRange:function(range){var v=this.values.sortBy(Prototype.K);range=range||0;return $R(v[range],v[range+1])},minimumOffset:function(){return this.isVertical()?this.alignY:this.alignX},maximumOffset:function(){return this.isVertical()?(this.track.offsetHeight!=0?this.track.offsetHeight:this.track.style.height.replace(/px$/,""))-this.alignY:(this.track.offsetWidth!=0?this.track.offsetWidth:this.track.style.width.replace(/px$/,""))-this.alignX},isVertical:function(){return this.axis==
"vertical"},drawSpans:function(){var slider=this;if(this.spans)$R(0,this.spans.length-1).each(function(r){slider.setSpan(slider.spans[r],slider.getRange(r))});if(this.options.startSpan)this.setSpan(this.options.startSpan,$R(0,this.values.length>1?this.getRange(0).min():this.value));if(this.options.endSpan)this.setSpan(this.options.endSpan,$R(this.values.length>1?this.getRange(this.spans.length-1).max():this.value,this.maximum))},setSpan:function(span,range){if(this.isVertical()){span.style.top=this.translateToPx(range.start);
span.style.height=this.translateToPx(range.end-range.start+this.range.start)}else{span.style.left=this.translateToPx(range.start);span.style.width=this.translateToPx(range.end-range.start+this.range.start)}},updateStyles:function(){this.handles.each(function(h){Element.removeClassName(h,"selected")});Element.addClassName(this.activeHandle,"selected")},startDrag:function(event){if(Event.isLeftClick(event)){if(!this.disabled){this.active=true;var handle=Event.element(event);var pointer=[Event.pointerX(event),
Event.pointerY(event)];var track=handle;if(track==this.track){var offsets=this.track.cumulativeOffset();this.event=event;this.setValue(this.translateToValue((this.isVertical()?pointer[1]-offsets[1]:pointer[0]-offsets[0])-this.handleLength/2));var offsets=this.activeHandle.cumulativeOffset();this.offsetX=pointer[0]-offsets[0];this.offsetY=pointer[1]-offsets[1]}else{while(this.handles.indexOf(handle)==-1&&handle.parentNode)handle=handle.parentNode;if(this.handles.indexOf(handle)!=-1){this.activeHandle=
handle;this.activeHandleIdx=this.handles.indexOf(this.activeHandle);this.updateStyles();var offsets=this.activeHandle.cumulativeOffset();this.offsetX=pointer[0]-offsets[0];this.offsetY=pointer[1]-offsets[1]}}}Event.stop(event)}},update:function(event){if(this.active){if(!this.dragging)this.dragging=true;this.draw(event);if(Prototype.Browser.WebKit)window.scrollBy(0,0);Event.stop(event)}},draw:function(event){var pointer=[Event.pointerX(event),Event.pointerY(event)];var offsets=this.track.cumulativeOffset();
pointer[0]-=this.offsetX+offsets[0];pointer[1]-=this.offsetY+offsets[1];this.event=event;this.setValue(this.translateToValue(this.isVertical()?pointer[1]:pointer[0]));if(this.initialized&&this.options.onSlide)this.options.onSlide(this.values.length>1?this.values:this.value,this)},endDrag:function(event){if(this.active&&this.dragging){this.finishDrag(event,true);Event.stop(event)}this.active=false;this.dragging=false},finishDrag:function(event,success){this.active=false;this.dragging=false;this.updateFinished()},
updateFinished:function(){if(this.initialized&&this.options.onChange)this.options.onChange(this.values.length>1?this.values:this.value,this);this.event=null}});var Spinners={Version:"1.3.0"};
(function(g){function c(d,f){d=g.$(d);!d||(this.element=d.source,Spinners.remove(d),Spinners.removeDetached(),this.options=g.Object.extend({radii:[5,10],color:"#000",dashWidth:1.8,dashes:12,opacity:1,padding:3,speed:0.7,build:!0},f),this._position=0,this._state="stopped",this.options.build&&this.build(),Spinners.add(this))}function e(d){return d*Math.PI/180}g.Object.extend(Spinners,{spinners:[],enabled:!1,Required:{Bridge:"1.1.0"},support:{canvas:function(){var d=document.createElement("canvas");
return!!d.getContext&&!!d.getContext("2d")}()},insertScript:function(d){try{document.write("<script type='text/javascript' src='"+d+"'><\/script>")}catch(f){(document.head||Bridge.$$("head").source[0].source).appendChild(new Bridge.Element("script",{src:d,type:"text/javascript"}))}},require:function(d,f){(typeof window[d]=="undefined"||this.convertVersionString(window[d].Version)<this.convertVersionString(this.Required[d]))&&alert("Spinners requires "+(f||d)+" >= "+this.Required[d])},convertVersionString:function(d){var f=
d.replace(/_.*|\./g,"");f=parseInt(f+Bridge.String.times("0",4-f.length));return d.indexOf("_")>-1?f-1:f},start:function(){this.require("Bridge");if(!this.support.canvas&&!window.G_vmlCanvasManager){if(!window.attachEvent||navigator.userAgent.indexOf("Opera")!==-1)return;alert("Spinners requires ExplorerCanvas (excanvas.js)")}this.enabled=!0},get:function(d){if(d=g.$(d).source){var f=null;g._each(this.spinners,function(h){h.element==d&&(f=h)});return f}},add:function(d){this.spinners.push(d)},remove:function(d){(d=
this.get(d))&&(d.remove(),this.spinners=g.Array.without(this.spinners,d))},removeDetached:function(){return function(){g.each(this.spinners,function(d){if(d.element){var f;for(f=d.element;f&&f.parentNode;)f=f.parentNode;(!f||!f.body)&&this.remove(d.element)}},this)}}()});var b={drawRoundedRectangle:function(f,m){var n=g.Object.extend({top:0,left:0,width:0,height:0,radius:0},m||{}),d=n.left,h=n.top,k=n.width,l=n.height;n=n.radius;f.beginPath();f.moveTo(d+n,h);f.arc(d+k-n,h+n,n,e(-90),e(0),!1);f.arc(d+
k-n,h+l-n,n,e(0),e(90),!1);f.arc(d+n,h+l-n,n,e(90),e(180),!1);f.arc(d+n,h+n,n,e(-180),e(-90),!1);f.closePath();f.fill()}},a=function(){function d(i){var j=[];i.indexOf("#")==0&&(i=i.substring(1));i=i.toLowerCase();if(i.replace(f,"")!="")return null;i.length==3?(j[0]=i.charAt(0)+i.charAt(0),j[1]=i.charAt(1)+i.charAt(1),j[2]=i.charAt(2)+i.charAt(2)):(j[0]=i.substring(0,2),j[1]=i.substring(2,4),j[2]=i.substring(4));for(i=0;i<j.length;i++)j[i]=parseInt(j[i],16);j.red=j[0];j.green=j[1];j.blue=j[2];return j}
var f=RegExp("[0123456789abcdef]","g"),h=function(){function i(j,k,l){j=j.toString(l||10);return g.String.times("0",k-j.length)+j}return function(j,l,k){return"#"+i(j,2,16)+i(l,2,16)+i(k,2,16)}}();return{hex2rgb:d,hex2fill:function(i,k){g.Object.isUndefined(k)&&(k=1);var l=k,j=d(i);j[3]=l;j.opacity=l;return"rgba("+j.join()+")"},rgb2hex:h}}();g.Object.extend(c.prototype,function(){function d(){var f=this.options.speed*1E3/this.options.dashes;this.nextPosition();this._playTimer=window.setTimeout(g.Function.bind(d,
this),f)}return{remove:function(){!this.canvas||(this.stop(),this.canvas.remove(),this.canvas=null,this.ctx=null)},build:function(){this.remove();var f=this.getLayout().workspace.radius,h=f*2;g.$(this.element).insert(this.canvas=(new g.Element("canvas",{height:h,width:h})).setStyle({zoom:1}));window.G_vmlCanvasManager&&G_vmlCanvasManager.initElement(this.canvas.source);this.ctx=this.canvas.source.getContext("2d");this.ctx.globalAlpha=this.options.opacity;this.ctx.translate(f,f);this.drawPosition(0);
return this},getLayout:function(){if(this._layout)return this._layout;var s=this.options,q=s.dashes,r=s.radii,p=s.dashWidth,l=Math.min(r[0],r[1]);r=Math.max(r[0],r[1]);var n=Math.ceil(Math.max(Math.max(p,r),Math.sqrt(r*r+p/2*(p/2))));n+=s.padding;s=n;for(var o=1/q,m=[],j=0;j<q;j++)m.push((j+1)*o);return this._layout=q={workspace:{radius:s,opacities:m},dash:{position:{top:n-r,left:n-p/2},dimensions:{width:p,height:r-l}}}},_nextPosition:d,nextPosition:function(){this._position==this.options.dashes-
1&&(this._position=-1);this._position++;this.drawPosition(this._position)},drawPosition:function(h){var l=this.getLayout().workspace,f=l.radius*2,k=-1*l.radius,j=this.options.dashes;this.ctx.clearRect(k,k,f,f);f=e(360/j);l=l.opacities;h*=-1;h?(k=l.slice(0,h),h=l.slice(h,l.length).concat(k)):h=l;for(l=0;l<j;l++)this.drawDash(h[l],this.options.color),this.ctx.rotate(f)},drawDash:function(i,l){this.ctx.fillStyle=a.hex2fill(l,i);var h=this.getLayout(),k=h.workspace.radius,j=h.dash.position;h=h.dash.dimensions;
b.drawRoundedRectangle(this.ctx,{top:j.top-k,left:j.left-k,width:h.width,height:h.height,radius:Math.min(h.height,h.width)/2})},play:function(){if(this._state!="playing"){this._state="playing";var f=this.options.speed*1E3/this.options.dashes;this._playTimer=window.setTimeout(g.Function.bind(d,this),f);return this}},pause:function(){if(this._state!="paused")return this._pause(),this._state="paused",this},_pause:function(){!this._playTimer||(window.clearTimeout(this._playTimer),this._playTimer=null)},
stop:function(){if(this._state!="stopped")return this._pause(),this._position=0,this.drawPosition(0),this._state="stopped",this},toggle:function(){this[this._state=="playing"?"pause":"play"]();return this}}}());window.Spinner=c;Spinners.start();Spinners.enabled||(g.each(g.Object.keys(c.prototype),function(d){c.prototype[d]=g.K}),c=g.K,g.each("get add remove removeDetached".split(" "),function(d){Spinners[d]=g.K}))})(Bridge);window.Tipped||(Tipped={});
Bridge.Object.extend(Tipped.Skins||(Tipped.Skins={}),{"base":{afterUpdate:false,ajax:{cache:true,method:"post"},background:{color:"#f2f2f2",opacity:1},border:{size:1,color:"#111",opacity:1},closeButtonSkin:"default",containment:{selector:"viewport",flip:false},fadeDuration:0.18,showDelay:0.05,hideDelay:0,radius:{size:3,position:"background"},hideAfter:false,hideOn:{element:"self",event:"mouseleave"},hideOnClickOutside:false,hook:"topleft",offset:{x:0,y:0,mouse:{x:-12,y:-12}},onHide:false,onShow:false,
shadow:{blur:2,color:"#000",offset:{x:0,y:0},opacity:0.3},showOn:"mousemove",spinner:true,stem:{corner:{height:7,width:6},center:{height:6,width:10}},target:"self"},"reset":{ajax:false,closeButton:false,hideOn:[{element:"self",event:"mouseleave"},{element:"tooltip",event:"mouseleave"}],hook:"topmiddle",stem:true}});
Bridge.Object.extend(Tipped.CloseButtonSkins||(Tipped.CloseButtonSkins={}),{"base":{diameter:17,border:2,x:{diameter:10,size:2,opacity:1},states:{"default":{background:{color:[{position:0,color:"#1a1a1a"},{position:0.46,color:"#171717"},{position:0.53,color:"#121212"},{position:0.54,color:"#101010"},{position:1,color:"#000"}],opacity:1},x:{color:"#fafafa",opacity:1},border:{color:"#fff",opacity:1}},"hover":{background:{color:[{position:0,color:"#232323"},{position:0.46,color:"#202020"},{position:0.53,
color:"#1b1b1b"},{position:0.54,color:"#191919"},{position:1,color:"#0a0a0a"}],opacity:1},x:{color:"#fff",opacity:1},border:{color:"#fff",opacity:1}}},shadow:{blur:2,color:"#000",offset:{x:0,y:0},opacity:0.38}},"reset":{}});window.Tipped||(Tipped={});
Bridge.Object.extend(Tipped.Skins||(Tipped.Skins={}),{"black":{border:0,background:{color:"#000",opacity:0.8},shadow:{opacity:0.14,offset:{x:1,y:1}},spinner:{color:"#fff"}},"blackonblack":{border:{size:1,color:"#f7f7f7",opacity:0.3},background:{color:"#000",opacity:0.8},shadow:{opacity:0.15},spinner:{color:"#fff"}},"cloud":{border:{size:1,color:[{position:0,color:"#bec6d5"},{position:1,color:"#b1c2e3"}]},closeButtonSkin:"light",background:{color:[{position:0,color:"#f6fbfd"},{position:0.1,color:"#fff"},
{position:0.48,color:"#fff"},{position:0.5,color:"#fefffe"},{position:0.52,color:"#f7fbf9"},{position:0.8,color:"#edeff0"},{position:1,color:"#e2edf4"}]},shadow:{opacity:0.12}},"dark":{border:{size:1,color:"#1f1f1f",opacity:0.95},radius:{size:4},background:{color:[{position:0,color:"#898989"},{position:0.015,color:"#686766"},{position:0.48,color:"#3a3939"},{position:0.52,color:"#2e2d2d"},{position:0.54,color:"#2c2b2b"},{position:0.95,color:"#222"},{position:1,color:"#202020"}],opacity:0.9},shadow:{color:"#2f2f2f",
offset:{x:0,y:1},opacity:0.4},spinner:{color:"#ffffff"}},"lavender":{background:{color:[{position:0,color:"#c1c5d0"},{position:0.0010,color:"#b9bdca"},{position:0.05,color:"#b6bac7"},{position:0.5,color:"#9da2b4"},{position:1,color:"#7f85a0"}]},border:{color:[{position:0,color:"#a2a9be"},{position:1,color:"#6b7290"}],size:1},radius:1,shadow:{opacity:0.1}},"light":{border:{size:0,color:"#afafaf"},background:{color:[{position:0,color:"#fefefe"},{position:1,color:"#f7f7f7"}]},closeButtonSkin:"light",
radius:1,shadow:{opacity:0.35},stem:{corner:{height:8,width:8},center:{height:7,width:13}}},"limegreen":{border:{size:1,color:[{position:0,color:"#5a785f"},{position:0.05,color:"#0c7908"},{position:1,color:"#587d3c"}]},background:{color:[{position:0,color:"#b3e991"},{position:0.02,color:"#cef8be"},{position:0.09,color:"#7bc83f"},{position:0.35,color:"#77d228"},{position:0.65,color:"#85d219"},{position:0.8,color:"#abe041"},{position:1,color:"#c4f087"}]},shadow:{blur:1}},"liquid":{radius:{size:4},border:{size:1,
color:[{position:0,color:"#454545"},{position:1,color:"#101010"}]},background:{color:[{position:0,color:"#515562"},{position:0.3,color:"#252e43"},{position:0.48,color:"#111c34"},{position:0.52,color:"#161e32"},{position:0.54,color:"#0c162e"},{position:1,color:"#010c28"}],opacity:0.8},shadow:{color:"#021625"},spinner:{color:"#ffffff"}},"royalblue":{border:{color:[{position:0,color:"#113d71"},{position:1,color:"#1e5290"}]},background:{color:[{position:0,color:"#3a7ab8"},{position:0.48,color:"#346daa"},
{position:0.52,color:"#326aa6"},{position:1,color:"#2d609b"}]},shadow:{opacity:0.2},spinner:{color:"#f2f6f9"}},"salmon":{background:{color:[{position:0,color:"#fcdecd"},{position:0.0010,color:"#fde8db"},{position:0.05,color:"#fcdecd"},{position:0.5,color:"#fab993"},{position:1,color:"#f8b38b"}]},border:{color:[{position:0,color:"#eda67b"},{position:1,color:"#df946f"}],size:1},radius:1,shadow:{opacity:0.1}},"yellow":{border:{size:1,color:"#f7c735"},background:"#ffffaa",radius:1,shadow:{opacity:0.05}}});
Bridge.Object.extend(Tipped.CloseButtonSkins||(Tipped.CloseButtonSkins={}),{"default":{},"light":{diameter:17,border:2,x:{diameter:10,size:2,opacity:1},states:{"default":{background:{color:[{position:0,color:"#797979"},{position:0.48,color:"#717171"},{position:0.52,color:"#666"},{position:1,color:"#666"}],opacity:1},x:{color:"#fff",opacity:0.95},border:{color:"#676767",opacity:1}},"hover":{background:{color:[{position:0,color:"#868686"},{position:0.48,color:"#7f7f7f"},{position:0.52,color:"#757575"},
{position:1,color:"#757575"}],opacity:1},x:{color:"#fff",opacity:1},border:{color:"#767676",opacity:1}}},shadow:{blur:2,color:"#000",offset:{x:0,y:0},opacity:0.4}}});
eval(function(p,a,c,k,e,r){e=function(c){return(c<a?"":e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!"".replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return"\\w+"};c=1}while(c--)if(k[c])p=p.replace(new RegExp("\\b"+e(c)+"\\b","g"),k[c]);return p}('(M(f){M G(a,b,e){X(a=f.$(a)){L.13=a.1c,o.1q(L.13),o.2X(L),a=f.V.1U(b)||f.V.2M(b)?e||{}:b,L.R=o.5R(a),L.3f=b,L.22=L.R.22||+o.R.4g,L.1d={2Y:{P:1,Q:1},4N:[],3s:[],28:{4h:!1,4i:!1,1H:!1,3t:!1,1r:!1,4j:!1,4O:!1}},b=L.R.1j,L.1j=b=="2N"?"2N":b=="4k"||!b?L.13:b&&1I.7r(b)&&f.$(L.R.1j)||L.13,L.5S(),L.5T()}}M u(a,b){1K(S e 5U b){b[e]&&b[e].3u&&b[e].3u===V?(a[e]=f.V.1o(a[e])||{},u(a[e],b[e])):a[e]=b[e]}U a}M H(a,b){L.13=f.$(a).1c;!L.13||(L.R=f.V.1u({2O:5,1k:{x:0,y:0},1s:"#4P",1l:0.5,2r:1},b||{}),L.2b=L.R.2r,I.2X(L),L.1r(),L.4l())}M J(a,b,e){(L.13=f.$(a).1c)&&b&&(L.R=f.V.1u({2O:5,1k:{x:5,y:5},1s:"#5V",1l:0.5,2r:1},e||{}),L.2b=L.R.2r,L.1d={},C.2X(L),L.1r(),L.4l())}M K(a){X(a){L.13=f.$(a).1c,z.1q(L.13),a=L.1V(),L.R=f.V.1o(a.R),L.2b=1,L.1d={},z.2X(L),L.1t=L.R.14.1h,L.7s=L.R.17&&L.1t,L.1r()}}M F(a){U 1/W.5W(a)}M r(a){U a*W.2s/1W}M t(a){S b={},e;1K(e 5U a){b[e]=a[e]+"29"}U b}S v=f.V.1u({5X:"1.6.0.5",R:{}},1N.3P||{}),A=M(a){M b(b){U(b=5Y(b+"([\\\\d.]+)").7t(a))?7u(b[1]):!0}U{3v:!!1N.7v&&a.2Z("4m")===-1&&b("7w "),4m:a.2Z("4m")>-1&&b("4m/"),3Q:a.2Z("5Z/")>-1&&b("5Z/"),3w:a.2Z("3w")>-1&&a.2Z("7x")===-1&&b("7y:"),7z:!!a.1L(/7A.*7B.*7C/),4Q:a.2Z("4Q")>-1&&b("4Q/")}}(7D.7E);f.V.1u(v,M(){M a(a){1K(S c="",b=0;b<16;b++){c+="60".2P(W.3x(W.4R()*52))}a+="?="+c;4S{1I.7F("<3R 3g=\'61/62\' 3S=\'"+a+"\'><\\/3R>")}4T(d){(1I.4U||1I.7G("4U")[0]).63((1m f.1w("3R",{3S:a,3g:"61/62"})).1c)}}M b(a){(4V 1N[a]=="7H"||e(1N[a].5X)<e(c[a]))&&64("3P 65 "+a+" >= "+c[a])}M e(a){S c=a.4n(/4W.*|\\./g,""),c=3y(c+f.66.7I("0",4-c.1X));U a.2Z("4W")>-1?c-1:c}S c={4X:"1.1.2",4Y:"1.3.0"},d=M(){S a=1I.67("30");U!!a.3h&&!!a.3h("2d")}(),i;4S{i=!!1I.4o("7J")}4T(g){i=!1}U{3z:{30:d,4Z:i,4p:M(){S a=!1;f.1Y(["7K","7L","7M"],M(c){4S{1I.4o(c),a=!0}4T(b){}});U a}()},3T:M(){b("4X");X(!L.3z.30&&!1N.2c){X(A.3v){64("3P 65 7N (7O.3U)")}1E{U}}b("4Y");X(L.R&&L.R.2C){L.2C=L.R.2C||"",L.2C.7P(L.2C.1X-1)!="/"&&(L.2C+="/")}1E{S c=/1F([\\w\\d-4W.]+)?\\.3U(.*)/;f.$$("3R[3S]").1Y(M(a){a=a.1c.3S;X(a.1L(c)){L.2C=a.4n(c,"")}},L)}S d=v.31,e=v.4q;d&&d.3V&&d.3A&&e&&e.3V&&e.3A||a(L.2C+"3i-3V-3A.3U");d&&f.V.68(d).1X>2&&e&&f.V.68(e).1X>1||a(L.2C+"3i.3U");f.69(M(){o.6a()})},1O:M(a){o.1O(a);U L},1x:M(a){o.1x(a);U L},3j:M(a){o.3j(a);U L},1q:M(a){o.1q(a);a&&!f.V.2M(a)&&f.$$(a).1Y(M(a){a.1c.6b("3B","");a.1c.3W("3B");a.1c.3W("32-1F");a.1c.3W("32-1F-R")});U L},53:M(){o.53();U L},33:M(a){o.33(a);U L},54:M(a){o.54(a);U L},55:M(a){o.55(a);U L},1H:M(a){X(f.V.2M(a)){U o.56(a)}X(!f.V.57(a)){f.$$(a);S c=0;f.1Z(f.$$(a).1c,M(a){o.56(a&&a.1c)&&c++});U c}U o.3C().1X}}}());v.3T();(M(){M a(a,e){S c=f.V.58(a)?a:[f.$(a)],d=f.2t.59(e);f.1Z(c,M(a){a.1x()});d=1I.7Q(d.x,d.y);f.1Z(c,M(a){a.1O()});d&&(c=1I.4o("7R"),c.7S(e.3g,e.7T,e.7U,e.7V,e.7W,e.7X,e.7Y,e.7Z,e.80,e.81,e.82,e.83,e.84,e.85,e.86),d.87(c))}U 1I.4o?a:f.K})();S D={6c:M(a,b){S e=f.V.1u({2e:!1,6d:!1,O:0,N:0,P:0,Q:0,1a:0},b||{}),c=e.N,d=e.O,i=e.P,g=e.Q,j=e.1a;X(e.6d){S k=2*j;c-=j;d-=j;i+=k;g+=k}j?(a.24(),a.3D(c+j,d),e.2e=="2D"?a.Y(c+i,d):a.1M(c+i-j,d+j,j,r(-90),r(0),!1),e.2e=="2Q"?a.Y(c+i,d+g):a.1M(c+i-j,d+g-j,j,r(0),r(90),!1),e.2e=="2R"?a.Y(c,d+g):a.1M(c+j,d+g-j,j,r(90),r(1W),!1),e.2e=="2u"?a.Y(c,d):a.1M(c+j,d+j,j,r(-1W),r(-90),!1),a.25(),a.34()):a.6e(d,c,i,g)},88:M(a,b,e){1K(S e=f.V.1u({x:0,y:0,1s:"#4P"},e||{}),c=0,d=b.1X;c<d;c++){1K(S i=0,g=b[c].1X;i<g;i++){S j=3y(b[c].2P(i))*(1/9);a.2E=x.2F(e.1s,j);j&&a.6e(e.x+i,e.y+c,1,1)}}},3X:M(a,b,e){S c;f.V.1U(b)?c=x.2F(b):f.V.1U(b.1s)?c=x.2F(b.1s,f.V.2f(b.1l)?b.1l:1):f.V.58(b.1s)&&(e=f.V.1u({3E:0,3F:0,3G:0,3H:0},e||{}),c=D.6f.6g(a.89(e.3E,e.3F,e.3G,e.3H),b.1s,b.1l));U c},6f:{6g:M(a,b,e){1K(S e=f.V.2f(e)?e:1,c=0,d=b.1X;c<d;c++){S i=b[c];X(f.V.57(i.1l)||!f.V.2f(i.1l)){i.1l=1}a.8a(i.T,x.2F(i.1s,i.1l*e))}U a}}},s={3Y:["2u","4r","2D","35","4s","3k","2Q","4t","2R","3l","4u","2S"],3Z:{6h:/^(O|N|1P|1Q)(O|N|1P|1Q|26|1R)$/,1S:/^(O|1P)/,2T:/(26|1R)/,6i:/^(O|1P|N|1Q)/},6j:M(){S a={O:"Q",N:"P",1P:"Q",1Q:"P"};U M(b){U a[b]}}(),2T:M(a){U a.36().1L(L.3Z.2T)},4v:M(a){U!L.2T(a)},2v:M(a){U a.36().1L(L.3Z.1S)?"1S":"2g"},6k:M(a){U a.36().1L(L.3Z.6i)},3I:M(a){U a.36().1L(L.3Z.6h)}},E={3m:M(a){U a.R.17[s.4v(a.1t)?"2h":"1R"]},40:M(a,b,e){S e=f.V.1u({3J:"1y"},e||{}),c=s.2T(a.1t)?"1R":"2h",d=a.R.17[c],a=d.P,d=d.Q,d=L["1f"+f.66.8b(c)+"6l"](a,d,b);e.3J&&(d.P=W[e.3J](d.P),d.Q=W[e.3J](d.Q));U{P:d.P,Q:d.Q}},6m:M(a,b,e){S c=F(r(90-W.5a(b/a)*1W/W.2s))*e,c=e+a+c,b=a=c*b/a;a-=e;U{P:a*c/b,Q:a}},6n:M(a,b,e){e*=W.5W(r(1W-W.5a(b/a*0.5)*1W/W.2s-90));e=a+e*2;U{P:e,Q:e*b/a}},3K:M(a,b){S e=L.40(a,b),c=L.3m(a),d=s.2T(a.1t),f=W.1y(e.Q+b),g={2l:{Z:{P:W.1y(e.P),Q:W.1y(f)}},12:{Z:e,T:{O:0,N:0}},17:{Z:{P:c.P,Q:c.Q}}};d?g.17.T={O:f-c.Q,N:e.P*0.5-c.P*0.5}:g.17.T={O:f-c.Q,N:b};U g},3n:M(a,b,e){S c=s.2v(b.1t)=="2g",b=s.3I(b.1t),e={Q:e.2l.Z[c?"P":"Q"],P:e.2l.Z[c?"Q":"P"]},c=W.2w(e.P,e.Q),d=c/2,f=c/2,g=0,j=1,k=1,h=d,m=f;1z(b[1]){11"O":b[2]=="1Q"&&(h=f-(c-e.P),j=-1);1i;11"1Q":1z(b[2]){11"1P":h=f-(c-e.P);m=d-(c-e.Q);j=-1;g=90;1i;11"O":11"1R":11"26":g=5b,k=j=-1,h=f-(c-e.P)}1i;11"1P":1z(b[2]){11"N":g=1W;m=f-(c-e.Q);j=-1;1i;11"26":11"1R":11"1Q":m=d-(c-e.Q),h=f-(c-e.P),k=j=-1}1i;11"N":1z(b[2]){11"1P":g=90;m=f-(c-e.Q);j=k=-1;1i;11"O":11"26":11"1R":g=5b,j=-1}}a.6o(h,m);a.3n(r(g));a.8c(j,k)},5c:M(a,b,e,c,d){S c={O:0,N:0},i={O:0,N:0},g={O:0,N:0},j=f.V.1o(b);X(a.R.17){S k=s.6k(a.1t);k[1]=="O"?c.O=e.Q-d:k[1]=="N"&&(c.N=e.Q-d);S h=s.3I(a.1t),a=s.2v(a.1t);X(a=="1S"){1z(h[2]){11"26":11"1R":i.N=0.5*j.P-0.5*e.P;g.N=0.5*j.P;1i;11"1Q":i.N=j.P-e.P,g.N=j.P}h[1]=="1P"&&(i.O=j.Q-d,g.O=j.Q-d+e.Q)}1E{1z(h[2]){11"26":11"1R":i.O=0.5*j.Q-0.5*e.P;g.O=0.5*j.Q;1i;11"1P":i.O=j.Q-e.P,g.O=j.Q}h[1]=="1Q"&&(i.N=j.P-d,g.N=j.P-d+e.Q)}j[s.6j(k[1])]+=e.Q-d}1E{X(h=s.3I(a.1t),a=s.2v(a.1t),a=="1S"){1z(h[2]){11"26":11"1R":g.N=0.5*j.P;1i;11"1Q":g.N=j.P}h[1]=="1P"&&(g.O=j.Q)}1E{1z(h[2]){11"26":11"1R":g.O=0.5*j.Q;1i;11"1P":g.O=j.Q}h[1]=="1Q"&&(g.N=j.P)}}U{Z:j,T:{O:0,N:0},19:{T:c,Z:b},17:{T:i,Z:e},2a:g}}},x=M(){M a(a){S d=2x(3);a.2Z("#")==0&&(a=a.4w(1));a=a.36();X(a.4n(e,"")!=""){U 1p}a.1X==3?(d[0]=a.2P(0)+a.2P(0),d[1]=a.2P(1)+a.2P(1),d[2]=a.2P(2)+a.2P(2)):(d[0]=a.4w(0,2),d[1]=a.4w(2,4),d[2]=a.4w(4));1K(a=0;a<d.1X;a++){d[a]=3y(d[a],16)}U b(d)}M b(a){a.6p=a[0];a.6q=a[1];a.6r=a[2];U a}S e=5Y("[8d]","g");U{8e:a,2F:M(c,b){f.V.57(b)&&(b=1);S e=b,g=a(c);g[3]=e;g.1l=e;U"8f("+g.8g()+")"},8h:M(c){S c=a(c),c=b(c),d=c.6p,e=c.6q,f=c.6r,j,k=d>e?d:e;f>k&&(k=f);S h=d<e?d:e;f<h&&(h=f);c=k!=0?(k-h)/k:0;X(c==0){j=0}1E{S m=(k-d)/(k-h),q=(k-e)/(k-h),f=(k-f)/(k-h);d==k?j=f-q:e==k?j=2+m-f:j=4+q-m;j/=6;j<0&&(j+=1)}j=W.1A(j*6s);c=W.1A(c*6t);d=W.1A(k/8i*6t);e=[];e[0]=j;e[1]=c;e[2]=d;e.8j=j;e.8k=c;e.8l=d;U"#"+(e[2]>50?"4P":"5V")}}}(),z={3i:[],1f:M(a){X(a=f.$(a).1c){S b=1p;f.1Z(L.3i,M(e){e.13==a&&(b=e)});U b}},2X:M(a){L.3i.2m(a)},1q:M(a){(a=L.1f(a))&&(L.3i=f.2x.4x(L.3i,a),a.1q())}};f.V.1u(K.4y,M(){U{4z:M(){S a=L.1V();L.2Y=a.1d.2Y;a=a.R;L.1a=a.1a&&a.1a.27||0;L.12=a.12&&a.12.27||0;L.2G=a.2G;a=W.5d(L.2Y.Q,L.2Y.P);L.1a>a/2&&(L.1a=W.3x(a/2));L.R.1a.T=="12"&&L.1a>L.12&&(L.12=L.1a);L.1d={R:{1a:L.1a,12:L.12,2G:L.2G}}},6u:M(){L.1d.14={};S a=L.1t;f.1Y(s.3Y,M(a){S e;L.1d.14[a]={};L.1t=a;e=L.2i();L.1d.14[a].2a=e.2a;L.1d.14[a].1n={Z:e.1n.Z,T:{O:e.1n.T.O,N:e.1n.T.N}};L.1d.14[a].1h={Z:e.1B.Z};X(L.1b){e=L.1b.2i(),L.1d.14[a].2a=e.2a,L.1d.14[a].1n.T.O+=e.1B.T.O,L.1d.14[a].1n.T.N+=e.1B.T.N,L.1d.14[a].1h.Z=e.1h.Z}},L);L.1t=a},1r:M(){L.2U();1N.2c&&1N.2c.8m(1I);S a=L.1V(),b=L.R;L.1n=1m f.1w("1T",{"20":"8n"});a.4A.1G(L.1n);L.4z();L.6v(a);b.1g&&(L.6w(a),b.1g.1b&&(L.2H?(L.2H.R=b.1g.1b,L.2H.1r()):L.2H=1m H(L.13,f.V.1u({2r:L.2b},b.1g.1b))));L.4B();b.1b&&(L.1b?(L.1b.R=b.1b,L.1b.1r()):L.1b=1m J(L.13,L,f.V.1u({2r:L.2b},b.1b)));L.6u()},1q:M(){L.2U();L.R.1b&&(C.1q(L.13),L.R.1g&&L.R.1g.1b&&I.1q(L.13));L.15&&L.15.1q()},2U:M(){!L.1n||(L.1g&&(L.1g.1q(),L.1g=1p,L.5e=1p,L.5f=1p),L.1n.1q(),L.17=1p,L.19=1p,L.1n=1p,L.1d={})},1V:M(){U o.1f(L.13)},33:M(){S a=L.1V(),b=a.15.8o(".6x");X(b){b=f.$(b);b.1e({P:"5g",Q:"5g"});S e=3y(a.15.5h("O")),c=3y(a.15.5h("N")),d=3y(a.15.5h("P"));a.15.1e({N:"-6y",O:"-6y",P:"8p",Q:"5g"});S i=o.4C.5i(b);a.R.37&&f.V.2f(a.R.37)&&i.P>a.R.37&&(b.1e({P:a.R.37+"29"}),i=o.4C.5i(b));a.1d.2Y=i;a.15.1e({N:c+"29",O:e+"29",P:d+"29"});L.1r()}},41:M(a){L.1t!=a&&(L.1t=a,L.1r())},6w:M(a){S b=a.R.1g,b={P:b.3o+2*b.12,Q:b.3o+2*b.12};a.15.1G(L.1g=(1m f.1w("1T",{"20":"6z"})).1e(t(b)).1G(L.6A=(1m f.1w("1T",{"20":"8q"})).1e(t(b))));L.5j(a,"5k");L.5j(a,"5l");L.1g.38("3L",f.1C.39(L.6B,L)).38("5m",f.1C.39(L.6C,L))},5j:M(a,b){S e=a.R.1g,c=e.3o,d=e.12||0,i=e.x.3o,g=e.x.27,e=e.28[b||"5k"],j={P:c+2*d,Q:c+2*d};i>=c&&(i=c-2);S k;L.6A.1G(L[b+"8r"]=(1m f.1w("1T",{"20":"8s"})).1e(f.V.1u(t(j),{N:(b=="5l"?j.P:0)+"29"})).1G(k=1m f.1w("30",j)));1N.2c&&2c.42(k.1c);k=k.1c.3h("2d");k.2r=L.2b;k.6o(j.P/2,j.Q/2);k.2E=D.3X(k,e.19,{3E:0,3F:0-c/2,3G:0,3H:0+c/2});k.24();k.1M(0,0,c/2,0,W.2s*2,!0);k.25();k.34();d&&(k.2E=D.3X(k,e.12,{3E:0,3F:0-c/2-d,3G:0,3H:0+c/2+d}),k.24(),k.1M(0,0,c/2,W.2s,0,!1),k.Y((c+d)/2,0),k.1M(0,0,c/2+d,0,W.2s,!0),k.1M(0,0,c/2+d,W.2s,0,!0),k.Y(c/2,0),k.1M(0,0,c/2,0,W.2s,!1),k.25(),k.34());c=i/2;g/=2;g>c&&(d=g,g=c,c=d);k.2E=x.2F(e.x.1s||e.x,e.x.1l||1);k.3n(r(45));k.24();k.3D(0,0);k.Y(0,c);1K(e=0;e<4;e++){k.Y(0,c),k.Y(g,c),k.Y(g,c-(c-g)),k.Y(c,g),k.Y(c,0),k.3n(r(90))}k.25();k.34()},6v:M(){S a=L.2i(),b=L.R.17&&L.4D(),e=L.1t&&L.1t.36(),c=L.1a,d=L.12,i=0,g=0;c&&(i=L.R.1a.T=="19"?c:0,g=L.R.1a.T=="19"?c?c+d:0:c);c=o.5n(L.13);L.4E=1m f.1w("30",a.1n.Z);L.1n.1G(L.4E);1N.2c&&2c.42(L.4E.1c);S j=L.4E.1c.3h("2d");j.2r=L.2b;j.2E=D.3X(j,L.R.19,{3E:0,3F:a.19.T.O+d,3G:0,3H:a.19.T.O+a.19.Z.Q-d});j.8t=0;L.5o(j,{24:!0,25:!0,12:d,1a:i,3p:a,3q:b,17:L.R.17,3r:e,2e:c});j.34();X(d){S k=D.3X(j,L.R.12,{3E:0,3F:a.19.T.O,3G:0,3H:a.19.T.O+a.19.Z.Q});j.2E=k;L.5o(j,{24:!0,25:!1,12:d,1a:i,3p:a,3q:b,17:L.R.17,3r:e,2e:c});L.6D(j,{24:!1,25:!0,12:d,6E:i,1a:g,3p:a,3q:b,17:L.R.17,3r:e,2e:c});j.34()}},5o:M(a,b){S e=f.V.1u({17:!1,3r:1p,2e:1p,24:!1,25:!1,3p:1p,3q:1p,1a:0,12:0},b||{}),c=e.3p,d=e.3q,i=e.12,g=e.1a,j=e.3r,k=e.2e,h=c.19.T,m=c.19.Z,q,n,p,l;c.17&&(q=d.17.T,n=d.17.Z,p=d.2l.Z,l=c.17.T);c=h.N+i+g;d=h.O+i;e.24&&a.24();a.3D(c,d);X(e.17){1z(j){11"2u":c=q.N;a.3D(c,d);a.Y(c,d);d-=n.Q;a.Y(c,d);d+=n.Q;c+=n.P;a.Y(c,d);c+=p.P-n.P-q.N;a.Y(c,d);1i;11"4r":11"5p":c=h.N+m.P*0.5-n.P*0.5;a.Y(c,d);d-=n.Q;c+=n.P*0.5;a.Y(c,d);d+=n.Q;c+=n.P*0.5;a.Y(c,d);c=h.N+m.P*0.5-p.P*0.5;a.Y(c,d);1i;11"2D":c=l.N,c+=p.P-i-n.P,a.Y(c,d),d-=n.Q,c+=n.P,a.Y(c,d),d+=n.Q,a.Y(c,d)}}k=="2D"||k=="35"||!g?(c=h.N+m.P-i,d=h.O+i,a.Y(c,d)):g&&(a.1M(h.N+m.P-i-g,h.O+i+g,g,r(-90),r(0),!1),c=h.N+m.P-i,d=h.O+i+g);X(e.17){1z(j){11"35":c=l.N+n.Q;a.Y(c,d);c=l.N;d+=n.P;a.Y(c,d);1i;11"4s":11"5q":c=l.N;d=l.O+p.P*0.5-n.P*0.5;a.Y(c,d);c+=n.Q;d+=n.P*0.5;a.Y(c,d);c=l.N;d+=n.P*0.5;a.Y(c,d);1i;11"3k":c=l.N,d=l.O+p.P-q.N-n.P,a.Y(c,d),c+=n.Q,d+=n.P,a.Y(c,d),c=l.N,a.Y(c,d)}}k=="2Q"||k=="3k"||!g?(c=h.N+m.P-i,d=h.O+m.Q-i,a.Y(c,d)):g&&(a.1M(h.N+m.P-i-g,h.O+m.Q-i-g,g,r(0),r(90),!1),c=h.N+m.P-i-g,d=h.O+m.Q-i);X(e.17){1z(j){11"2Q":d+=n.Q;a.Y(c,d);c-=n.P;d=l.O;a.Y(c,d);1i;11"4t":11"5r":c=l.N+p.P*0.5+n.P*0.5;d=l.O;a.Y(c,d);c-=n.P*0.5;d+=n.Q;a.Y(c,d);c-=n.P*0.5;d=l.O;a.Y(c,d);1i;11"2R":c=l.N+q.N+n.P,d=l.O,a.Y(c,d),c-=n.P,d+=n.Q,a.Y(c,d),d=l.O,a.Y(c,d)}}k=="2R"||k=="3l"||!g?(c=h.N+i,d=h.O+m.Q-i,a.Y(c,d)):g&&(a.1M(h.N+i+g,h.O+m.Q-i-g,g,r(90),r(1W),!1),c=h.N+i,d=h.O+m.Q-i-g);X(e.17){1z(j){11"3l":c=l.N+p.Q;d=l.O+p.P-q.N;a.Y(c,d);c-=n.Q;a.Y(c,d);c+=n.Q;d-=n.P;a.Y(c,d);1i;11"4u":11"5s":c=l.N+p.Q;d=l.O+p.P*0.5+n.P*0.5;a.Y(c,d);c-=n.Q;d-=n.P*0.5;a.Y(c,d);c=l.N+p.Q;d-=n.P*0.5;a.Y(c,d);1i;11"2S":c=l.N+p.Q,d=l.O+q.N+n.P,a.Y(c,d),c-=n.Q,d-=n.P,a.Y(c,d),c=l.N+p.Q,a.Y(c,d)}}k=="2u"||k=="2S"||!g?(c=h.N+i,d=h.O+i,a.Y(c,d)):g&&(a.1M(h.N+i+g,h.O+i+g,g,r(-1W),r(-90),!1),c=h.N+i+g,d=h.O+i,c+=1,a.Y(c,d));e.25&&a.25();U{x:c,y:d}},6D:M(a,b){S e=f.V.1u({17:!1,3r:1p,2e:1p,24:!1,25:!1,3p:1p,3q:1p,1a:0,12:0},b||{}),c=e.3p,d=e.3q,i=e.12,g=e.1a,j=e.6E,k=e.3r,h=e.2e,m=c.19.T,q=c.19.Z,n,p,l,w;c.17&&(n=d.2l.Z,p=d.12.T,l=d.12.Z,w=c.17.T);c=m.N+i+j;d=m.O+i;X(k=="2u"||k=="2S"){c-=j}h!="2u"&&h!="2S"&&j&&(c+=1);j=f.V.1o({x:c,y:d});e.24&&a.24();d-=i;a.Y(c,d);i=f.V.1o({x:c,y:d});h=="2u"||h=="2S"||!g?(c=m.N,d=m.O,a.Y(c,d)):g&&(a.1M(m.N+g,m.O+g,g,r(-90),r(-1W),!0),c=m.N,d=m.O+g);X(e.17){1z(k){11"2S":c=w.N+p.O;d=w.O;a.Y(c,d);c+=l.Q;d+=l.P;a.Y(c,d);1i;11"4u":11"5s":c=w.N+p.O+l.Q;d=w.O+(n.P*0.5-l.P*0.5);a.Y(c,d);c-=l.Q;d+=l.P*0.5;a.Y(c,d);c+=l.Q;d+=l.P*0.5;a.Y(c,d);1i;11"3l":c=w.N+p.O+l.Q,d=w.O+n.P-l.P,a.Y(c,d),c-=l.Q,d+=l.P,a.Y(c,d),c+=l.Q,a.Y(c,d)}}h=="3l"||h=="2R"||!g?(c=m.N,d=m.O+q.Q,a.Y(c,d)):g&&(a.1M(m.N+g,m.O+q.Q-g,g,r(-1W),r(-5b),!0),c=m.N+g,d=m.O+q.Q);X(e.17){1z(k){11"2R":c=w.N;d=w.O+n.Q-p.O;a.Y(c,d);c+=l.P;d-=l.Q;a.Y(c,d);1i;11"4t":11"5r":c=w.N+n.P*0.5-l.P*0.5;d=w.O+n.Q-p.O-l.Q;a.Y(c,d);c+=l.P*0.5;d+=l.Q;a.Y(c,d);c+=l.P*0.5;d-=l.Q;a.Y(c,d);1i;11"2Q":c=w.N+n.P-l.P,d=w.O+n.Q-p.O-l.Q,a.Y(c,d),c+=l.P,d+=l.Q,a.Y(c,d),d-=l.Q,a.Y(c,d)}}h=="2Q"||h=="3k"||!g?(c=m.N+q.P,d=m.O+q.Q,a.Y(c,d)):g&&(a.1M(m.N+q.P-g,m.O+q.Q-g,g,r(90),r(0),!0),c=m.N,d=m.O+g);X(e.17){1z(k){11"3k":c=w.N+n.Q-p.O;a.Y(c,d);c-=l.Q;d-=l.P;a.Y(c,d);1i;11"4s":11"5q":c=w.N+n.Q-p.O-l.Q;d=w.O+n.P*0.5+l.P*0.5;a.Y(c,d);c+=l.Q;d-=l.P*0.5;a.Y(c,d);c-=l.Q;d-=l.P*0.5;a.Y(c,d);1i;11"35":c=w.N+n.Q-p.O-l.Q,d=w.O+l.P,a.Y(c,d),c+=l.Q,d-=l.P,a.Y(c,d),c-=l.Q,a.Y(c,d)}}h=="35"||h=="2D"||!g?(c=m.N+q.P,d=m.O,a.Y(c,d)):g&&a.1M(m.N+q.P-g,m.O+g,g,r(0),r(-90),!0);X(e.17){1z(k){11"2D":c=w.N+n.P;d=w.O+p.O;a.Y(c,d);c-=l.P;d+=l.Q;a.Y(c,d);1i;11"4r":11"5p":c=w.N+n.P*0.5+l.P*0.5;d=w.O+p.O+l.Q;a.Y(c,d);c-=l.P*0.5;d-=l.Q;a.Y(c,d);c-=l.P*0.5;d+=l.Q;a.Y(c,d);1i;11"2u":c=w.N+l.P,d=w.O+p.O+l.Q,a.Y(c,d),c-=l.P,d-=l.Q,a.Y(c,d),d+=l.Q,a.Y(c,d)}}a.Y(i.x,i.y);a.Y(j.x,j.y);e.25&&a.25()},6B:M(){S a=L.1V().R.1g;L.5e.1e({N:-1*(a.3o+a.12*2)+"29"});L.5f.1e({N:0})},6C:M(){S a=L.1V().R.1g,a=a.3o+a.12*2;L.5e.1e({N:0});L.5f.1e({N:a+"29"})},4D:M(){U E.3K(L,L.12)},2i:M(){S a=L.2Y,b=L.1V().R,e=L.1a,c=L.12,d=L.2G,a={P:c*2+d*2+a.P,Q:c*2+d*2+a.Q},f,g;X(L.R.17){f=L.4D().2l.Z,g=L.R.1a.T=="12"?e:e+c}S j=E.5c(L,a,f,g,c),d=j.Z,k=j.T,a=j.19.Z,h=j.19.T;f=j.17.T;g={O:0,N:0};S m,q,n,p={P:d.P,Q:d.Q};X(b.1g){m=e;b.1a.T=="19"&&(m+=c);e=m-W.6F(r(45))*m;c="1Q";L.1t.36().1L(/^(2D|35)$/)&&(c="N");b=b.1g.3o+2*b.1g.12;m={P:b,Q:b};g.N=h.N-b/2+(c=="N"?e:a.P-e);g.O=h.O-b/2+e;X(c=="N"){X(g.N<0){b=W.2y(g.N),p.P+=b,k.N+=b,g.N=0}}1E{b=g.N+b-p.P,b>0&&(p.P+=b)}X(g.O<0){b=W.2y(g.O),p.Q+=b,k.O+=b,g.O=0}X(L.R.1g.1b){q=L.R.1g.1b;n=q.2O;b=q.1k;q={P:m.P+2*n,Q:m.Q+2*n};n={O:g.O-n+b.y,N:g.N-n+b.x};X(c=="N"){X(n.N<0){b=W.2y(n.N),p.P+=b,k.N+=b,g.N+=b,n.N=0}}1E{b=n.N+q.P-p.P,b>0&&(p.P+=b)}X(n.O<0){b=W.2y(n.O),p.Q+=b,k.O+=b,g.O+=b,n.O=0}}}j=j.2a;j.O+=k.O;j.N+=k.N;a={1h:{Z:{P:W.1y(p.P),Q:W.1y(p.Q)}},1B:{Z:{P:W.1y(p.P),Q:W.1y(p.Q)}},1n:{Z:d,T:{O:W.1A(k.O),N:W.1A(k.N)}},19:{Z:{P:W.1y(a.P),Q:W.1y(a.Q)},T:{O:W.1A(h.O),N:W.1A(h.N)}},2a:{O:W.1A(j.O),N:W.1A(j.N)},3f:{T:{N:W.1y(k.N+h.N+L.12+L.R.2G),O:W.1y(k.O+h.O+L.12+L.R.2G)}}};L.R.17&&(a.17={T:{O:W.1A(f.O),N:W.1A(f.N)}});L.R.1g&&(a.1g={Z:{P:W.1y(m.P),Q:W.1y(m.Q)},T:{O:W.1A(g.O),N:W.1A(g.N)}},L.R.1g.1b&&(a.2H={Z:{P:W.1y(q.P),Q:W.1y(q.Q)},T:{O:W.1A(n.O),N:W.1A(n.N)}}));U a},4B:M(){S a=L.2i(),b=L.1V();b.15.1e(t(a.1h.Z));b.4A.1e(t(a.1B.Z));L.1n.1e(f.V.1u(t(a.1n.Z),t(a.1n.T)));L.1g&&(L.1g.1e(t(a.1g.T)),a.2H&&L.2H.15.1e(t(a.2H.T)));b.3a.1e(t(a.3f.T))},6G:M(a){L.2b=a||0;L.1b&&(L.1b.2b=L.2b)},8u:M(a){L.6G(a);L.1r()}}}());S C={2I:[],1f:M(a){X(a=f.$(a).1c){S b=1p;f.1Z(L.2I,M(e){e.13==a&&(b=e)});U b}},2X:M(a){L.2I.2m(a)},1q:M(a){(a=L.1f(a))&&(L.2I=f.2x.4x(L.2I,a),a.1q())},3M:{40:M(a,b){S e=z.1f(a.13),c=e.4D().12.Z,e=L["1f"+(s.2T(e.1t)?"8v":"8w")+"6l"](c.P,c.Q,b,{3J:!1});U{P:e.P,Q:e.Q}},6n:M(a,b,e){S c=a*0.5;e*=F(r(1W-W.6H(c/W.5t(c*c+b*b))*1W/W.2s-90));c=(c+e)*2;U{P:c,Q:c/a*b}},8x:M(a,b,e){a*=0.5;e*=F(r(1W-W.6H(a/W.5t(a*a+b*b))*1W/W.2s-90));U{P:(a+e)*2,Q:(a+e)/b*a}},6m:M(a,b,e){S c=e/W.6F(r(W.5a(b/a)*1W/W.2s)),e=e+a+c;U{P:e,Q:e*b/a}},3K:M(a){S b=z.1f(a.13),e=a.R.2O,c=s.4v(b.1t);s.2v(b.1t);b=C.3M.40(a,e);b={2l:{Z:{P:W.1y(b.P),Q:W.1y(b.Q)},T:{O:0,N:0}}};X(e){b.43=[];1K(S d=0;d<=e;d++){S i=C.3M.40(a,d,{3J:!1});b.43.2m({T:{O:b.2l.Z.Q-i.Q,N:c?e-d:(b.2l.Z.P-i.P)/2},Z:i})}}1E{b.43=[f.V.1o(b.2l)]}U b},3n:M(a,b,e){E.3n(a,b.2V(),e)}}};f.V.1u(J.4y,M(){U{4z:M(){},1q:M(){L.2U()},2U:M(){!L.15||(L.15.1q(),L.17=1p,L.19=1p,L.1n=1p,L.15=1p,L.1d={})},1r:M(){L.2U();L.4z();S a=L.1V(),b=L.2V();L.15=1m f.1w("1T",{"20":"8y"});a.15.1c.8z(L.15.1c,a.15.1c.44);L.15.1e({O:b.2i().1B.Z.Q+"29"});L.1n=1m f.1w("1T",{"20":"8A"});L.15.1G(L.1n);L.6I();b.R.17&&L.6J();L.4B()},1V:M(){U o.1f(L.13)},2V:M(){U z.1f(L.13)},2i:M(){S a=L.2V(),b=a.2i();L.1V();S e=L.R.2O,c=f.V.1o(b.19.Z);c.P+=2*e;c.Q+=2*e;S d,i;X(a.R.17){d=C.3M.3K(L).2l.Z,i=a.1a,a.R.1a&&a.R.1a.T=="19"&&(i+=a.12)}S g=E.5c(a,c,d,i,e);d=g.Z;i=g.T;S c=g.19.Z,j=g.19.T,g=g.17.T,k=b.1n.T,h=b.19.T,e={O:k.O+h.O-(j.O+e)+L.R.1k.y,N:k.N+h.N-(j.N+e)+L.R.1k.x},k=b.2a,h=b.1B.Z,m={O:0,N:0};X(e.O<0){S q=W.2y(e.O);m.O+=q;e.O=0;k.O+=q}X(e.N<0){q=W.2y(e.N),m.N+=q,e.N=0,k.N+=q}U{1h:{Z:{Q:W.2w(d.Q+e.O,h.Q+m.O),P:W.2w(d.P+e.N,h.P+m.N)}},1B:{Z:h,T:m},15:{Z:d,T:e},1n:{Z:d,T:{O:W.1A(i.O),N:W.1A(i.N)}},19:{Z:{P:W.1y(c.P),Q:W.1y(c.Q)},T:{O:W.1A(j.O),N:W.1A(j.N)}},17:{T:{O:W.1A(g.O),N:W.1A(g.N)}},2a:k,3f:{T:{N:W.1y(m.N+b.1n.T.N+b.19.T.N+a.12+a.2G),O:W.1y(m.O+b.1n.T.O+b.19.T.O+a.12+a.2G)}}}},3N:M(){U L.R.1l/(L.R.2O+1)},6I:M(){S a=L.2V(),b=a.2i(),e=f.V.1o(b.19.Z),c=L.1V(),d=L.R.2O,b=f.V.1o(b.19.Z);b.P+=2*d;b.Q+=2*d;S i=a.1d.R,a=i.1a,i=i.12;c.R.1a.T=="19"&&a&&(a+=i);L.1n.1G(L.19=(1m f.1w("1T",{"20":"8B"})).1e(t(b)).1G(L.5u=1m f.1w("30",b)));1N.2c&&2c.42(L.5u.1c);c=L.5u.1c.3h("2d");c.2r=L.2b;b=o.5n(L.13);c.2E=x.2F(L.R.1s,L.3N());1K(i=0;i<=d;i++){D.6c(c,{P:e.P+i*2,Q:e.Q+i*2,O:d-i,N:d-i,1a:a+i,2e:b})}},6J:M(){S a=L.2V(),b=C.3M.3K(L),e=b.2l.Z,c=s.4v(a.1t),d=s.2v(a.1t),i=W.2w(e.P,e.Q),a=i/2;i/=2;d={P:e[d=="2g"?"Q":"P"],Q:e[d=="2g"?"P":"Q"]};L.1n.1G(L.17=(1m f.1w("1T",{"20":"8C"})).1e(t(d)).1G(L.5v=1m f.1w("30",d)));1N.2c&&2c.42(L.5v.1c);d=L.5v.1c.3h("2d");d.2r=L.2b;C.3M.3n(d,L,b);d.2E=x.2F(L.R.1s,L.3N());d.2E=x.2F(L.R.1s,L.3N());1K(S g=0,j=b.43.1X;g<j;g++){S k=b.43[g];d.24();c?d.3D(k.T.N-a,k.T.O-i):d.3D(e.P/2-a,k.T.O-i);d.Y(k.T.N-a,e.Q-g-i);d.Y(k.T.N+k.Z.P-a,e.Q-g-i);d.25();d.34()}},4B:M(){S a=L.2i(),b=L.2V(),e=L.1V();e.15.1e(t(a.1h.Z));e.4A.1e(f.V.1u(t(a.1B.T),t(a.1B.Z)));X(e.R.1g){S c=b.2i(),d=a.1B.T,i=c.1g.T;b.1g.1e(t({O:d.O+i.O,N:d.N+i.N}));X(e.R.1g.1b){c=c.2H.T,b.2H.15.1e(t({O:d.O+c.O,N:d.N+c.N}))}}L.15.1e(f.V.1u(t(a.15.Z),t(a.15.T)));L.1n.1e(t(a.1n.Z));L.19.1e(t(a.19.T));b.R.17&&L.17.1e(t(a.17.T));e.3a.1e(t(a.3f.T))},4l:f.K}}());S I={2I:[],1f:M(a){X(a=f.$(a).1c){S b=1p;f.1Z(L.2I,M(e){e.13==a&&(b=e)});U b}},2X:M(a){L.2I.2m(a)},1q:M(a){(a=L.1f(a))&&(L.2I=f.2x.4x(L.2I,a),a.1q())}};f.V.1u(H.4y,M(){U{1r:M(){L.2U();L.1V();S a=L.2V(),b=a.2i().1g.Z,e=f.V.1o(b),c=L.R.2O;e.P+=c*2;e.Q+=c*2;a.1g.1G({8D:L.15=(1m f.1w("1T",{"20":"8E"})).1G(L.5w=1m f.1w("30",e))});1N.2c&&2c.42(L.5w.1c);a=L.5w.1c.3h("2d");a.2r=L.2b;a.2E=x.2F(L.R.1s,L.3N());1K(S d=e.P/2,e=e.Q/2,b=b.Q/2,i=0;i<=c;i++){a.24(),a.1M(d,e,b+i,r(0),r(6s),!0),a.25(),a.34()}},1q:M(){L.2U()},2U:M(){!L.15||(L.15.1q(),L.15=1p)},1V:M(){U o.1f(L.13)},2V:M(){U z.1f(L.13)},3N:M(){U L.R.1l/(L.R.2O+1)},4l:f.K}}());S o={2n:[],R:{4F:"5x",4g:8F},6a:M(){M a(){S a=["8G"],e=["2J"],c=f.$(1I.46);v.3z.4Z&&(a.2m("6K"),e.2m("6K"),f.$(1I.46).38("2J",M(){}));f.1Z(a,M(a){c.38(a,M(a){X((a=f.2t.5y(a,".1F[32-1F], .1F[3B]"))&&(a.47("3B")||a.47("32-1F"))){a=o.3b(a),a.R.2z&&f.2x.5z(a.R.2z,"3L")&&a.5A()}})});f.1Z(e,M(a){f.$(1I.6L).38(a,M(a){S c=f.2t.5y(a,".3O .6z, .3O .8H");c&&(f.2t.8I(a),o.6M(f.$(c).6N(".3O")).1x())})});A.3v&&A.3v<9||A.3w&&A.3w<2||A.3Q&&A.3Q<6O||f.2t.38(1N,"8J",f.1C.39(L.6P,L))}U a=f.1C.8K(a,M(a){1K(S e="",c=f.$$("4U").1c[0].1c,d=1I.67("3R"),i=0,g=W.3x(W.4R()*10+3);i<g;i++){e+="60".2P(W.3x(W.4R()*52))}v.3T[e]=a;d.3S=(v.2C+"1F-k.3U?g=3P&f=3T&k="+e).4n(/\\?(&|$)/,e+"$1");d.8L=M(){d.5B.8M(d);d=1p;6Q v.3T[e]};c.63(d)})}(),3b:M(a,b,e){X(a=f.$(a)){S c=a.1c,b=c.47("32-1F"),e=c.47("3B");X(!b){X(e){b=e}1E{U}}e=c.47("32-1F-R");e=f.V.1U(e)?8N("({"+e+"})"):e||{};c.6b("3B","");c.3W("32-1F");c.3W("32-1F-R");U 1m G(a,b,e)}},1f:M(a){X((a=f.$(a))&&(!a||a.1L(".1F"))){S b=1p;f.1Z(L.2n,M(e){e.13==a.1c&&(b=e)});U b}},6M:M(a){X(a=f.$(a).1c){S b=1p;f.1Z(L.2n,M(e){e.1D("1r")&&e.15.1c===a&&(b=e)});U b}},8O:M(a){S b=[];f.1Z(L.2n,M(e){e.13&&$(e.13).1L(a)&&b.2m(e)});U b},1O:M(a){X(f.V.2M(a)){X((a=f.$(a))&&(!a||a.1L(".1F"))){(a=L.1f(a)||L.3b(a))&&a.1O()}}1E{f.$$(a).1Y(M(a){a.1L(".1F")&&(a=L.1f(a)||L.3b(a))&&a.1O()},L)}},1x:M(a){f.V.2M(a)?(a=L.1f(a))&&a.1x():f.$$(a).1Y(M(a){(a=L.1f(a))&&a.1x()},L)},3j:M(a){X(f.V.2M(a)){S b=f.$(a);X(b&&(!b||b.1L(".1F"))){(a=L.1f(a)||L.3b(a))&&a.3j()}}1E{f.$$(a).1Y(M(a){a.1L(".1F")&&(a=L.1f(a)||L.3b(a))&&a.3j()},L)}},53:M(){f.1Y(L.3C(),M(a){a.1x()})},33:M(a){X(f.V.2M(a)){X((a=f.$(a))&&(!a||a.1L(".1F"))){(a=L.1f(a)||L.3b(a))&&a.33()}}1E{f.$$(a).1Y(M(a){a.1L(".1F")&&(a=L.1f(a)||L.3b(a))&&a.33()},L)}},6P:M(){S a=L.3C();f.1Z(a,M(a){a.T()})},3C:M(){S a=[];f.1Z(L.2n,M(b){b.1H()&&a.2m(b)});U a},56:M(a){X(!f.V.2M(a)){U!1}U!!f.2x.5C(L.3C()||[],M(b){U b.13==a})},1H:M(){U f.2x.5C(L.2n,M(a){U a.1H()})},6R:M(){S a=0,b;f.1Y(L.2n,M(e){e.22>a&&(a=e.22,b=e)});U b},6S:M(){L.3C().1X<=1&&f.1Z(L.2n,M(a){a.1D("1r")&&!a.R.22&&a.15.1e({22:a.22=+o.R.4g})})},2X:M(a){L.2n.2m(a)},5D:M(a){(a=L.1f(a))&&(a.1x(),a.1q(),L.2n=f.2x.4x(L.2n,a))},1q:M(a){f.V.2M(a)?L.5D(a):f.$$(a).1Y(f.1C.2K(M(a){L.5D(a)},L));L.6T()},6T:M(){U M(){f.1Y(L.2n,M(a){X(a.13){S b;1K(b=a.13;b&&b.5B;){b=b.5B}(!b||!b.46)&&L.1q(a.13)}},L)}}(),5n:M(a){S a=z.1f(a),b=!1;X(a.R.17&&a.1t){1z(a.1t.36()){11"2u":11"2S":b="2u";1i;11"2D":11"35":b="2D";1i;11"2R":11"3l":b="2R";1i;11"2Q":11"3k":b="2Q"}}U b},54:M(a){L.R.4F=a||"5x"},55:M(a){L.R.4g=a||0},5R:M(){M a(a){a.1B=a.1B||(v.31[o.R.4F]?o.R.4F:"5x");S b=a.1B?f.V.1o(v.31[a.1B]):{},b=u(f.V.1o(d),b),b=u(f.V.1o(b),a);b.1J&&(f.V.3c(b.1J)&&(b.1J={48:d.1J&&d.1J.48||c.1J.48,49:d.1J&&d.1J.49||c.1J.49}),b.1J=u(f.V.1o(c.1J),b.1J));b.19&&f.V.1U(b.19)&&(b.19={1s:b.19,1l:1});X(b.12){S h;f.V.2f(b.12)?h={27:b.12,1s:d.12&&d.12.1s||c.12.1s,1l:d.12&&d.12.1l||c.12.1l}:f.V.1U(b.12)?h={27:d.12&&d.12.27||c.12.27,1s:b.12,1l:d.12&&d.12.1l||c.12.1l}:h=u(f.V.1o(c.12),b.12);b.12=h.27===0?!1:h}X(b.1a){S m;f.V.2f(b.1a)?m={27:b.1a,T:d.1a&&d.1a.T||c.1a.T}:f.V.1U(b.1a)?m={27:d.1a&&d.1a.27||c.1a.27,T:b.T}:m=u(f.V.1o(c.1a),b.1a);b.1a=m.27===0?!1:m}S q;h=h=b.14&&b.14.1j||f.V.1U(b.14)&&b.14||d.14&&d.14.1j||f.V.1U(d.14)&&d.14||c.14&&c.14.1j||c.14;m=b.14&&b.14.1h||d.14&&d.14.1h||c.14&&c.14.1h||o.2o.5E(h);b.14?f.V.1U(b.14)?q={1j:b.14,1h:o.2o.5E(b.14)}:(q={1h:m,1j:h},b.14.1h&&(q.1h=b.14.1h),b.14.1j&&(q.1j=b.14.1j)):q={1h:m,1j:h};b.14=q;b.1j=="2N"?(h=u({},c.1k.2N),f.V.1u(h,v.31.3A.1k||{}),a.1B&&u(h,v.31[a.1B].1k||{}),h=v.31[a.1B],h.1k&&h.14?(m=f.V.1U(h.14)?h.14:h.14&&h.14.1j||c.14,h=o.2o.5F(h.1k,m,q.1j)):h=o.2o.5F(c.1k.2N,c.14,q.1j),a.1k&&(h=f.V.1u(h,a.1k||{}))):h={x:b.1k.x,y:b.1k.y};b.1k=h;X(b.1g&&b.6U){S a=f.V.1o(v.4q[b.6U]),n=u(f.V.1o(g),a);n.28&&f.1Y(["5k","5l"],M(a){S b=n.28[a],c=g.28&&g.28[a];X(b.19){S d=c&&c.19;f.V.2f(b.19)?b.19={1s:d&&d.1s||i.28[a].19.1s,1l:b.19}:f.V.1U(b.19)?(d=d&&f.V.2f(d.1l)&&d.1l||i.28[a].19.1l,b.19={1s:b.19,1l:d}):b.19=u(f.V.1o(i.28[a].19),b.19)}X(b.12){c=c&&c.12,f.V.2f(b.12)?b.12={1s:c&&c.1s||i.28[a].12.1s,1l:b.12}:f.V.1U(b.12)?(d=c&&f.V.2f(c.1l)&&c.1l||i.28[a].12.1l,b.12={1s:b.12,1l:d}):b.12=u(f.V.1o(i.28[a].12),b.12)}});X(n.1b){a=g.1b&&g.1b.3u&&g.1b.3u==V?g.1b:i.1b,n.1b.3u&&n.1b.3u==V&&(a=u(a,n.1b)),n.1b=a}b.1g=n}X(b.1b){S p;f.V.3c(b.1b)?d.1b&&f.V.3c(d.1b)?p=c.1b:d.1b?p=d.1b:p=c.1b:p=u(f.V.1o(c.1b),b.1b||{});f.V.2f(p.1k)&&(p.1k={x:p.1k,y:p.1k});b.1b=p}X(b.17){p={},f.V.3c(b.17)?p=u({},c.17):p=u(u({},c.17),f.V.1o(b.17)),f.V.2f(p.2h.1k)&&(p.2h.1k={x:p.2h.1k,y:p.2h.1k}),p.2h.6V&&(p.2h.1k={x:0,y:0}),!p.2h.6V&&b.1a&&b.1a.T=="12"&&p.2h.1k&&(p.2h.1k={x:W.2w(b.1a.27,p.2h.1k.x),y:W.2w(b.1a.27,p.2h.1k.y)}),b.17=p}X(b.1v){X(f.V.1U(b.1v)){p=d.1v&&d.1v.2A&&f.V.3c(d.1v.2A)?d.1v.2A:c.1v.2A,b.1v={4G:b.1v,2A:p}}1E{X(f.V.3c(b.1v)){p=d.1v&&d.1v.2A&&f.V.3c(d.1v.2A)?d.1v.2A:c.1v.2A,b.1v=b.1v?{4G:"6W",2A:p}:!1}}}X(b.21){X(f.V.58(b.21)){S l=[];f.1Z(b.21,M(a){l.2m(e(a))});b.21=l}1E{b.21=[e(b.21)]}}b.2z&&f.V.1U(b.2z)&&(b.2z=[""+b.2z]);b.2j&&f.V.3c(b.2j)&&(b.2j={});4Y.8P||(b.2j=!1);b.2G=0;U b}M b(e){c=v.31.3V;d=u(f.V.1o(c),v.31.3A);i=v.4q.3V;g=u(f.V.1o(i),v.4q.3A);b=a;U a(e)}M e(a){S b;f.V.1U(a)?b={13:d.21&&d.21.13||c.21.13,2p:a}:b=u(f.V.1o(c.21),a);U b}S c,d,i,g;U b}()};o.2o=M(){M a(a){S b=f.5G.6X(),c=a.R.1j;X(c=="2N"||c=="4k"){c=a.13}(c=f.$(c).6N(a.R.1v.4G))&&(c=f.$(c));X(!c||a.R.1v.4G=="6W"){U{Z:f.5G.3m(),T:b}}S a=c.5H(),d=c.6Y();a.N+=-1*(d.N-b.N);a.O+=-1*(d.O-b.O);U{Z:c.3m(),T:a}}M b(b,i,l,j){S h,m,o=z.1f(b.13),r=o.R.1k,y=g(l);y||!l?(m={P:1,Q:1},y?h={O:f.2t.8Q(l),N:f.2t.6Z(l)}:(l=b.1d.2p,h={O:l?l.y:0,N:l?l.x:0}),b.1d.2p={x:h.N,y:h.O}):(l=f.$(l),h=e(l),m=l.3m());l=f.V.1o(h);o=y?k(o.R.14.1h):o.R.14.1j;c(m,o);y=c(m,j);h={N:h.N+y.N,O:h.O+y.O};r=f.V.1o(r);r=q(r,o,j);h.O+=r.y;h.N+=r.x;o=z.1f(b.13);r=o.1d.14;y=f.V.1o(r[i]);h={O:h.O-y.2a.O,N:h.N-y.2a.N};y.1h.T=h;y={1S:!0,2g:!0};X(b.R.1v){S s=a(b),b=(b.R.1b?C.1f(b.13):o).2i().1h.Z;y.2L=d({Z:b,T:h},s);X(y.2L<1){X(h.N<s.T.N||h.N+b.P>s.T.N+s.Z.P){y.1S=!1}X(h.O<s.T.O||h.O+b.Q>s.T.O+s.Z.Q){y.2g=!1}}}1E{y.2L=1}b=r[i].1n;m=d({Z:m,T:l},{Z:b.Z,T:{O:h.O+b.T.O,N:h.N+b.T.N}});U{T:h,2L:{1j:m},4a:y,14:{1h:i,1j:j}}}M e(a){S a=f.$(a),b=a.5H(),a=a.6Y(),c=f.5G.6X();b.N+=-1*(a.N-c.N);b.O+=-1*(a.O-c.O);U b}M c(a,b){S c=s.3I(b),d={N:0,O:0};X(s.2v(b)=="1S"){1z(c[2]){11"26":11"1R":d.N=0.5*a.P;1i;11"1Q":d.N=a.P}c[1]=="1P"&&(d.O=a.Q)}1E{1z(c[2]){11"26":11"1R":d.O=0.5*a.Q;1i;11"1P":d.O=a.Q}c[1]=="1Q"&&(d.N=a.P)}U d}M d(a,b){S c=a.Z.P*a.Z.Q;U c?i(a.T.N,a.T.N+a.Z.P,b.T.N,b.T.N+b.Z.P)*i(a.T.O,a.T.O+a.Z.Q,b.T.O,b.T.O+b.Z.Q)/c:0}M i(a,b,c,d){S e=a>=c&&a<=d,f=b>=c&&b<=d;X(e&&f){U b-a}X(e&&!f){U d-a}X(!e&&f){U b-c}e=c>=a&&c<=b;f=d>=a&&d<=b;X(e&&f){U d-c}X(e&&!f){U b-c}X(!e&&f){U d-a}U 0}M g(a){U a&&(/^2N|2J|4Z$/.70(4V a.3g=="71"&&a.3g||"")||f.2t.6Z(a)>=0||a.8R>=0)}M j(b,c){X(b.R.1v){S d=c,e=a(b),f=e.Z,e=e.T,g=z.1f(b.13).1d.14[d.14.1h].1h.Z,i=d.T;e.N>i.N&&(d.T.N=e.N);e.O>i.O&&(d.T.O=e.O);e.N+f.P<i.N+g.P&&(d.T.N=e.N+f.P-g.P);e.O+f.Q<i.O+g.Q&&(d.T.O=e.O+f.Q-g.Q);c=d}b.41(c.14.1h);d=c.T;b.15.1e({O:d.O+"29",N:d.N+"29"})}M k(a,b){S c=s.3I(a),d=c[1],c=c[2],e=s.2v(a),g=f.V.1u({1S:!0,2g:!0},b||{});e=="1S"?(g.2g&&(d=h[d]),g.1S&&(c=h[c])):(g.2g&&(c=h[c]),g.1S&&(d=h[d]));U d+c}S h={N:"1Q",1Q:"N",O:"1P",1P:"O",26:"26",1R:"1R"},m=A.3v&&A.3v<9||A.3w&&A.3w<2||A.3Q&&A.3Q<6O,q=M(){S a=[[-1,-1],[0,-1],[1,-1],[-1,0],[0,0],[1,0],[-1,1],[0,1],[1,1]],b={2S:0,2u:0,4r:1,5p:1,2D:2,35:2,4s:5,5q:5,3k:8,2Q:8,4t:7,5r:7,2R:6,3l:6,4u:3,5s:3};U M(c,d,e){S f=a[b[d]],g=a[b[e]],f=[W.3x(W.2y(f[0]-g[0])*0.5)?-1:1,W.3x(W.2y(f[1]-g[1])*0.5)?-1:1];s.2T(e)&&(s.2v(e)=="1S"?d.1L(/^(O|1P)(26|1R)$/i)||(f[0]=0):d.1L(/^(N|1Q)(26|1R)$/i)||(f[1]=0));U{x:f[0]*c.x,y:f[1]*c.y}}}();U{1f:b,72:M(a,c,e,f){S g=b(a,c,e,f),i=/8S$/.70(e&&4V e.3g=="71"?e.3g:"");X(g.4a.2L===1){U j(a,g),g}S h=c,o=f;X(a.R.1v.2A||m&&i){g={1S:!g.4a.1S,2g:!g.4a.2g};X(s.2T(c)){X(s.2v(c)=="1S"&&g.2g||s.2v(c)=="2g"&&g.1S){h=k(c,g),o=k(f,g)}g=b(a,h,e,o);j(a,g);U g}h=k(c,g);o=k(f,g);g=b(a,h,e,o);j(a,g);U g}c=[];f=s.3Y;h=0;1K(o=f.1X;h<o;h++){1K(S i=f[h],q=0,r=s.3Y.1X;q<r;q++){c.2m(b(a,s.3Y[q],e,i))}}1K(S e=g,t=z.1f(a.13).1d.14,h=t[e.14.1h],f=0,v={N:e.T.N+h.2a.N,O:e.T.O+h.2a.O},r=0,u=1,A={Z:h.1h.Z,T:e.T},x=0,h=1,o=0,i=c.1X;o<i;o++){q=c[o];q.2W={};q.2W.1v=q.4a.2L;S B=t[q.14.1h].2a,B=W.5t(W.73(W.2y(q.T.N+B.N-v.N),2)+W.73(W.2y(q.T.O+B.O-v.O),2)),f=W.2w(f,B);q.2W.74=B;B=q.2L.1j;u=W.5d(u,B);r=W.2w(r,B);q.2W.75=B;B=d(A,{Z:t[q.14.1h].1h.Z,T:q.T});h=W.5d(h,B);x=W.2w(x,B);q.2W.76=B}1K(S t=0,C,r=W.2w(e.2L.1j-u,r-e.2L.1j),u=x-h,o=0,i=c.1X;o<i;o++){q=c[o],x=q.2W.1v*51,x+=(1-q.2W.74/f)*18||18,x+=(1-((W.2y(e.2L.1j-q.2W.75)||0)/r||1))*8,x+=((q.2W.76-h)/u||0)*23,t=W.2w(t,x),x==t&&(C=o)}j(a,c[C]);U g},5E:k,77:e,5F:q,5I:g}}();o.2o.5J={x:0,y:0};f.69(M(){S a=o.2o.5J;f.$(1I).38("4H",M(b){b=f.2t.59(b);a.x=b.x;a.y=b.y})});o.4C=M(){M a(a){U f.$(a).3m()}U{1r:M(){f.$(1I.46).1G((1m f.1w("1T",{"20":"8T"})).1G((1m f.1w("1T",{"20":"3O"})).1G(L.15=1m f.1w("1T",{"20":"78"}))))},3d:M(b,e){L.15||L.1r();b.R.79&&(e=f.$(e));S c;L.15.1G(c=(1m f.1w("1T",{"20":"6x 8U"})).3d(e));b.R.79&&e.1O();b.R.1B&&c.4b("8V"+b.R.1B);S d=a(c);b.R.37&&f.V.2f(b.R.37)&&d.P>b.R.37&&(c.1e({P:b.R.37+"29"}),d=a(c));b.1d.2Y=d;b.3a.3d(c)},5i:a}}();f.V.1u(G.4y,M(){U{1r:M(){X(!L.1D("1r")){f.$(1I.46).1G(L.15.1e({N:"-4I",O:"-4I",22:L.22}).1G(L.4A=1m f.1w("1T",{"20":"8W"})).1G(L.3a=1m f.1w("1T",{"20":"78"})));L.15.4b("8X"+L.R.1B);L.R.8Y&&L.2B(1I.6L,"2J",f.1C.39(M(a){L.1H()&&(a=f.2t.5y(a,".3O, .1F"),(!a||a&&a!=L.15.1c&&a!=L.13)&&L.1x())},L));X(v.3z.4p&&L.R.3e){L.15.4b("5K");S a=L.15.1c.8Z;a.91=L.R.3e+"s";a.92=L.R.3e+"s";a.93=L.R.3e+"s";a.94=L.R.3e+"s"}L.7a();L.2q("1r",!0)}},5S:M(){L.15=1m f.1w("1T",{"20":"3O"})},5L:M(){L.1r();S a=z.1f(L.13);a?a.1r():(1m K(L.13),L.2q("4j",!0))},5T:M(){L.2B(L.13,"3L",L.4c);L.2B(L.13,"5m",f.1C.2K(M(a){L.5M(a)},L));L.R.2z&&f.1Y(L.R.2z,M(a){S e=!1;a=="2J"&&(e=L.R.21&&!!f.2x.5C(L.R.21,M(a){U a.13=="4k"&&a.2p=="2J"}),L.2q("4O",e));L.2B(L.13,a,a=="2J"?e?L.3j:L.1O:f.1C.39(M(){L.5A()},L))},L);L.R.21&&f.1Y(L.R.21,M(a){S e;1z(a.13){11"4k":X(L.1D("4O")&&a.2p=="2J"){U}e=L.13;1i;11"1j":e=L.1j}!e||L.2B(e,a.2p,a.2p=="2J"?L.1x:f.1C.39(M(){L.5N()},L))},L);S a=!1;!L.R.7b&&L.R.2z&&((a=f.2x.5z(L.R.2z,"4H"))||f.2x.5z(L.R.2z,"7c"))&&L.1j=="2N"&&L.2B(L.13,a?"4H":"7c",M(a){!L.1D("4j")||L.T(a)})},7a:M(){L.2B(L.15,"3L",L.4c);L.2B(L.15,"5m",L.5M);L.2B(L.15,"3L",f.1C.39(L.1O,L));L.R.21&&f.1Y(L.R.21,M(a){S b;1z(a.13){11"1h":b=L.15}!b||L.2B(b,a.2p,a.2p.1L(/^(2J|4H|3L)$/)?L.1x:L.5N)},L)},1O:M(a){L.2k("1x");L.2k("4J");L.1H()||(L.2q("1H",!0),L.R.1J?L.7d(a):L.1D("3t")||L.3d(L.3f),L.1D("4j")&&L.T(a),L.4K(),L.R.4L&&f.1C.7e(f.1C.2K(M(){L.4c()},L),0.4d),f.V.7f(L.R.4M)&&(!L.R.1J||L.R.1J&&L.R.1J.48&&L.1D("3t"))&&L.R.4M(L.3a.1c.44,L.13),v.3z.4p&&L.R.3e&&L.15.4b("7g").7h("5K"))},1x:M(){L.2k("1O");!L.1D("1H")||(L.2q("1H",!1),v.3z.4p&&L.R.3e?(L.15.7h("7g").4b("5K"),L.4e("4J",f.1C.2K(L.5O,L),L.R.3e)):L.5O())},5O:M(){!L.1D("1r")||(L.15.1e({N:"-4I",O:"-4I"}),o.6S(),L.7i(),f.V.7f(L.R.7j)&&!L.2j&&L.R.7j(L.3a.1c.44,L.13))},3j:M(a){L[L.1H()?"1x":"1O"](a)},1H:M(){U L.1D("1H")},5A:M(a){L.2k("1x");L.2k("4J");!L.1D("1H")&&!L.5P("1O")&&L.4e("1O",f.1C.2K(M(a){L.2k("1O");L.1O(a)},L,a),L.R.95||0.4d)},5N:M(){L.2k("1O");!L.5P("1x")&&L.1D("1H")&&L.4e("1x",f.1C.2K(M(){L.2k("1x");L.2k("4J");L.1x()},L),L.R.96||0.4d)},2q:M(a,b){L.1d.28[a]=b},1D:M(a){U L.1d.28[a]},4c:M(){L.2q("4h",!0);L.1D("1H")&&L.4K();L.R.4L&&L.2k("5Q")},5M:M(){L.2q("4h",!1);L.R.4L&&L.4e("5Q",f.1C.2K(M(){L.2k("5Q");L.1D("4h")||L.1x()},L),L.R.4L)},5P:M(a){U L.1d.3s[a]},4e:M(a,b,e){L.1d.3s[a]=1N.7k(b,e*97)},2k:M(a){L.1d.3s[a]&&(1N.98(L.1d.3s[a]),6Q L.1d.3s[a])},2B:M(a,b,e,c){a=f.$(a);e=f.1C.39(e,c||L);L.1d.4N.2m({13:a,7l:b,7m:e});a.38(b,e)},7n:M(){f.1Z(L.1d.4N,M(a){a.13.99(a.7l,a.7m)})},41:M(a){S b=z.1f(L.13);b&&b.41(a)},7i:M(){L.41(L.R.14.1h)},33:M(){S a=z.1f(L.13);a&&(a.33(),L.1H()&&L.T())},3d:M(a,b){S e=f.V.1u({4f:L.R.4f},b||{});L.1r();o.4C.3d(L,a);L.5L();L.2q("3t",!0);e.4f&&e.4f(L.3a.1c.44,L.13)},7d:M(a){L.1D("4i")||L.R.1J.48&&L.1D("3t")||(L.2q("4i",!0),L.R.2j&&(L.2j?L.2j.7o():(L.2j=L.7p(L.R.2j),L.2q("3t",!1)),L.T(a)),1m f.9a.9b(L.3f,{49:L.R.1J.49,7q:L.R.1J.7q||{},9c:f.1C.2K(M(b){L.R.2j?(L.2j.1q(),L.2j=1p):L.5L();L.3d(b.9d);L.2q("4i",!1);L.1D("1H")&&(L.T(a),L.4K(),f.1C.7e(f.1C.2K(M(){L.4c()},L),0.4d),L.R.4M&&L.R.4M(L.3a.1c.44,L.13))},L)}))},7p:M(a){S b=1m f.1w("1T"),a=1m 9e(b,f.V.1u({1r:!1},a||{})),e=a.3K().9f.1a;b.1e({P:e*2+"29",Q:e*2+"29"});L.3d(b.1c,{4f:!1});a.1r();a.7o();U a},T:M(a){X(L.1H()){S b;X(L.R.1j=="2N"){X(o.2o.5I(a)){b=a}1E{b=o.2o.5J;X(L.R.7b&&(b.x||b.y)){L.1d.2p={x:b.x,y:b.y}}1E{X(!L.1d.2p){b=o.2o.77(L.13),L.1d.2p={x:b.N,y:b.O}}}b=1p}}1E{b=L.1j}o.2o.72(L,L.R.14.1h,b,L.R.14.1j);X(a&&o.2o.5I(a)){S e=L.15.3m(),a=f.2t.59(a);b=L.15.5H();a.x>=b.N&&a.x<=b.N+e.P&&a.y>=b.O&&a.y<=b.O+e.Q&&1N.7k(f.1C.2K(M(){L.2k("1x")},L),0.4d)}}},4K:M(){X(L.1D("1r")&&!L.R.22){S a=o.6R();a&&a!=L&&L.22<=a.22&&L.15.1e({22:L.22=a.22+1})}},1q:M(){L.7n();z.1q(L.13);L.1D("1r")&&L.15&&L.15.1q()}}}());1N.3P=v})(4X);',62,
574,"|||||||||||||||||||||||||||||||||||||||||||||||this|function|left|top|width|height|options|var|position|return|Object|Math|if|lineTo|dimensions||case|border|element|hook|container||stem||background|radius|shadow|source|_cache|setStyle|get|closeButton|tooltip|break|target|offset|opacity|new|bubble|clone|null|remove|build|color|_hookPosition|extend|containment|Element|hide|ceil|switch|round|skin|Function|getState|else|tipped|insert|visible|document|ajax|for|match|arc|window|show|bottom|right|center|horizontal|div|isString|getTooltip|180|length|each|_each|class|hideOn|zIndex||beginPath|closePath|middle|size|states|px|anchor|_globalAlpha|G_vmlCanvasManager||mergedCorner|isNumber|vertical|corner|getOrderLayout|spinner|clearTimer|box|push|tooltips|Position|event|setState|globalAlpha|PI|Event|topleft|getOrientation|max|Array|abs|showOn|flip|setEvent|path|topright|fillStyle|hex2fill|padding|closeButtonShadow|shadows|click|bind|overlap|isElement|mouse|blur|charAt|bottomright|bottomleft|lefttop|isCenter|cleanup|getSkin|score|add|contentDimensions|indexOf|canvas|Skins|data|refresh|fill|righttop|toLowerCase|maxWidth|observe|bindAsEventListener|contentElement|create|isBoolean|update|fadeDuration|content|type|getContext|skins|toggle|rightbottom|leftbottom|getDimensions|rotate|diameter|layout|stemLayout|hookPosition|timers|updated|constructor|IE|Gecko|floor|parseInt|support|reset|title|getVisible|moveTo|x1|y1|x2|y2|split|math|getLayout|mouseenter|Stem|getBlurOpacity|t_Tooltip|Tipped|WebKit|script|src|start|js|base|removeAttribute|createFillStyle|positions|regex|getBorderDimensions|setHookPosition|initElement|blurs|firstChild||body|getAttribute|cache|method|contained|addClassName|setActive|01|setTimer|afterUpdate|startingZIndex|active|xhr|skinned|self|startBlending|Opera|replace|createEvent|cssTransitions|CloseButtonSkins|topmiddle|rightmiddle|bottommiddle|leftmiddle|isCorner|substring|without|prototype|prepare|skinElement|order|UpdateQueue|getStemLayout|bubbleCanvas|defaultSkin|selector|mousemove|10000px|fadeTransition|raise|hideAfter|onShow|events|toggles|000|Chrome|random|try|catch|head|typeof|_|Bridge|Spinners|touch||||hideAll|setDefaultSkin|setStartingZIndex|isVisibleByElement|isUndefined|isArray|pointer|atan|270|getBubbleLayout|min|defaultCloseButton|hoverCloseButton|auto|getStyle|getMeasureElementDimensions|drawCloseButtonState|default|hover|mouseleave|getMergedCorner|_drawBackgroundPath|topcenter|rightcenter|bottomcenter|leftcenter|sqrt|backgroundCanvas|stemCanvas|closeButtonCanvas|black|findElement|include|showDelayed|parentNode|find|_remove|getInversedPosition|adjustOffsetBasedOnHooks|Viewport|cumulativeOffset|isPointerEvent|mouseBuffer|t_hidden|_buildSkin|setIdle|hideDelayed|_hide|getTimer|idle|createOptions|_preBuild|createPreBuildObservers|in|fff|cos|Version|RegExp|AppleWebKit|ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz|text|javascript|appendChild|alert|requires|String|createElement|keys|domloaded|startDelegating|setAttribute|drawRoundedRectangle|expand|fillRect|Gradient|addColorStops|toOrientation|side|toDimension|getSide|BorderDimensions|getCornerBorderDimensions|getCenterBorderDimensions|translate|red|green|blue|360|100|createHookCache|drawBubble|drawCloseButton|t_ContentContainer|25000px|t_Close|closeButtonShift|closeButtonMouseover|closeButtonMouseout|_drawBorderPath|backgroundRadius|sin|setGlobalAlpha|acos|drawBackground|drawStem|touchstart|documentElement|getByTooltipElement|up|530|onWindowResize|delete|getHighestTooltip|resetZ|removeDetached|closeButtonSkin|merged|viewport|getScrollOffsets|cumulativeScrollOffset|pointerX|test|string|set|pow|distance|targetOverlap|tooltipOverlap|getAbsoluteOffset|t_Content|inline|createPostBuildObservers|fixed|touchmove|ajaxUpdate|delay|isFunction|t_visible|removeClassName|resetHookPosition|onHide|setTimeout|eventName|handler|clearEvents|play|insertSpinner|parameters|getElementById|_stemPosition|exec|parseFloat|attachEvent|MSIE|KHTML|rv|MobileSafari|Apple|Mobile|Safari|navigator|userAgent|write|getElementsByTagName|undefined|times|TouchEvent|WebKitTransitionEvent|TransitionEvent|OTransitionEvent|ExplorerCanvas|excanvas|substr|elementFromPoint|MouseEvents|initMouseEvent|bubbles|cancelable|view|detail|screenX|screenY|clientX|clientY|ctrlKey|altKey|shiftKey|metaKey|button|relatedTarget|dispatchEvent|drawPixelArray|createLinearGradient|addColorStop|capitalize|scale|0123456789abcdef|hex2rgb|rgba|join|getSaturatedBW|255|hue|saturation|brightness|init_|t_Bubble|down|15000px|t_CloseButtonShift|CloseButton|t_CloseState|lineWidth|setOpacity|Center|Corner|getCenterBorderDimensions3|t_Shadow|insertBefore|t_ShadowBubble|t_ShadowBackground|t_ShadowStem|before|t_CloseButtonShadow|9999|mouseover|close|stop|resize|wrap|onload|removeChild|eval|getBySelector|enabled|pointerY|pageX|move|t_UpdateQueue|t_clearfix|t_Content_|t_Skin|t_Tooltip_|hideOnClickOutside|style||MozTransitionDuration|webkitTransitionDuration|OTransitionDuration|transitionDuration|showDelay|hideDelay|1000|clearTimeout|stopObserving|Ajax|Request|onComplete|responseText|Spinner|workspace".split("|"),
0,{}));

