var Prototype={Version:'1.5.1',Browser:{IE:!!(window.attachEvent&&!window.opera),Opera:!!window.opera,WebKit:navigator.userAgent.indexOf('AppleWebKit/')>-1,Gecko:navigator.userAgent.indexOf('Gecko')>-1&&navigator.userAgent.indexOf('KHTML')==-1},BrowserFeatures:{XPath:!!document.evaluate,ElementExtensions:!!window.HTMLElement,SpecificElementExtensions:(document.createElement('div').__proto__!==document.createElement('form').__proto__)},ScriptFragment:'<script[^>]*>([\u0001-\uFFFF]*?)</script>',JSONFilter:/^\/\*-secure-\s*(.*)\s*\*\/\s*$/,emptyFunction:function(){},K:function(x){return x}}
var Class={create:function(){return function(){this.initialize.apply(this,arguments);}}}
var Abstract=new Object();Object.extend=function(destination,source){for(var property in source){destination[property]=source[property];}
return destination;}
Object.extend(Object,{inspect:function(object){try{if(object===undefined)return'undefined';if(object===null)return'null';return object.inspect?object.inspect():object.toString();}catch(e){if(e instanceof RangeError)return'...';throw e;}},toJSON:function(object){var type=typeof object;switch(type){case'undefined':case'function':case'unknown':return;case'boolean':return object.toString();}
if(object===null)return'null';if(object.toJSON)return object.toJSON();if(object.ownerDocument===document)return;var results=[];for(var property in object){var value=Object.toJSON(object[property]);if(value!==undefined)
results.push(property.toJSON()+': '+value);}
return'{'+results.join(', ')+'}';},keys:function(object){var keys=[];for(var property in object)
keys.push(property);return keys;},values:function(object){var values=[];for(var property in object)
values.push(object[property]);return values;},clone:function(object){return Object.extend({},object);}});Function.prototype.bind=function(){var __method=this,args=$A(arguments),object=args.shift();return function(){return __method.apply(object,args.concat($A(arguments)));}}
Function.prototype.bindAsEventListener=function(object){var __method=this,args=$A(arguments),object=args.shift();return function(event){return __method.apply(object,[event||window.event].concat(args));}}
Object.extend(Number.prototype,{toColorPart:function(){return this.toPaddedString(2,16);},succ:function(){return this+1;},times:function(iterator){$R(0,this,true).each(iterator);return this;},toPaddedString:function(length,radix){var string=this.toString(radix||10);return'0'.times(length-string.length)+string;},toJSON:function(){return isFinite(this)?this.toString():'null';}});Date.prototype.toJSON=function(){return'"'+this.getFullYear()+'-'+
(this.getMonth()+1).toPaddedString(2)+'-'+
this.getDate().toPaddedString(2)+'T'+
this.getHours().toPaddedString(2)+':'+
this.getMinutes().toPaddedString(2)+':'+
this.getSeconds().toPaddedString(2)+'"';};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 PeriodicalExecuter=Class.create();PeriodicalExecuter.prototype={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*1000);},stop:function(){if(!this.timer)return;clearInterval(this.timer);this.timer=null;},onTimerEvent:function(){if(!this.currentlyExecuting){try{this.currentlyExecuting=true;this.callback(this);}finally{this.currentlyExecuting=false;}}}}
Object.extend(String,{interpret:function(value){return value==null?'':String(value);},specialChar:{'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\f','\r':'\\r','\\':'\\\\'}});Object.extend(String.prototype,{gsub:function(pattern,replacement){var result='',source=this,match;replacement=arguments.callee.prepareReplacement(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;},sub:function(pattern,replacement,count){replacement=this.gsub.prepareReplacement(replacement);count=count===undefined?1:count;return this.gsub(pattern,function(match){if(--count<0)return match[0];return replacement(match);});},scan:function(pattern,iterator){this.gsub(pattern,iterator);return this;},truncate:function(length,truncation){length=length||30;truncation=truncation===undefined?'...':truncation;return this.length>length?this.slice(0,length-truncation.length)+truncation:this;},strip:function(){return this.replace(/^\s+/,'').replace(/\s+$/,'');},stripTags:function(){return this.replace(/<\/?[^>]+>/gi,'');},stripScripts:function(){return this.replace(new RegExp(Prototype.ScriptFragment,'img'),'');},extractScripts:function(){var matchAll=new RegExp(Prototype.ScriptFragment,'img');var matchOne=new RegExp(Prototype.ScriptFragment,'im');return(this.match(matchAll)||[]).map(function(scriptTag){return(scriptTag.match(matchOne)||['',''])[1];});},evalScripts:function(){return this.extractScripts().map(function(script){return eval(script)});},escapeHTML:function(){var self=arguments.callee;self.text.data=this;return self.div.innerHTML;},unescapeHTML:function(){var div=document.createElement('div');div.innerHTML=this.stripTags();return div.childNodes[0]?(div.childNodes.length>1?$A(div.childNodes).inject('',function(memo,node){return memo+node.nodeValue}):div.childNodes[0].nodeValue):'';},toQueryParams:function(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());var value=pair.length>1?pair.join('='):pair[0];if(value!=undefined)value=decodeURIComponent(value);if(key in hash){if(hash[key].constructor!=Array)hash[key]=[hash[key]];hash[key].push(value);}
else hash[key]=value;}
return hash;});},toArray:function(){return this.split('');},succ:function(){return this.slice(0,this.length-1)+
String.fromCharCode(this.charCodeAt(this.length-1)+1);},times:function(count){var result='';for(var i=0;i<count;i++)result+=this;return result;},camelize:function(){var parts=this.split('-'),len=parts.length;if(len==1)return parts[0];var camelized=this.charAt(0)=='-'?parts[0].charAt(0).toUpperCase()+parts[0].substring(1):parts[0];for(var i=1;i<len;i++)
camelized+=parts[i].charAt(0).toUpperCase()+parts[i].substring(1);return camelized;},capitalize:function(){return this.charAt(0).toUpperCase()+this.substring(1).toLowerCase();},underscore:function(){return this.gsub(/::/,'/').gsub(/([A-Z]+)([A-Z][a-z])/,'#{1}_#{2}').gsub(/([a-z\d])([A-Z])/,'#{1}_#{2}').gsub(/-/,'_').toLowerCase();},dasherize:function(){return this.gsub(/_/,'-');},inspect:function(useDoubleQuotes){var escapedString=this.gsub(/[\x00-\x1f\\]/,function(match){var character=String.specialChar[match[0]];return character?character:'\\u00'+match[0].charCodeAt().toPaddedString(2,16);});if(useDoubleQuotes)return'"'+escapedString.replace(/"/g,'\\"')+'"';return"'"+escapedString.replace(/'/g,'\\\'')+"'";},toJSON:function(){return this.inspect(true);},unfilterJSON:function(filter){return this.sub(filter||Prototype.JSONFilter,'#{1}');},evalJSON:function(sanitize){var json=this.unfilterJSON();try{if(!sanitize||(/^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/.test(json)))
return eval('('+json+')');}catch(e){}
throw new SyntaxError('Badly formed JSON string: '+this.inspect());},include:function(pattern){return this.indexOf(pattern)>-1;},startsWith:function(pattern){return this.indexOf(pattern)===0;},endsWith:function(pattern){var d=this.length-pattern.length;return d>=0&&this.lastIndexOf(pattern)===d;},empty:function(){return this=='';},blank:function(){return/^\s*$/.test(this);}});if(Prototype.Browser.WebKit||Prototype.Browser.IE)Object.extend(String.prototype,{escapeHTML:function(){return this.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');},unescapeHTML:function(){return this.replace(/&amp;/g,'&').replace(/&lt;/g,'<').replace(/&gt;/g,'>');}});String.prototype.gsub.prepareReplacement=function(replacement){if(typeof replacement=='function')return replacement;var template=new Template(replacement);return function(match){return template.evaluate(match)};}
String.prototype.parseQuery=String.prototype.toQueryParams;Object.extend(String.prototype.escapeHTML,{div:document.createElement('div'),text:document.createTextNode('')});with(String.prototype.escapeHTML)div.appendChild(text);var Template=Class.create();Template.Pattern=/(^|.|\r|\n)(#\{(.*?)\})/;Template.prototype={initialize:function(template,pattern){this.template=template.toString();this.pattern=pattern||Template.Pattern;},evaluate:function(object){return this.template.gsub(this.pattern,function(match){var before=match[1];if(before=='\\')return match[2];return before+String.interpret(object[match[3]]);});}}
var $break={},$continue=new Error('"throw $continue" is deprecated, use "return" instead');var Enumerable={each:function(iterator){var index=0;try{this._each(function(value){iterator(value,index++);});}catch(e){if(e!=$break)throw e;}
return this;},eachSlice:function(number,iterator){var index=-number,slices=[],array=this.toArray();while((index+=number)<array.length)
slices.push(array.slice(index,index+number));return slices.map(iterator);},all:function(iterator){var result=true;this.each(function(value,index){result=result&&!!(iterator||Prototype.K)(value,index);if(!result)throw $break;});return result;},any:function(iterator){var result=false;this.each(function(value,index){if(result=!!(iterator||Prototype.K)(value,index))
throw $break;});return result;},collect:function(iterator){var results=[];this.each(function(value,index){results.push((iterator||Prototype.K)(value,index));});return results;},detect:function(iterator){var result;this.each(function(value,index){if(iterator(value,index)){result=value;throw $break;}});return result;},findAll:function(iterator){var results=[];this.each(function(value,index){if(iterator(value,index))
results.push(value);});return results;},grep:function(pattern,iterator){var results=[];this.each(function(value,index){var stringValue=value.toString();if(stringValue.match(pattern))
results.push((iterator||Prototype.K)(value,index));})
return results;},include:function(object){var found=false;this.each(function(value){if(value==object){found=true;throw $break;}});return found;},inGroupsOf:function(number,fillWith){fillWith=fillWith===undefined?null:fillWith;return this.eachSlice(number,function(slice){while(slice.length<number)slice.push(fillWith);return slice;});},inject:function(memo,iterator){this.each(function(value,index){memo=iterator(memo,value,index);});return memo;},invoke:function(method){var args=$A(arguments).slice(1);return this.map(function(value){return value[method].apply(value,args);});},max:function(iterator){var result;this.each(function(value,index){value=(iterator||Prototype.K)(value,index);if(result==undefined||value>=result)
result=value;});return result;},min:function(iterator){var result;this.each(function(value,index){value=(iterator||Prototype.K)(value,index);if(result==undefined||value<result)
result=value;});return result;},partition:function(iterator){var trues=[],falses=[];this.each(function(value,index){((iterator||Prototype.K)(value,index)?trues:falses).push(value);});return[trues,falses];},pluck:function(property){var results=[];this.each(function(value,index){results.push(value[property]);});return results;},reject:function(iterator){var results=[];this.each(function(value,index){if(!iterator(value,index))
results.push(value);});return results;},sortBy:function(iterator){return this.map(function(value,index){return{value:value,criteria:iterator(value,index)};}).sort(function(left,right){var a=left.criteria,b=right.criteria;return a<b?-1:a>b?1:0;}).pluck('value');},toArray:function(){return this.map();},zip:function(){var iterator=Prototype.K,args=$A(arguments);if(typeof args.last()=='function')
iterator=args.pop();var collections=[this].concat(args).map($A);return this.map(function(value,index){return iterator(collections.pluck(index));});},size:function(){return this.toArray().length;},inspect:function(){return'#<Enumerable:'+this.toArray().inspect()+'>';}}
Object.extend(Enumerable,{map:Enumerable.collect,find:Enumerable.detect,select:Enumerable.findAll,member:Enumerable.include,entries:Enumerable.toArray});var $A=Array.from=function(iterable){if(!iterable)return[];if(iterable.toArray){return iterable.toArray();}else{var results=[];for(var i=0,length=iterable.length;i<length;i++)
results.push(iterable[i]);return results;}}
if(Prototype.Browser.WebKit){$A=Array.from=function(iterable){if(!iterable)return[];if(!(typeof iterable=='function'&&iterable=='[object NodeList]')&&iterable.toArray){return iterable.toArray();}else{var results=[];for(var i=0,length=iterable.length;i<length;i++)
results.push(iterable[i]);return results;}}}
Object.extend(Array.prototype,Enumerable);if(!Array.prototype._reverse)
Array.prototype._reverse=Array.prototype.reverse;Object.extend(Array.prototype,{_each:function(iterator){for(var i=0,length=this.length;i<length;i++)
iterator(this[i]);},clear:function(){this.length=0;return this;},first:function(){return this[0];},last:function(){return this[this.length-1];},compact:function(){return this.select(function(value){return value!=null;});},flatten:function(){return this.inject([],function(array,value){return array.concat(value&&value.constructor==Array?value.flatten():[value]);});},without:function(){var values=$A(arguments);return this.select(function(value){return!values.include(value);});},indexOf:function(object){for(var i=0,length=this.length;i<length;i++)
if(this[i]==object)return i;return-1;},reverse:function(inline){return(inline!==false?this:this.toArray())._reverse();},reduce:function(){return this.length>1?this:this[0];},uniq:function(sorted){return this.inject([],function(array,value,index){if(0==index||(sorted?array.last()!=value:!array.include(value)))
array.push(value);return array;});},clone:function(){return[].concat(this);},size:function(){return this.length;},inspect:function(){return'['+this.map(Object.inspect).join(', ')+']';},toJSON:function(){var results=[];this.each(function(object){var value=Object.toJSON(object);if(value!==undefined)results.push(value);});return'['+results.join(', ')+']';}});Array.prototype.toArray=Array.prototype.clone;function $w(string){string=string.strip();return string?string.split(/\s+/):[];}
if(Prototype.Browser.Opera){Array.prototype.concat=function(){var array=[];for(var i=0,length=this.length;i<length;i++)array.push(this[i]);for(var i=0,length=arguments.length;i<length;i++){if(arguments[i].constructor==Array){for(var j=0,arrayLength=arguments[i].length;j<arrayLength;j++)
array.push(arguments[i][j]);}else{array.push(arguments[i]);}}
return array;}}
var Hash=function(object){if(object instanceof Hash)this.merge(object);else Object.extend(this,object||{});};Object.extend(Hash,{toQueryString:function(obj){var parts=[];parts.add=arguments.callee.addPair;this.prototype._each.call(obj,function(pair){if(!pair.key)return;var value=pair.value;if(value&&typeof value=='object'){if(value.constructor==Array)value.each(function(value){parts.add(pair.key,value);});return;}
parts.add(pair.key,value);});return parts.join('&');},toJSON:function(object){var results=[];this.prototype._each.call(object,function(pair){var value=Object.toJSON(pair.value);if(value!==undefined)results.push(pair.key.toJSON()+': '+value);});return'{'+results.join(', ')+'}';}});Hash.toQueryString.addPair=function(key,value,prefix){key=encodeURIComponent(key);if(value===undefined)this.push(key);else this.push(key+'='+(value==null?'':encodeURIComponent(value)));}
Object.extend(Hash.prototype,Enumerable);Object.extend(Hash.prototype,{_each:function(iterator){for(var key in this){var value=this[key];if(value&&value==Hash.prototype[key])continue;var pair=[key,value];pair.key=key;pair.value=value;iterator(pair);}},keys:function(){return this.pluck('key');},values:function(){return this.pluck('value');},merge:function(hash){return $H(hash).inject(this,function(mergedHash,pair){mergedHash[pair.key]=pair.value;return mergedHash;});},remove:function(){var result;for(var i=0,length=arguments.length;i<length;i++){var value=this[arguments[i]];if(value!==undefined){if(result===undefined)result=value;else{if(result.constructor!=Array)result=[result];result.push(value)}}
delete this[arguments[i]];}
return result;},toQueryString:function(){return Hash.toQueryString(this);},inspect:function(){return'#<Hash:{'+this.map(function(pair){return pair.map(Object.inspect).join(': ');}).join(', ')+'}>';},toJSON:function(){return Hash.toJSON(this);}});function $H(object){if(object instanceof Hash)return object;return new Hash(object);};if(function(){var i=0,Test=function(value){this.key=value};Test.prototype.key='foo';for(var property in new Test('bar'))i++;return i>1;}())Hash.prototype._each=function(iterator){var cache=[];for(var key in this){var value=this[key];if((value&&value==Hash.prototype[key])||cache.include(key))continue;cache.push(key);var pair=[key,value];pair.key=key;pair.value=value;iterator(pair);}};ObjectRange=Class.create();Object.extend(ObjectRange.prototype,Enumerable);Object.extend(ObjectRange.prototype,{initialize:function(start,end,exclusive){this.start=start;this.end=end;this.exclusive=exclusive;},_each:function(iterator){var value=this.start;while(this.include(value)){iterator(value);value=value.succ();}},include:function(value){if(value<this.start)
return false;if(this.exclusive)
return value<this.end;return value<=this.end;}});var $R=function(start,end,exclusive){return new ObjectRange(start,end,exclusive);}
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(typeof responder[callback]=='function'){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=function(){};Ajax.Base.prototype={setOptions:function(options){this.options={method:'post',asynchronous:true,contentType:'application/x-www-form-urlencoded',encoding:'UTF-8',parameters:''}
Object.extend(this.options,options||{});this.options.method=this.options.method.toLowerCase();if(typeof this.options.parameters=='string')
this.options.parameters=this.options.parameters.toQueryParams();}}
Ajax.Request=Class.create();Ajax.Request.Events=['Uninitialized','Loading','Loaded','Interactive','Complete'];Ajax.Request.prototype=Object.extend(new Ajax.Base(),{_complete:false,initialize:function(url,options){this.transport=Ajax.getTransport();this.setOptions(options);this.request(url);},request:function(url){this.url=url;this.method=this.options.method;var params=Object.clone(this.options.parameters);if(!['get','post'].include(this.method)){params['_method']=this.method;this.method='post';}
this.parameters=params;if(params=Hash.toQueryString(params)){if(this.method=='get')
this.url+=(this.url.include('?')?'&':'?')+params;else if(/Konqueror|Safari|KHTML/.test(navigator.userAgent))
params+='&_=';}
try{if(this.options.onCreate)this.options.onCreate(this.transport);Ajax.Responders.dispatch('onCreate',this,this.transport);this.transport.open(this.method.toUpperCase(),this.url,this.options.asynchronous);if(this.options.asynchronous)
setTimeout(function(){this.respondToReadyState(1)}.bind(this),10);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(typeof extras.push=='function')
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(){return!this.transport.status||(this.transport.status>=200&&this.transport.status<300);},respondToReadyState:function(readyState){var state=Ajax.Request.Events[readyState];var transport=this.transport,json=this.evalJSON();if(state=='Complete'){try{this._complete=true;(this.options['on'+this.transport.status]||this.options['on'+(this.success()?'Success':'Failure')]||Prototype.emptyFunction)(transport,json);}catch(e){this.dispatchException(e);}
var contentType=this.getHeader('Content-type');if(contentType&&contentType.strip().match(/^(text|application)\/(x-)?(java|ecma)script(;.*)?$/i))
this.evalResponse();}
try{(this.options['on'+state]||Prototype.emptyFunction)(transport,json);Ajax.Responders.dispatch('on'+state,this,transport,json);}catch(e){this.dispatchException(e);}
if(state=='Complete'){this.transport.onreadystatechange=Prototype.emptyFunction;}},getHeader:function(name){try{return this.transport.getResponseHeader(name);}catch(e){return null}},evalJSON:function(){try{var json=this.getHeader('X-JSON');return json?json.evalJSON():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.Updater=Class.create();Object.extend(Object.extend(Ajax.Updater.prototype,Ajax.Request.prototype),{initialize:function(container,url,options){this.container={success:(container.success||container),failure:(container.failure||(container.success?null:container))}
this.transport=Ajax.getTransport();this.setOptions(options);var onComplete=this.options.onComplete||Prototype.emptyFunction;this.options.onComplete=(function(transport,param){this.updateContent();onComplete(transport,param);}).bind(this);this.request(url);},updateContent:function(){var receiver=this.container[this.success()?'success':'failure'];var response=this.transport.responseText;if(!this.options.evalScripts)response=response.stripScripts();if(receiver=$(receiver)){if(this.options.insertion)
new this.options.insertion(receiver,response);else
receiver.update(response);}
if(this.success()){if(this.onComplete)
setTimeout(this.onComplete.bind(this),10);}}});Ajax.PeriodicalUpdater=Class.create();Ajax.PeriodicalUpdater.prototype=Object.extend(new Ajax.Base(),{initialize:function(container,url,options){this.setOptions(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(request){if(this.options.decay){this.decay=(request.responseText==this.lastText?this.decay*this.options.decay:1);this.lastText=request.responseText;}
this.timer=setTimeout(this.onTimerEvent.bind(this),this.decay*this.frequency*1000);},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(typeof element=='string')
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(query.snapshotItem(i));return results;};document.getElementsByClassName=function(className,parentElement){var q=".//*[contains(concat(' ', @class, ' '), ' "+className+" ')]";return document._getElementsByXPath(q,parentElement);}}else document.getElementsByClassName=function(className,parentElement){var children=($(parentElement)||document.body).getElementsByTagName('*');var elements=[],child;for(var i=0,length=children.length;i<length;i++){child=children[i];if(Element.hasClassName(child,className))
elements.push(Element.extend(child));}
return elements;};if(!window.Element)var Element={};Element.extend=function(element){var F=Prototype.BrowserFeatures;if(!element||!element.tagName||element.nodeType==3||element._extended||F.SpecificElementExtensions||element==window)
return element;var methods={},tagName=element.tagName,cache=Element.extend.cache,T=Element.Methods.ByTag;if(!F.ElementExtensions){Object.extend(methods,Element.Methods),Object.extend(methods,Element.Methods.Simulated);}
if(T[tagName])Object.extend(methods,T[tagName]);for(var property in methods){var value=methods[property];if(typeof value=='function'&&!(property in element))
element[property]=cache.findOrStore(value);}
element._extended=Prototype.emptyFunction;return element;};Element.extend.cache={findOrStore:function(value){return this[value]=this[value]||function(){return value.apply(null,[this].concat($A(arguments)));}}};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).style.display='none';return element;},show:function(element){$(element).style.display='';return element;},remove:function(element){element=$(element);element.parentNode.removeChild(element);return element;},update:function(element,html){html=typeof html=='undefined'?'':html.toString();$(element).innerHTML=html.stripScripts();setTimeout(function(){html.evalScripts()},10);return element;},replace:function(element,html){element=$(element);html=typeof html=='undefined'?'':html.toString();if(element.outerHTML){element.outerHTML=html.stripScripts();}else{var range=element.ownerDocument.createRange();range.selectNodeContents(element);element.parentNode.replaceChild(range.createContextualFragment(html.stripScripts()),element);}
setTimeout(function(){html.evalScripts()},10);return element;},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();var value=(element[property]||'').toString();if(value)result+=' '+attribute+'='+value.inspect(true);});return result+'>';},recursivelyCollect:function(element,property){element=$(element);var elements=[];while(element=element[property])
if(element.nodeType==1)
elements.push(Element.extend(element));return elements;},ancestors:function(element){return $(element).recursivelyCollect('parentNode');},descendants:function(element){return $A($(element).getElementsByTagName('*')).each(Element.extend);},firstDescendant:function(element){element=$(element).firstChild;while(element&&element.nodeType!=1)element=element.nextSibling;return $(element);},immediateDescendants:function(element){if(!(element=$(element).firstChild))return[];while(element&&element.nodeType!=1)element=element.nextSibling;if(element)return[element].concat($(element).nextSiblings());return[];},previousSiblings:function(element){return $(element).recursivelyCollect('previousSibling');},nextSiblings:function(element){return $(element).recursivelyCollect('nextSibling');},siblings:function(element){element=$(element);return element.previousSiblings().reverse().concat(element.nextSiblings());},match:function(element,selector){if(typeof selector=='string')
selector=new Selector(selector);return selector.match($(element));},up:function(element,expression,index){element=$(element);if(arguments.length==1)return $(element.parentNode);var ancestors=element.ancestors();return expression?Selector.findElement(ancestors,expression,index):ancestors[index||0];},down:function(element,expression,index){element=$(element);if(arguments.length==1)return element.firstDescendant();var descendants=element.descendants();return expression?Selector.findElement(descendants,expression,index):descendants[index||0];},previous:function(element,expression,index){element=$(element);if(arguments.length==1)return $(Selector.handlers.previousElementSibling(element));var previousSiblings=element.previousSiblings();return expression?Selector.findElement(previousSiblings,expression,index):previousSiblings[index||0];},next:function(element,expression,index){element=$(element);if(arguments.length==1)return $(Selector.handlers.nextElementSibling(element));var nextSiblings=element.nextSiblings();return expression?Selector.findElement(nextSiblings,expression,index):nextSiblings[index||0];},getElementsBySelector:function(){var args=$A(arguments),element=$(args.shift());return Selector.findChildElements(element,args);},getElementsByClassName:function(element,className){return document.getElementsByClassName(className,element);},readAttribute:function(element,name){element=$(element);if(Prototype.Browser.IE){if(!element.attributes)return null;var t=Element._attributeTranslations;if(t.values[name])return t.values[name](element,name);if(t.names[name])name=t.names[name];var attribute=element.attributes[name];return attribute?attribute.nodeValue:null;}
return element.getAttribute(name);},getHeight:function(element){return $(element).getDimensions().height;},getWidth:function(element){return $(element).getDimensions().width;},classNames:function(element){return new Element.ClassNames(element);},hasClassName:function(element,className){if(!(element=$(element)))return;var elementClassName=element.className;if(elementClassName.length==0)return false;if(elementClassName==className||elementClassName.match(new RegExp("(^|\\s)"+className+"(\\s|$)")))
return true;return false;},addClassName:function(element,className){if(!(element=$(element)))return;Element.classNames(element).add(className);return element;},removeClassName:function(element,className){if(!(element=$(element)))return;Element.classNames(element).remove(className);return element;},toggleClassName:function(element,className){if(!(element=$(element)))return;Element.classNames(element)[element.hasClassName(className)?'remove':'add'](className);return element;},observe:function(){Event.observe.apply(Event,arguments);return $A(arguments).first();},stopObserving:function(){Event.stopObserving.apply(Event,arguments);return $A(arguments).first();},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);while(element=element.parentNode)
if(element==ancestor)return true;return false;},scrollTo:function(element){element=$(element);var pos=Position.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){var css=document.defaultView.getComputedStyle(element,null);value=css?css[style]:null;}
if(style=='opacity')return value?parseFloat(value):1.0;return value=='auto'?null:value;},getOpacity:function(element){return $(element).getStyle('opacity');},setStyle:function(element,styles,camelized){element=$(element);var elementStyle=element.style;for(var property in styles)
if(property=='opacity')element.setOpacity(styles[property])
else
elementStyle[(property=='float'||property=='cssFloat')?(elementStyle.styleFloat===undefined?'cssFloat':'styleFloat'):(camelized?property:property.camelize())]=styles[property];return element;},setOpacity:function(element,value){element=$(element);element.style.opacity=(value==1||value==='')?'':(value<0.00001)?0:value;return element;},getDimensions:function(element){element=$(element);var display=$(element).getStyle('display');if(display!='none'&&display!=null)
return{width:element.offsetWidth,height:element.offsetHeight};var els=element.style;var originalVisibility=els.visibility;var originalPosition=els.position;var originalDisplay=els.display;els.visibility='hidden';els.position='absolute';els.display='block';var originalWidth=element.clientWidth;var originalHeight=element.clientHeight;els.display=originalDisplay;els.position=originalPosition;els.visibility=originalVisibility;return{width:originalWidth,height:originalHeight};},makePositioned:function(element){element=$(element);var pos=Element.getStyle(element,'position');if(pos=='static'||!pos){element._madePositioned=true;element.style.position='relative';if(window.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.style.overflow||'auto';if((Element.getStyle(element,'overflow')||'visible')!='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;}};Object.extend(Element.Methods,{childOf:Element.Methods.descendantOf,childElements:Element.Methods.immediateDescendants});if(Prototype.Browser.Opera){Element.Methods._getStyle=Element.Methods.getStyle;Element.Methods.getStyle=function(element,style){switch(style){case'left':case'top':case'right':case'bottom':if(Element._getStyle(element,'position')=='static')return null;default:return Element._getStyle(element,style);}};}
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.0;}
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){element=$(element);var filter=element.getStyle('filter'),style=element.style;if(value==1||value===''){style.filter=filter.replace(/alpha\([^\)]*\)/gi,'');return element;}else if(value<0.00001)value=0;style.filter=filter.replace(/alpha\([^\)]*\)/gi,'')+'alpha(opacity='+(value*100)+')';return element;};Element.Methods.update=function(element,html){element=$(element);html=typeof html=='undefined'?'':html.toString();var tagName=element.tagName.toUpperCase();if(['THEAD','TBODY','TR','TD'].include(tagName)){var div=document.createElement('div');switch(tagName){case'THEAD':case'TBODY':div.innerHTML='<table><tbody>'+html.stripScripts()+'</tbody></table>';depth=2;break;case'TR':div.innerHTML='<table><tbody><tr>'+html.stripScripts()+'</tr></tbody></table>';depth=3;break;case'TD':div.innerHTML='<table><tbody><tr><td>'+html.stripScripts()+'</td></tr></tbody></table>';depth=4;}
$A(element.childNodes).each(function(node){element.removeChild(node)});depth.times(function(){div=div.firstChild});$A(div.childNodes).each(function(node){element.appendChild(node)});}else{element.innerHTML=html.stripScripts();}
setTimeout(function(){html.evalScripts()},10);return element;}}
else if(Prototype.Browser.Gecko){Element.Methods.setOpacity=function(element,value){element=$(element);element.style.opacity=(value==1)?0.999999:(value==='')?'':(value<0.00001)?0:value;return element;};}
Element._attributeTranslations={names:{colspan:"colSpan",rowspan:"rowSpan",valign:"vAlign",datetime:"dateTime",accesskey:"accessKey",tabindex:"tabIndex",enctype:"encType",maxlength:"maxLength",readonly:"readOnly",longdesc:"longDesc"},values:{_getAttr:function(element,attribute){return element.getAttribute(attribute,2);},_flag:function(element,attribute){return $(element).hasAttribute(attribute)?attribute:null;},style:function(element){return element.style.cssText.toLowerCase();},title:function(element){var node=element.getAttributeNode('title');return node.specified?node.nodeValue:null;}}};(function(){Object.extend(this,{href:this._getAttr,src:this._getAttr,type:this._getAttr,disabled:this._flag,checked:this._flag,readonly:this._flag,multiple:this._flag});}).call(Element._attributeTranslations.values);Element.Methods.Simulated={hasAttribute:function(element,attribute){var t=Element._attributeTranslations,node;attribute=t.names[attribute]||attribute;node=$(element).getAttributeNode(attribute);return node&&node.specified;}};Element.Methods.ByTag={};Object.extend(Element,Element.Methods);if(!Prototype.BrowserFeatures.ElementExtensions&&document.createElement('div').__proto__){window.HTMLElement={};window.HTMLElement.prototype=document.createElement('div').__proto__;Prototype.BrowserFeatures.ElementExtensions=true;}
Element.hasAttribute=function(element,attribute){if(element.hasAttribute)return element.hasAttribute(attribute);return Element.Methods.Simulated.hasAttribute(element,attribute);};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)});}
if(arguments.length==2){var tagName=methods;methods=arguments[1];}
if(!tagName)Object.extend(Element.Methods,methods||{});else{if(tagName.constructor==Array)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;var cache=Element.extend.cache;for(var property in methods){var value=methods[property];if(!onlyIfAbsent||!(property in destination))
destination[property]=cache.findOrStore(value);}}
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];window[klass]={};window[klass].prototype=document.createElement(tagName).__proto__;return window[klass];}
if(F.ElementExtensions){copy(Element.Methods,HTMLElement.prototype);copy(Element.Methods.Simulated,HTMLElement.prototype,true);}
if(F.SpecificElementExtensions){for(var tag in Element.Methods.ByTag){var klass=findDOMClass(tag);if(typeof klass=="undefined")continue;copy(T[tag],klass.prototype);}}
Object.extend(Element,Element.Methods);delete Element.ByTag;};var Toggle={display:Element.toggle};Abstract.Insertion=function(adjacency){this.adjacency=adjacency;}
Abstract.Insertion.prototype={initialize:function(element,content){this.element=$(element);this.content=content.stripScripts();if(this.adjacency&&this.element.insertAdjacentHTML){try{this.element.insertAdjacentHTML(this.adjacency,this.content);}catch(e){var tagName=this.element.tagName.toUpperCase();if(['TBODY','TR'].include(tagName)){this.insertContent(this.contentFromAnonymousTable());}else{throw e;}}}else{this.range=this.element.ownerDocument.createRange();if(this.initializeRange)this.initializeRange();this.insertContent([this.range.createContextualFragment(this.content)]);}
setTimeout(function(){content.evalScripts()},10);},contentFromAnonymousTable:function(){var div=document.createElement('div');div.innerHTML='<table><tbody>'+this.content+'</tbody></table>';return $A(div.childNodes[0].childNodes[0].childNodes);}}
var Insertion=new Object();Insertion.Before=Class.create();Insertion.Before.prototype=Object.extend(new Abstract.Insertion('beforeBegin'),{initializeRange:function(){this.range.setStartBefore(this.element);},insertContent:function(fragments){fragments.each((function(fragment){this.element.parentNode.insertBefore(fragment,this.element);}).bind(this));}});Insertion.Top=Class.create();Insertion.Top.prototype=Object.extend(new Abstract.Insertion('afterBegin'),{initializeRange:function(){this.range.selectNodeContents(this.element);this.range.collapse(true);},insertContent:function(fragments){fragments.reverse(false).each((function(fragment){this.element.insertBefore(fragment,this.element.firstChild);}).bind(this));}});Insertion.Bottom=Class.create();Insertion.Bottom.prototype=Object.extend(new Abstract.Insertion('beforeEnd'),{initializeRange:function(){this.range.selectNodeContents(this.element);this.range.collapse(this.element);},insertContent:function(fragments){fragments.each((function(fragment){this.element.appendChild(fragment);}).bind(this));}});Insertion.After=Class.create();Insertion.After.prototype=Object.extend(new Abstract.Insertion('afterEnd'),{initializeRange:function(){this.range.setStartAfter(this.element);},insertContent:function(fragments){fragments.each((function(fragment){this.element.parentNode.insertBefore(fragment,this.element.nextSibling);}).bind(this));}});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);var Selector=Class.create();Selector.prototype={initialize:function(expression){this.expression=expression.strip();this.compileMatcher();},compileMatcher:function(){if(Prototype.BrowserFeatures.XPath&&!(/\[[\w-]*?:/).test(this.expression))
return this.compileXPathMatcher();var e=this.expression,ps=Selector.patterns,h=Selector.handlers,c=Selector.criteria,le,p,m;if(Selector._cache[e]){this.matcher=Selector._cache[e];return;}
this.matcher=["this.matcher = function(root) {","var r = root, h = Selector.handlers, c = false, n;"];while(e&&le!=e&&(/\S/).test(e)){le=e;for(var i in ps){p=ps[i];if(m=e.match(p)){this.matcher.push(typeof c[i]=='function'?c[i](m):new Template(c[i]).evaluate(m));e=e.replace(m[0],'');break;}}}
this.matcher.push("return h.unique(n);\n}");eval(this.matcher.join('\n'));Selector._cache[this.expression]=this.matcher;},compileXPathMatcher:function(){var e=this.expression,ps=Selector.patterns,x=Selector.xpath,le,m;if(Selector._cache[e]){this.xpath=Selector._cache[e];return;}
this.matcher=['.//*'];while(e&&le!=e&&(/\S/).test(e)){le=e;for(var i in ps){if(m=e.match(ps[i])){this.matcher.push(typeof x[i]=='function'?x[i](m):new Template(x[i]).evaluate(m));e=e.replace(m[0],'');break;}}}
this.xpath=this.matcher.join('');Selector._cache[this.expression]=this.xpath;},findElements:function(root){root=root||document;if(this.xpath)return document._getElementsByXPath(this.xpath,root);return this.matcher(root);},match:function(element){return this.findElements(document).include(element);},toString:function(){return this.expression;},inspect:function(){return"#<Selector:"+this.expression.inspect()+">";}};Object.extend(Selector,{_cache:{},xpath:{descendant:"//*",child:"/*",adjacent:"/following-sibling::*[1]",laterSibling:'/following-sibling::*',tagName:function(m){if(m[1]=='*')return'';return"[local-name()='"+m[1].toLowerCase()+"' or local-name()='"+m[1].toUpperCase()+"']";},className:"[contains(concat(' ', @class, ' '), ' #{1} ')]",id:"[@id='#{1}']",attrPresence:"[@#{1}]",attr:function(m){m[3]=m[5]||m[6];return new Template(Selector.xpath.operators[m[2]]).evaluate(m);},pseudo:function(m){var h=Selector.xpath.pseudos[m[1]];if(!h)return'';if(typeof h==='function')return h(m);return new Template(Selector.xpath.pseudos[m[1]]).evaluate(m);},operators:{'=':"[@#{1}='#{3}']",'!=':"[@#{1}!='#{3}']",'^=':"[starts-with(@#{1}, '#{3}')]",'$=':"[substring(@#{1}, (string-length(@#{1}) - string-length('#{3}') + 1))='#{3}']",'*=':"[contains(@#{1}, '#{3}')]",'~=':"[contains(concat(' ', @#{1}, ' '), ' #{3} ')]",'|=':"[contains(concat('-', @#{1}, '-'), '-#{3}-')]"},pseudos:{'first-child':'[not(preceding-sibling::*)]','last-child':'[not(following-sibling::*)]','only-child':'[not(preceding-sibling::* or following-sibling::*)]','empty':"[count(*) = 0 and (count(text()) = 0 or translate(text(), ' \t\r\n', '') = '')]",'checked':"[@checked]",'disabled':"[@disabled]",'enabled':"[not(@disabled)]",'not':function(m){var e=m[6],p=Selector.patterns,x=Selector.xpath,le,m,v;var exclusion=[];while(e&&le!=e&&(/\S/).test(e)){le=e;for(var i in p){if(m=e.match(p[i])){v=typeof x[i]=='function'?x[i](m):new Template(x[i]).evaluate(m);exclusion.push("("+v.substring(1,v.length-1)+")");e=e.replace(m[0],'');break;}}}
return"[not("+exclusion.join(" and ")+")]";},'nth-child':function(m){return Selector.xpath.pseudos.nth("(count(./preceding-sibling::*) + 1) ",m);},'nth-last-child':function(m){return Selector.xpath.pseudos.nth("(count(./following-sibling::*) + 1) ",m);},'nth-of-type':function(m){return Selector.xpath.pseudos.nth("position() ",m);},'nth-last-of-type':function(m){return Selector.xpath.pseudos.nth("(last() + 1 - position()) ",m);},'first-of-type':function(m){m[6]="1";return Selector.xpath.pseudos['nth-of-type'](m);},'last-of-type':function(m){m[6]="1";return Selector.xpath.pseudos['nth-last-of-type'](m);},'only-of-type':function(m){var p=Selector.xpath.pseudos;return p['first-of-type'](m)+p['last-of-type'](m);},nth:function(fragment,m){var mm,formula=m[6],predicate;if(formula=='even')formula='2n+0';if(formula=='odd')formula='2n+1';if(mm=formula.match(/^(\d+)$/))
return'['+fragment+"= "+mm[1]+']';if(mm=formula.match(/^(-?\d*)?n(([+-])(\d+))?/)){if(mm[1]=="-")mm[1]=-1;var a=mm[1]?Number(mm[1]):1;var b=mm[2]?Number(mm[2]):0;predicate="[((#{fragment} - #{b}) mod #{a} = 0) and "+"((#{fragment} - #{b}) div #{a} >= 0)]";return new Template(predicate).evaluate({fragment:fragment,a:a,b:b});}}}},criteria:{tagName:'n = h.tagName(n, r, "#{1}", c);   c = false;',className:'n = h.className(n, r, "#{1}", c); c = false;',id:'n = h.id(n, r, "#{1}", c);        c = false;',attrPresence:'n = h.attrPresence(n, r, "#{1}"); c = false;',attr:function(m){m[3]=(m[5]||m[6]);return new Template('n = h.attr(n, r, "#{1}", "#{3}", "#{2}"); c = false;').evaluate(m);},pseudo:function(m){if(m[6])m[6]=m[6].replace(/"/g,'\\"');return new Template('n = h.pseudo(n, "#{1}", "#{6}", r, c); c = false;').evaluate(m);},descendant:'c = "descendant";',child:'c = "child";',adjacent:'c = "adjacent";',laterSibling:'c = "laterSibling";'},patterns:{laterSibling:/^\s*~\s*/,child:/^\s*>\s*/,adjacent:/^\s*\+\s*/,descendant:/^\s/,tagName:/^\s*(\*|[\w\-]+)(\b|$)?/,id:/^#([\w\-\*]+)(\b|$)/,className:/^\.([\w\-\*]+)(\b|$)/,pseudo:/^:((first|last|nth|nth-last|only)(-child|-of-type)|empty|checked|(en|dis)abled|not)(\((.*?)\))?(\b|$|\s|(?=:))/,attrPresence:/^\[([\w]+)\]/,attr:/\[((?:[\w-]*:)?[\w-]+)\s*(?:([!^$*~|]?=)\s*((['"])([^\]]*?)\4|([^'"][^\]]*?)))?\]/},handlers:{concat:function(a,b){for(var i=0,node;node=b[i];i++)
a.push(node);return a;},mark:function(nodes){for(var i=0,node;node=nodes[i];i++)
node._counted=true;return nodes;},unmark:function(nodes){for(var i=0,node;node=nodes[i];i++)
node._counted=undefined;return nodes;},index:function(parentNode,reverse,ofType){parentNode._counted=true;if(reverse){for(var nodes=parentNode.childNodes,i=nodes.length-1,j=1;i>=0;i--){node=nodes[i];if(node.nodeType==1&&(!ofType||node._counted))node.nodeIndex=j++;}}else{for(var i=0,j=1,nodes=parentNode.childNodes;node=nodes[i];i++)
if(node.nodeType==1&&(!ofType||node._counted))node.nodeIndex=j++;}},unique:function(nodes){if(nodes.length==0)return nodes;var results=[],n;for(var i=0,l=nodes.length;i<l;i++)
if(!(n=nodes[i])._counted){n._counted=true;results.push(Element.extend(n));}
return Selector.handlers.unmark(results);},descendant:function(nodes){var h=Selector.handlers;for(var i=0,results=[],node;node=nodes[i];i++)
h.concat(results,node.getElementsByTagName('*'));return results;},child:function(nodes){var h=Selector.handlers;for(var i=0,results=[],node;node=nodes[i];i++){for(var j=0,children=[],child;child=node.childNodes[j];j++)
if(child.nodeType==1&&child.tagName!='!')results.push(child);}
return results;},adjacent:function(nodes){for(var i=0,results=[],node;node=nodes[i];i++){var next=this.nextElementSibling(node);if(next)results.push(next);}
return results;},laterSibling:function(nodes){var h=Selector.handlers;for(var i=0,results=[],node;node=nodes[i];i++)
h.concat(results,Element.nextSiblings(node));return results;},nextElementSibling:function(node){while(node=node.nextSibling)
if(node.nodeType==1)return node;return null;},previousElementSibling:function(node){while(node=node.previousSibling)
if(node.nodeType==1)return node;return null;},tagName:function(nodes,root,tagName,combinator){tagName=tagName.toUpperCase();var results=[],h=Selector.handlers;if(nodes){if(combinator){if(combinator=="descendant"){for(var i=0,node;node=nodes[i];i++)
h.concat(results,node.getElementsByTagName(tagName));return results;}else nodes=this[combinator](nodes);if(tagName=="*")return nodes;}
for(var i=0,node;node=nodes[i];i++)
if(node.tagName.toUpperCase()==tagName)results.push(node);return results;}else return root.getElementsByTagName(tagName);},id:function(nodes,root,id,combinator){var targetNode=$(id),h=Selector.handlers;if(!nodes&&root==document)return targetNode?[targetNode]:[];if(nodes){if(combinator){if(combinator=='child'){for(var i=0,node;node=nodes[i];i++)
if(targetNode.parentNode==node)return[targetNode];}else if(combinator=='descendant'){for(var i=0,node;node=nodes[i];i++)
if(Element.descendantOf(targetNode,node))return[targetNode];}else if(combinator=='adjacent'){for(var i=0,node;node=nodes[i];i++)
if(Selector.handlers.previousElementSibling(targetNode)==node)
return[targetNode];}else nodes=h[combinator](nodes);}
for(var i=0,node;node=nodes[i];i++)
if(node==targetNode)return[targetNode];return[];}
return(targetNode&&Element.descendantOf(targetNode,root))?[targetNode]:[];},className:function(nodes,root,className,combinator){if(nodes&&combinator)nodes=this[combinator](nodes);return Selector.handlers.byClassName(nodes,root,className);},byClassName:function(nodes,root,className){if(!nodes)nodes=Selector.handlers.descendant([root]);var needle=' '+className+' ';for(var i=0,results=[],node,nodeClassName;node=nodes[i];i++){nodeClassName=node.className;if(nodeClassName.length==0)continue;if(nodeClassName==className||(' '+nodeClassName+' ').include(needle))
results.push(node);}
return results;},attrPresence:function(nodes,root,attr){var results=[];for(var i=0,node;node=nodes[i];i++)
if(Element.hasAttribute(node,attr))results.push(node);return results;},attr:function(nodes,root,attr,value,operator){if(!nodes)nodes=root.getElementsByTagName("*");var handler=Selector.operators[operator],results=[];for(var i=0,node;node=nodes[i];i++){var nodeValue=Element.readAttribute(node,attr);if(nodeValue===null)continue;if(handler(nodeValue,value))results.push(node);}
return results;},pseudo:function(nodes,name,value,root,combinator){if(nodes&&combinator)nodes=this[combinator](nodes);if(!nodes)nodes=root.getElementsByTagName("*");return Selector.pseudos[name](nodes,value,root);}},pseudos:{'first-child':function(nodes,value,root){for(var i=0,results=[],node;node=nodes[i];i++){if(Selector.handlers.previousElementSibling(node))continue;results.push(node);}
return results;},'last-child':function(nodes,value,root){for(var i=0,results=[],node;node=nodes[i];i++){if(Selector.handlers.nextElementSibling(node))continue;results.push(node);}
return results;},'only-child':function(nodes,value,root){var h=Selector.handlers;for(var i=0,results=[],node;node=nodes[i];i++)
if(!h.previousElementSibling(node)&&!h.nextElementSibling(node))
results.push(node);return results;},'nth-child':function(nodes,formula,root){return Selector.pseudos.nth(nodes,formula,root);},'nth-last-child':function(nodes,formula,root){return Selector.pseudos.nth(nodes,formula,root,true);},'nth-of-type':function(nodes,formula,root){return Selector.pseudos.nth(nodes,formula,root,false,true);},'nth-last-of-type':function(nodes,formula,root){return Selector.pseudos.nth(nodes,formula,root,true,true);},'first-of-type':function(nodes,formula,root){return Selector.pseudos.nth(nodes,"1",root,false,true);},'last-of-type':function(nodes,formula,root){return Selector.pseudos.nth(nodes,"1",root,true,true);},'only-of-type':function(nodes,formula,root){var p=Selector.pseudos;return p['last-of-type'](p['first-of-type'](nodes,formula,root),formula,root);},getIndices:function(a,b,total){if(a==0)return b>0?[b]:[];return $R(1,total).inject([],function(memo,i){if(0==(i-b)%a&&(i-b)/a>=0)memo.push(i);return memo;});},nth:function(nodes,formula,root,reverse,ofType){if(nodes.length==0)return[];if(formula=='even')formula='2n+0';if(formula=='odd')formula='2n+1';var h=Selector.handlers,results=[],indexed=[],m;h.mark(nodes);for(var i=0,node;node=nodes[i];i++){if(!node.parentNode._counted){h.index(node.parentNode,reverse,ofType);indexed.push(node.parentNode);}}
if(formula.match(/^\d+$/)){formula=Number(formula);for(var i=0,node;node=nodes[i];i++)
if(node.nodeIndex==formula)results.push(node);}else if(m=formula.match(/^(-?\d*)?n(([+-])(\d+))?/)){if(m[1]=="-")m[1]=-1;var a=m[1]?Number(m[1]):1;var b=m[2]?Number(m[2]):0;var indices=Selector.pseudos.getIndices(a,b,nodes.length);for(var i=0,node,l=indices.length;node=nodes[i];i++){for(var j=0;j<l;j++)
if(node.nodeIndex==indices[j])results.push(node);}}
h.unmark(nodes);h.unmark(indexed);return results;},'empty':function(nodes,value,root){for(var i=0,results=[],node;node=nodes[i];i++){if(node.tagName=='!'||(node.firstChild&&!node.innerHTML.match(/^\s*$/)))continue;results.push(node);}
return results;},'not':function(nodes,selector,root){var h=Selector.handlers,selectorType,m;var exclusions=new Selector(selector).findElements(root);h.mark(exclusions);for(var i=0,results=[],node;node=nodes[i];i++)
if(!node._counted)results.push(node);h.unmark(exclusions);return results;},'enabled':function(nodes,value,root){for(var i=0,results=[],node;node=nodes[i];i++)
if(!node.disabled)results.push(node);return results;},'disabled':function(nodes,value,root){for(var i=0,results=[],node;node=nodes[i];i++)
if(node.disabled)results.push(node);return results;},'checked':function(nodes,value,root){for(var i=0,results=[],node;node=nodes[i];i++)
if(node.checked)results.push(node);return results;}},operators:{'=':function(nv,v){return nv==v;},'!=':function(nv,v){return nv!=v;},'^=':function(nv,v){return nv.startsWith(v);},'$=':function(nv,v){return nv.endsWith(v);},'*=':function(nv,v){return nv.include(v);},'~=':function(nv,v){return(' '+nv+' ').include(' '+v+' ');},'|=':function(nv,v){return('-'+nv.toUpperCase()+'-').include('-'+v.toUpperCase()+'-');}},matchElements:function(elements,expression){var matches=new Selector(expression).findElements(),h=Selector.handlers;h.mark(matches);for(var i=0,results=[],element;element=elements[i];i++)
if(element._counted)results.push(element);h.unmark(matches);return results;},findElement:function(elements,expression,index){if(typeof expression=='number'){index=expression;expression=false;}
return Selector.matchElements(elements,expression||'*')[index||0];},findChildElements:function(element,expressions){var exprs=expressions.join(','),expressions=[];exprs.scan(/(([\w#:.~>+()\s-]+|\*|\[.*?\])+)\s*(,|$)/,function(m){expressions.push(m[1].strip());});var results=[],h=Selector.handlers;for(var i=0,l=expressions.length,selector;i<l;i++){selector=new Selector(expressions[i].strip());h.concat(results,selector.findElements(element));}
return(l>1)?h.unique(results):results;}});function $$(){return Selector.findChildElements(document,$A(arguments));}
var Form={reset:function(form){$(form).reset();return form;},serializeElements:function(elements,getHash){var data=elements.inject({},function(result,element){if(!element.disabled&&element.name){var key=element.name,value=$(element).getValue();if(value!=null){if(key in result){if(result[key].constructor!=Array)result[key]=[result[key]];result[key].push(value);}
else result[key]=value;}}
return result;});return getHash?data:Hash.toQueryString(data);}};Form.Methods={serialize:function(form,getHash){return Form.serializeElements(Form.getElements(form),getHash);},getElements:function(form){return $A($(form).getElementsByTagName('*')).inject([],function(elements,child){if(Form.Element.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){return $(form).getElements().find(function(element){return element.type!='hidden'&&!element.disabled&&['input','select','textarea'].include(element.tagName.toLowerCase());});},focusFirstElement:function(form){form=$(form);form.findFirstElement().activate();return form;},request:function(form,options){form=$(form),options=Object.clone(options||{});var params=options.parameters;options.parameters=form.serialize(true);if(params){if(typeof params=='string')params=params.toQueryParams();Object.extend(options.parameters,params);}
if(form.hasAttribute('method')&&!options.method)
options.method=form.method;return new Ajax.Request(form.readAttribute('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 Hash.toQueryString(pair);}}
return'';},getValue:function(element){element=$(element);var method=element.tagName.toLowerCase();return Form.Element.Serializers[method](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'].include(element.type)))
element.select();}catch(e){}
return element;},disable:function(element){element=$(element);element.blur();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={input:function(element){switch(element.type.toLowerCase()){case'checkbox':case'radio':return Form.Element.Serializers.inputSelector(element);default:return Form.Element.Serializers.textarea(element);}},inputSelector:function(element){return element.checked?element.value:null;},textarea:function(element){return element.value;},select:function(element){return this[element.type=='select-one'?'selectOne':'selectMany'](element);},selectOne:function(element){var index=element.selectedIndex;return index>=0?this.optionValue(element.options[index]):null;},selectMany:function(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(this.optionValue(opt));}
return values;},optionValue:function(opt){return Element.extend(opt).hasAttribute('value')?opt.value:opt.text;}}
Abstract.TimedObserver=function(){}
Abstract.TimedObserver.prototype={initialize:function(element,frequency,callback){this.frequency=frequency;this.element=$(element);this.callback=callback;this.lastValue=this.getValue();this.registerCallback();},registerCallback:function(){setInterval(this.onTimerEvent.bind(this),this.frequency*1000);},onTimerEvent:function(){var value=this.getValue();var changed=('string'==typeof this.lastValue&&'string'==typeof value?this.lastValue!=value:String(this.lastValue)!=String(value));if(changed){this.callback(this.element,value);this.lastValue=value;}}}
Form.Element.Observer=Class.create();Form.Element.Observer.prototype=Object.extend(new Abstract.TimedObserver(),{getValue:function(){return Form.Element.getValue(this.element);}});Form.Observer=Class.create();Form.Observer.prototype=Object.extend(new Abstract.TimedObserver(),{getValue:function(){return Form.serialize(this.element);}});Abstract.EventObserver=function(){}
Abstract.EventObserver.prototype={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.bind(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();Form.Element.EventObserver.prototype=Object.extend(new Abstract.EventObserver(),{getValue:function(){return Form.Element.getValue(this.element);}});Form.EventObserver=Class.create();Form.EventObserver.prototype=Object.extend(new Abstract.EventObserver(),{getValue:function(){return Form.serialize(this.element);}});if(!window.Event){var Event=new Object();}
Object.extend(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,element:function(event){return $(event.target||event.srcElement);},isLeftClick:function(event){return(((event.which)&&(event.which==1))||((event.button)&&(event.button==1)));},pointerX:function(event){return event.pageX||(event.clientX+
(document.documentElement.scrollLeft||document.body.scrollLeft));},pointerY:function(event){return event.pageY||(event.clientY+
(document.documentElement.scrollTop||document.body.scrollTop));},stop:function(event){if(event.preventDefault){event.preventDefault();event.stopPropagation();}else{event.returnValue=false;event.cancelBubble=true;}},findElement:function(event,tagName){var element=Event.element(event);while(element.parentNode&&(!element.tagName||(element.tagName.toUpperCase()!=tagName.toUpperCase())))
element=element.parentNode;return element;},observers:false,_observeAndCache:function(element,name,observer,useCapture){if(!this.observers)this.observers=[];if(element.addEventListener){this.observers.push([element,name,observer,useCapture]);element.addEventListener(name,observer,useCapture);}else if(element.attachEvent){this.observers.push([element,name,observer,useCapture]);element.attachEvent('on'+name,observer);}},unloadCache:function(){if(!Event.observers)return;for(var i=0,length=Event.observers.length;i<length;i++){Event.stopObserving.apply(this,Event.observers[i]);Event.observers[i][0]=null;}
Event.observers=false;},observe:function(element,name,observer,useCapture){element=$(element);useCapture=useCapture||false;if(name=='keypress'&&(Prototype.Browser.WebKit||element.attachEvent))
name='keydown';Event._observeAndCache(element,name,observer,useCapture);},stopObserving:function(element,name,observer,useCapture){element=$(element);useCapture=useCapture||false;if(name=='keypress'&&(Prototype.Browser.WebKit||element.attachEvent))
name='keydown';if(element.removeEventListener){element.removeEventListener(name,observer,useCapture);}else if(element.detachEvent){try{element.detachEvent('on'+name,observer);}catch(e){}}}});if(Prototype.Browser.IE)
Event.observe(window,'unload',Event.unloadCache,false);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;},realOffset:function(element){var valueT=0,valueL=0;do{valueT+=element.scrollTop||0;valueL+=element.scrollLeft||0;element=element.parentNode;}while(element);return[valueL,valueT];},cumulativeOffset:function(element){var valueT=0,valueL=0;do{valueT+=element.offsetTop||0;valueL+=element.offsetLeft||0;element=element.offsetParent;}while(element);return[valueL,valueT];},positionedOffset:function(element){var valueT=0,valueL=0;do{valueT+=element.offsetTop||0;valueL+=element.offsetLeft||0;element=element.offsetParent;if(element){if(element.tagName=='BODY')break;var p=Element.getStyle(element,'position');if(p=='relative'||p=='absolute')break;}}while(element);return[valueL,valueT];},offsetParent:function(element){if(element.offsetParent)return element.offsetParent;if(element==document.body)return element;while((element=element.parentNode)&&element!=document.body)
if(Element.getStyle(element,'position')!='static')
return element;return document.body;},within:function(element,x,y){if(this.includeScrollOffsets)
return this.withinIncludingScrolloffsets(element,x,y);this.xcomp=x;this.ycomp=y;this.offset=this.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=this.realOffset(element);this.xcomp=x+offsetcache[0]-this.deltaX;this.ycomp=y+offsetcache[1]-this.deltaY;this.offset=this.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;},page:function(forElement){var valueT=0,valueL=0;var element=forElement;do{valueT+=element.offsetTop||0;valueL+=element.offsetLeft||0;if(element.offsetParent==document.body)
if(Element.getStyle(element,'position')=='absolute')break;}while(element=element.offsetParent);element=forElement;do{if(!window.opera||element.tagName=='BODY'){valueT-=element.scrollTop||0;valueL-=element.scrollLeft||0;}}while(element=element.parentNode);return[valueL,valueT];},clone:function(source,target){var options=Object.extend({setLeft:true,setTop:true,setWidth:true,setHeight:true,offsetTop:0,offsetLeft:0},arguments[2]||{})
source=$(source);var p=Position.page(source);target=$(target);var delta=[0,0];var parent=null;if(Element.getStyle(target,'position')=='absolute'){parent=Position.offsetParent(target);delta=Position.page(parent);}
if(parent==document.body){delta[0]-=document.body.offsetLeft;delta[1]-=document.body.offsetTop;}
if(options.setLeft)target.style.left=(p[0]-delta[0]+options.offsetLeft)+'px';if(options.setTop)target.style.top=(p[1]-delta[1]+options.offsetTop)+'px';if(options.setWidth)target.style.width=source.offsetWidth+'px';if(options.setHeight)target.style.height=source.offsetHeight+'px';},absolutize:function(element){element=$(element);if(element.style.position=='absolute')return;Position.prepare();var offsets=Position.positionedOffset(element);var top=offsets[1];var left=offsets[0];var width=element.clientWidth;var height=element.clientHeight;element._originalLeft=left-parseFloat(element.style.left||0);element._originalTop=top-parseFloat(element.style.top||0);element._originalWidth=element.style.width;element._originalHeight=element.style.height;element.style.position='absolute';element.style.top=top+'px';element.style.left=left+'px';element.style.width=width+'px';element.style.height=height+'px';},relativize:function(element){element=$(element);if(element.style.position=='relative')return;Position.prepare();element.style.position='relative';var top=parseFloat(element.style.top||0)-(element._originalTop||0);var left=parseFloat(element.style.left||0)-(element._originalLeft||0);element.style.top=top+'px';element.style.left=left+'px';element.style.height=element._originalHeight;element.style.width=element._originalWidth;}}
if(Prototype.Browser.WebKit){Position.cumulativeOffset=function(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[valueL,valueT];}}
Element.addMethods();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){}};Array.prototype.call=function(){var args=arguments;this.each(function(f){f.apply(this,args)});}
var Effect={_elementDoesNotExistError:{name:'ElementDoesNotExistError',message:'The specified DOM element does not exist, but is required for this effect to operate'},tagifyText:function(element){if(typeof Builder=='undefined')
throw("Effect.tagifyText requires including script.aculo.us' builder.js library");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(Builder.node('span',{style:tagifyStyle},character==' '?String.fromCharCode(160):character),child);});Element.remove(child);}});},multiple:function(element,effect){var elements;if(((typeof element=='object')||(typeof element=='function'))&&(element.length))
elements=element;else
elements=$(element).childNodes;var options=Object.extend({speed:0.1,delay:0.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){element=$(element);effect=(effect||'appear').toLowerCase();var options=Object.extend({queue:{position:'end',scope:(element.id||'global'),limit:1}},arguments[2]||{});Effect[element.visible()?Effect.PAIRS[effect][1]:Effect.PAIRS[effect][0]](element,options);}};var Effect2=Effect;Effect.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){pulses=pulses||5;return(Math.round((pos%(1/pulses))*pulses)==0?((pos*pulses*2)-Math.floor(pos*pulses*2)):1-((pos*pulses*2)-Math.floor(pos*pulses*2)));},none:function(pos){return 0;},full:function(pos){return 1;}};Effect.ScopedQueue=Class.create();Object.extend(Object.extend(Effect.ScopedQueue.prototype,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=(typeof effect.options.queue=='string')?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(typeof queueName!='string')return queueName;if(!this.instances[queueName])
this.instances[queueName]=new Effect.ScopedQueue();return this.instances[queueName];}}
Effect.Queue=Effect.Queues.get('global');Effect.DefaultOptions={transition:Effect.Transitions.sinoidal,duration:1.0,fps:100,sync:false,from:0.0,to:1.0,delay:0.0,queue:'parallel'}
Effect.Base=function(){};Effect.Base.prototype={position:null,start:function(options){function codeForEvent(options,eventName){return((options[eventName+'Internal']?'this.options.'+eventName+'Internal(this);':'')+
(options[eventName]?'this.options.'+eventName+'(this);':''));}
if(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*1000;this.finishOn=this.startOn+(this.options.duration*1000);this.fromToDelta=this.options.to-this.options.from;this.totalTime=this.finishOn-this.startOn;this.totalFrames=this.options.fps*this.options.duration;eval('this.render = function(pos){ '+'if(this.state=="idle"){this.state="running";'+
codeForEvent(options,'beforeSetup')+
(this.setup?'this.setup();':'')+
codeForEvent(options,'afterSetup')+'};if(this.state=="running"){'+'pos=this.options.transition(pos)*'+this.fromToDelta+'+'+this.options.from+';'+'this.position=pos;'+
codeForEvent(options,'beforeUpdate')+
(this.update?'this.update(pos);':'')+
codeForEvent(options,'afterUpdate')+'}}');this.event('beforeStart');if(!this.options.sync)
Effect.Queues.get(typeof this.options.queue=='string'?'global':this.options.queue.scope).add(this);},loop:function(timePos){if(timePos>=this.startOn){if(timePos>=this.finishOn){this.render(1.0);this.cancel();this.event('beforeFinish');if(this.finish)this.finish();this.event('afterFinish');return;}
var pos=(timePos-this.startOn)/this.totalTime,frame=Math.round(pos*this.totalFrames);if(frame>this.currentFrame){this.render(pos);this.currentFrame=frame;}}},cancel:function(){if(!this.options.sync)
Effect.Queues.get(typeof this.options.queue=='string'?'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(typeof this[property]!='function')data[property]=this[property];return'#<Effect:'+data.inspect()+',options:'+$H(this.options).inspect()+'>';}}
Effect.Parallel=Class.create();Object.extend(Object.extend(Effect.Parallel.prototype,Effect.Base.prototype),{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.0);effect.cancel();effect.event('beforeFinish');if(effect.finish)effect.finish(position);effect.event('afterFinish');});}});Effect.Event=Class.create();Object.extend(Object.extend(Effect.Event.prototype,Effect.Base.prototype),{initialize:function(){var options=Object.extend({duration:0},arguments[0]||{});this.start(options);},update:Prototype.emptyFunction});Effect.Opacity=Class.create();Object.extend(Object.extend(Effect.Opacity.prototype,Effect.Base.prototype),{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.0,to:1.0},arguments[1]||{});this.start(options);},update:function(position){this.element.setOpacity(position);}});Effect.Move=Class.create();Object.extend(Object.extend(Effect.Move.prototype,Effect.Base.prototype),{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:Math.round(this.options.x*position+this.originalLeft)+'px',top:Math.round(this.options.y*position+this.originalTop)+'px'});}});Effect.MoveBy=function(element,toTop,toLeft){return new Effect.Move(element,Object.extend({x:toLeft,y:toTop},arguments[3]||{}));};Effect.Scale=Class.create();Object.extend(Object.extend(Effect.Scale.prototype,Effect.Base.prototype),{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.0,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.0)+(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=Math.round(width)+'px';if(this.options.scaleY)d.height=Math.round(height)+'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();Object.extend(Object.extend(Effect.Highlight.prototype,Effect.Base.prototype),{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+(Math.round(this._base[i]+(this._delta[i]*position)).toColorPart());}.bind(this))});},finish:function(){this.element.setStyle(Object.extend(this.oldStyle,{backgroundColor:this.options.restorecolor}));}});Effect.ScrollTo=Class.create();Object.extend(Object.extend(Effect.ScrollTo.prototype,Effect.Base.prototype),{initialize:function(element){this.element=$(element);this.start(arguments[1]||{});},setup:function(){Position.prepare();var offsets=Position.cumulativeOffset(this.element);if(this.options.offset)offsets[1]+=this.options.offset;var max=window.innerHeight?window.height-window.innerHeight:document.body.scrollHeight-
(document.documentElement.clientHeight?document.documentElement.clientHeight:document.body.clientHeight);this.scrollStart=Position.deltaY;this.delta=(offsets[1]>max?max:offsets[1])-this.scrollStart;},update:function(position){Position.prepare();window.scrollTo(Position.deltaX,this.scrollStart+(position*this.delta));}});Effect.Fade=function(element){element=$(element);var oldOpacity=element.getInlineOpacity();var options=Object.extend({from:element.getOpacity()||1.0,to:0.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.0:element.getOpacity()||0.0),to:1.0,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.0})],Object.extend({duration:1.0,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.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 oldStyle={top:element.getStyle('top'),left:element.getStyle('left')};return new Effect.Move(element,{x:20,y:0,duration:0.05,afterFinishInternal:function(effect){new Effect.Move(effect.element,{x:-40,y:0,duration:0.1,afterFinishInternal:function(effect){new Effect.Move(effect.element,{x:40,y:0,duration:0.1,afterFinishInternal:function(effect){new Effect.Move(effect.element,{x:-40,y:0,duration:0.1,afterFinishInternal:function(effect){new Effect.Move(effect.element,{x:40,y:0,duration:0.1,afterFinishInternal:function(effect){new Effect.Move(effect.element,{x:-20,y:0,duration:0.05,afterFinishInternal:function(effect){effect.element.undoPositioned().setStyle(oldStyle);}})}})}})}})}})}});}
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');return new Effect.Scale(element,window.opera?0:1,Object.extend({scaleContent:false,scaleX:false,scaleMode:'box',scaleFrom:100,restoreAfterFinish:true,beforeStartInternal: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().setStyle({bottom:oldInnerBottom});effect.element.down().undoPositioned();}},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.0,from:0.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.0,from:1.0,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]||{};var oldOpacity=element.getInlineOpacity();var transition=options.transition||Effect.Transitions.sinoidal;var reverser=function(pos){return transition(1-Effect.Transitions.pulse(pos,options.pulses))};reverser.bind(transition);return new Effect.Opacity(element,Object.extend(Object.extend({duration:2.0,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();Object.extend(Object.extend(Effect.Morph.prototype,Effect.Base.prototype),{initialize:function(element){this.element=$(element);if(!this.element)throw(Effect._elementDoesNotExistError);var options=Object.extend({style:{}},arguments[1]||{});if(typeof options.style=='string'){if(options.style.indexOf(':')==-1){var cssText='',selector='.'+options.style;$A(document.styleSheets).reverse().each(function(styleSheet){if(styleSheet.cssRules)cssRules=styleSheet.cssRules;else if(styleSheet.rules)cssRules=styleSheet.rules;$A(cssRules).reverse().each(function(rule){if(selector==rule.selectorText){cssText=rule.style.cssText;throw $break;}});if(cssText)throw $break;});this.style=cssText.parseStyle();options.afterFinishInternal=function(effect){effect.element.addClassName(effect.options.style);effect.transforms.each(function(transform){if(transform.style!='opacity')
effect.element.style[transform.style]='';});}}else this.style=options.style.parseStyle();}else this.style=$H(options.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+Math.round(((transform.targetValue-transform.originalValue)*position)*1000)/1000+transform.unit;this.element.setStyle(style,true);}});Effect.Transform=Class.create();Object.extend(Effect.Transform.prototype,{initialize:function(tracks){this.tracks=[];this.options=arguments[1]||{};this.addTracks(tracks);},addTracks:function(tracks){tracks.each(function(track){var data=$H(track).values().first();this.tracks.push($H({ids:$H(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 elements=[$(track.ids)||$$(track.ids)].flatten();return elements.map(function(e){return new track.effect(e,Object.extend({sync:true},track.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.prototype.parseStyle=function(){var element=document.createElement('div');element.innerHTML='<div style="'+this+'"></div>';var style=element.childNodes[0].style,styleRules=$H();Element.CSS_PROPERTIES.each(function(property){if(style[property])styleRules[property]=style[property];});if(Prototype.Browser.IE&&this.indexOf('opacity')>-1){styleRules.opacity=this.match(/opacity:\s*((?:0|1)?(?:\.\d*)?)/)[1];}
return styleRules;};Element.morph=function(element,style){new Effect.Morph(element,Object.extend({style:style},arguments[2]||{}));return element;};['getInlineOpacity','forceRerendering','setContentZoom','collectTextNodes','collectTextNodesIgnoreClass','morph'].each(function(f){Element.Methods[f]=Element[f];});Element.Methods.visualEffect=function(element,effect,options){s=effect.dasherize().camelize();effect_class=s.charAt(0).toUpperCase()+s.substring(1);new Effect[effect_class](element,options);return $(element);};Element.addMethods();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,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'},options||{});this.duration=((11-this.options.resizeSpeed)*0.15);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=$H({width:'0px'});}else{var options=$H({height:'0px'});}
options.merge({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=$H({scaleX:true,scaleY:false});}else{this.scaling=$H({scaleX:false,scaleY:true});}
if(this.currentAccordion==this.showAccordion){this.deactivate();}else{this._handleAccordion();}},deactivate:function(){var options=$H({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(){flip_image(this.showAccordion,'up');this.showAccordion.setStyle({height:'auto',display:'none'});this.showAccordion=null;this.animating=false;}.bind(this)});options.merge(this.scaling);this.showAccordion.previous(0).removeClassName(this.options.classNames.toggleActive);new Effect.Scale(this.showAccordion,0,options);},_handleAccordion:function(){var options=$H({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}});options.merge(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=$H({sync:true,scaleContent:false,transition:Effect.Transitions.sinoidal});options.merge(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){flip_image(this.showAccordion,'up');this.showAccordion.setStyle({display:'none'});}
$(this.currentAccordion).setStyle({height:'auto'});flip_image(this.currentAccordion,'down');this.showAccordion=this.currentAccordion;this.animating=false;}.bind(this)});}}
function flip_image(accordion,direction)
{var accordion_id=$(accordion).id;var accordion_name_back=accordion_id.substring(accordion_id.lastIndexOf("_")+1);var accordion_name_front=accordion_id.substring(0,accordion_id.indexOf("_"));if(accordion_name_back=="el"||accordion_name_front=="event"){var current_header=document.getElementById("accordion_event_location");if(direction=='up'){current_header.style.background="url(../images/buttons/event-location-up.png) repeat-x";}else{current_header.style.background="url(../images/buttons/event-locations-down.png) repeat-x";}}
else if(accordion_name_back=="f"||accordion_name_front=="fashion"){var current_header=document.getElementById("accordion_fashion");if(direction=='up'){current_header.style.background="url(../images/buttons/fashion-up.png) repeat-x";}else{current_header.style.background="url(../images/buttons/fashion-down.png) repeat-x";}}
else if(accordion_name_back=="pv"||accordion_name_front=="photography"){var current_header=document.getElementById("accordion_photo_video");if(direction=='up'){current_header.style.background="url(../images/buttons/photo-video-up.png) repeat-x";}else{current_header.style.background="url(../images/buttons/photo-video-down.png) repeat-x";}}
else if(accordion_name_back=="fo"||accordion_name_front=="food"){var current_header=document.getElementById("accordion_food");if(direction=='up'){current_header.style.background="url(../images/buttons/food-up.png) repeat-x";}else{current_header.style.background="url(../images/buttons/food-down.png) repeat-x";}}
else if(accordion_name_back=="d"||accordion_name_front=="decor"){var current_header=document.getElementById("accordion_decor");if(direction=='up'){current_header.style.background="url(../images/buttons/decor-up.png) repeat-x";}else{current_header.style.background="url(../images/buttons/decor-down.png) repeat-x";}}
else if(accordion_name_back=="pc"||accordion_name_front=="planning"){var current_header=document.getElementById("accordion_plan_coord");if(direction=='up'){current_header.style.background="url(../images/buttons/plan-coord-up.png) repeat-x";}else{current_header.style.background="url(../images/buttons/plan-coord-down.png) repeat-x";}}
else if(accordion_name_back=="me"||accordion_name_front=="music"){var current_header=document.getElementById("accordion_music");if(direction=='up'){current_header.style.background="url(../images/buttons/music-ent-up.png) repeat-x";}else{current_header.style.background="url(../images/buttons/music-ent-down.png) repeat-x";}}
else if(accordion_name_front=="wedding"){var current_header=document.getElementById("weddings_edit_background_arrow_"+accordion_name_back);if(direction=='up'){current_header.style.background="url(../images/buttons/right-arrow.png) no-repeat";}else{current_header.style.background="url(../images/buttons/down-arrow.png) no-repeat";}}}
if(typeof Effect=='undefined')
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((typeof containment=='object')&&(containment.constructor==Array)){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 affected=[];if(this.last_active)this.deactivate(this.last_active);this.drops.each(function(drop){if(Droppables.isAffected(point,element,drop))
affected.push(drop);});if(affected.length>0){drop=Droppables.findDeepestChild(affected);Position.within(drop.element,point[0],point[1]);if(drop.onHover)
drop.onHover(element,drop.element,Position.overlap(drop.overlap,drop.element));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();Draggable._dragging={};Draggable.prototype={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=typeof element._opacity=='number'?element._opacity:1.0;new Effect.Opacity(element,{duration:0.2,from:0.7,to:toOpacity,queue:{scope:'_draggable',position:'end'},afterFinish:function(){Draggable._dragging[element]=false}});},zindex:1000,revert:false,quiet:false,scroll:false,scrollSensitivity:20,scrollSpeed:15,snap:false,delay:0};if(!arguments[1]||typeof arguments[1].endeffect=='undefined')
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&&(typeof options.handle=='string'))
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.delta=this.currentDelta();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(typeof Draggable._dragging[this.element]!='undefined'&&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=Position.cumulativeOffset(this.element);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.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);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);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){Position.relativize(this.element);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&&typeof revert=='function')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=Position.cumulativeOffset(this.element);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(typeof this.options.snap=='function'){p=this.options.snap(p[0],p[1],this);}else{if(this.options.snap instanceof Array){p=p.map(function(v,i){return Math.round(v/this.options.snap[i])*this.options.snap[i]}.bind(this))}else{p=p.map(function(v){return Math.round(v/this.options.snap)*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/1000;this.options.scroll.scrollTo(left+d*this.scrollSpeed[0],top+d*this.scrollSpeed[1]);}}}else{this.options.scroll.scrollLeft+=this.scrollSpeed[0]*delta/1000;this.options.scroll.scrollTop+=this.scrollSpeed[1]*delta/1000;}
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/1000;Draggables._lastScrollPointer[1]+=this.scrollSpeed[1]*delta/1000;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};}}
var SortableObserver=Class.create();SortableObserver.prototype={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){var s=Sortable.options(element);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).getElementsByClassName(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.id]=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>.33&&overlap<.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.0-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=Position.cumulativeOffset(dropon);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')];}
if(typeof Effect=='undefined')
throw("controls.js requires including script.aculo.us' effects.js library");var Autocompleter={}
Autocompleter.Base=function(){};Autocompleter.Base.prototype={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;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);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,'keypress',this.onKeyPress.bindAsEventListener(this));Event.observe(window,'beforeunload',function(){element.setAttribute('autocomplete','on');});},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();if(Prototype.Browser.WebKit)Event.stop(event);return;case Event.KEY_DOWN:this.markNext();this.render();if(Prototype.Browser.WebKit)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*1000);},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=document.getElementsByClassName(this.options.select,selectedElement)||[];if(nodes.length>0)value=Element.collectTextNodes(nodes[0],this.options.select);}else
value=Element.collectTextNodesIgnoreClass(selectedElement,'informal');var lastTokenPos=this.findLastToken();if(lastTokenPos!=-1){var newValue=this.element.value.substr(0,lastTokenPos+1);var whitespace=this.element.value.substr(lastTokenPos+1).match(/^\s+/);if(whitespace)
newValue+=whitespace[0];this.element.value=newValue+value;}else{this.element.value=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=-1;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;if(this.getToken().length>=this.options.minChars){this.getUpdatedChoices();}else{this.active=false;this.hide();}},getToken:function(){var tokenPos=this.findLastToken();if(tokenPos!=-1)
var ret=this.element.value.substr(tokenPos+1).replace(/^\s+/,'').replace(/\s+$/,'');else
var ret=this.element.value;return/\n/.test(ret)?'':ret;},findLastToken:function(){var lastTokenPos=-1;for(var i=0;i<this.options.tokens.length;i++){var thisTokenPos=this.element.value.lastIndexOf(this.options.tokens[i]);if(thisTokenPos>lastTokenPos)
lastTokenPos=thisTokenPos;}
return lastTokenPos;}}
Ajax.Autocompleter=Class.create();Object.extend(Object.extend(Ajax.Autocompleter.prototype,Autocompleter.Base.prototype),{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.Local.prototype=Object.extend(new 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();Ajax.InPlaceEditor.defaultHighlightColor="#FFFF99";Ajax.InPlaceEditor.prototype={initialize:function(element,url,options){this.url=url;this.element=$(element);this.options=Object.extend({paramName:"value",okButton:true,okLink:false,okText:"ok",cancelButton:false,cancelLink:true,cancelText:"cancel",textBeforeControls:'',textBetweenControls:'',textAfterControls:'',savingText:"Saving...",clickToEditText:"Click to edit",okText:"ok",rows:1,onComplete:function(transport,element){new Effect.Highlight(element,{startcolor:this.options.highlightcolor});},onFailure:function(transport){alert("Error communicating with the server: "+transport.responseText.stripTags());},callback:function(form){return Form.serialize(form);},handleLineBreaks:true,loadingText:'Loading...',savingClassName:'inplaceeditor-saving',loadingClassName:'inplaceeditor-loading',formClassName:'inplaceeditor-form',highlightcolor:Ajax.InPlaceEditor.defaultHighlightColor,highlightendcolor:"#FFFFFF",externalControl:null,submitOnBlur:false,ajaxOptions:{},evalScripts:false},options||{});if(!this.options.formId&&this.element.id){this.options.formId=this.element.id+"-inplaceeditor";if($(this.options.formId)){this.options.formId=null;}}
if(this.options.externalControl){this.options.externalControl=$(this.options.externalControl);}
this.originalBackground=Element.getStyle(this.element,'background-color');if(!this.originalBackground){this.originalBackground="transparent";}
this.element.title=this.options.clickToEditText;this.onclickListener=this.enterEditMode.bindAsEventListener(this);this.mouseoverListener=this.enterHover.bindAsEventListener(this);this.mouseoutListener=this.leaveHover.bindAsEventListener(this);Event.observe(this.element,'click',this.onclickListener);Event.observe(this.element,'mouseover',this.mouseoverListener);Event.observe(this.element,'mouseout',this.mouseoutListener);if(this.options.externalControl){Event.observe(this.options.externalControl,'click',this.onclickListener);Event.observe(this.options.externalControl,'mouseover',this.mouseoverListener);Event.observe(this.options.externalControl,'mouseout',this.mouseoutListener);}},enterEditMode:function(evt){if(this.saving)return;if(this.editing)return;this.editing=true;this.onEnterEditMode();if(this.options.externalControl){Element.hide(this.options.externalControl);}
Element.hide(this.element);this.createForm();this.element.parentNode.insertBefore(this.form,this.element);if(!this.options.loadTextURL)Field.scrollFreeActivate(this.editField);if(evt){Event.stop(evt);}
return false;},createForm:function(){this.form=document.createElement("form");this.form.id=this.options.formId;Element.addClassName(this.form,this.options.formClassName)
this.form.onsubmit=this.onSubmit.bind(this);this.createEditField();if(this.options.textarea){var br=document.createElement("br");this.form.appendChild(br);}
if(this.options.textBeforeControls)
this.form.appendChild(document.createTextNode(this.options.textBeforeControls));if(this.options.okButton){var okButton=document.createElement("input");okButton.type="submit";okButton.value=this.options.okText;okButton.className='editor_ok_button';this.form.appendChild(okButton);}
if(this.options.okLink){var okLink=document.createElement("a");okLink.href="#";okLink.appendChild(document.createTextNode(this.options.okText));okLink.onclick=this.onSubmit.bind(this);okLink.className='editor_ok_link';this.form.appendChild(okLink);}
if(this.options.textBetweenControls&&(this.options.okLink||this.options.okButton)&&(this.options.cancelLink||this.options.cancelButton))
this.form.appendChild(document.createTextNode(this.options.textBetweenControls));if(this.options.cancelButton){var cancelButton=document.createElement("input");cancelButton.type="submit";cancelButton.value=this.options.cancelText;cancelButton.onclick=this.onclickCancel.bind(this);cancelButton.className='editor_cancel_button';this.form.appendChild(cancelButton);}
if(this.options.cancelLink){var cancelLink=document.createElement("a");cancelLink.href="#";cancelLink.appendChild(document.createTextNode(this.options.cancelText));cancelLink.onclick=this.onclickCancel.bind(this);cancelLink.className='editor_cancel editor_cancel_link';this.form.appendChild(cancelLink);}
if(this.options.textAfterControls)
this.form.appendChild(document.createTextNode(this.options.textAfterControls));},hasHTMLLineBreaks:function(string){if(!this.options.handleLineBreaks)return false;return string.match(/<br/i)||string.match(/<p>/i);},convertHTMLLineBreaks:function(string){return string.replace(/<br>/gi,"\n").replace(/<br\/>/gi,"\n").replace(/<\/p>/gi,"\n").replace(/<p>/gi,"");},createEditField:function(){var text;if(this.options.loadTextURL){text=this.options.loadingText;}else{text=this.getText();}
var obj=this;if(this.options.rows==1&&!this.hasHTMLLineBreaks(text)){this.options.textarea=false;var textField=document.createElement("input");textField.obj=this;textField.type="text";textField.name=this.options.paramName;textField.value=text;textField.style.backgroundColor=this.options.highlightcolor;textField.className='editor_field';var size=this.options.size||this.options.cols||0;if(size!=0)textField.size=size;if(this.options.submitOnBlur)
textField.onblur=this.onSubmit.bind(this);this.editField=textField;}else{this.options.textarea=true;var textArea=document.createElement("textarea");textArea.obj=this;textArea.name=this.options.paramName;textArea.value=this.convertHTMLLineBreaks(text);textArea.rows=this.options.rows;textArea.cols=this.options.cols||40;textArea.className='editor_field';if(this.options.submitOnBlur)
textArea.onblur=this.onSubmit.bind(this);this.editField=textArea;}
if(this.options.loadTextURL){this.loadExternalText();}
this.form.appendChild(this.editField);},getText:function(){return this.element.innerHTML;},loadExternalText:function(){Element.addClassName(this.form,this.options.loadingClassName);this.editField.disabled=true;new Ajax.Request(this.options.loadTextURL,Object.extend({asynchronous:true,onComplete:this.onLoadedExternalText.bind(this)},this.options.ajaxOptions));},onLoadedExternalText:function(transport){Element.removeClassName(this.form,this.options.loadingClassName);this.editField.disabled=false;this.editField.value=transport.responseText.stripTags();Field.scrollFreeActivate(this.editField);},onclickCancel:function(){this.onComplete();this.leaveEditMode();return false;},onFailure:function(transport){this.options.onFailure(transport);if(this.oldInnerHTML){this.element.innerHTML=this.oldInnerHTML;this.oldInnerHTML=null;}
return false;},onSubmit:function(){var form=this.form;var value=this.editField.value;this.onLoading();if(this.options.evalScripts){new Ajax.Request(this.url,Object.extend({parameters:this.options.callback(form,value),onComplete:this.onComplete.bind(this),onFailure:this.onFailure.bind(this),asynchronous:true,evalScripts:true},this.options.ajaxOptions));}else{new Ajax.Updater({success:this.element,failure:null},this.url,Object.extend({parameters:this.options.callback(form,value),onComplete:this.onComplete.bind(this),onFailure:this.onFailure.bind(this)},this.options.ajaxOptions));}
if(arguments.length>1){Event.stop(arguments[0]);}
return false;},onLoading:function(){this.saving=true;this.removeForm();this.leaveHover();this.showSaving();},showSaving:function(){this.oldInnerHTML=this.element.innerHTML;this.element.innerHTML=this.options.savingText;Element.addClassName(this.element,this.options.savingClassName);this.element.style.backgroundColor=this.originalBackground;Element.show(this.element);},removeForm:function(){if(this.form){if(this.form.parentNode)Element.remove(this.form);this.form=null;}},enterHover:function(){if(this.saving)return;this.element.style.backgroundColor=this.options.highlightcolor;if(this.effect){this.effect.cancel();}
Element.addClassName(this.element,this.options.hoverClassName)},leaveHover:function(){if(this.options.backgroundColor){this.element.style.backgroundColor=this.oldBackground;}
Element.removeClassName(this.element,this.options.hoverClassName)
if(this.saving)return;this.effect=new Effect.Highlight(this.element,{startcolor:this.options.highlightcolor,endcolor:this.options.highlightendcolor,restorecolor:this.originalBackground});},leaveEditMode:function(){Element.removeClassName(this.element,this.options.savingClassName);this.removeForm();this.leaveHover();this.element.style.backgroundColor=this.originalBackground;Element.show(this.element);if(this.options.externalControl){Element.show(this.options.externalControl);}
this.editing=false;this.saving=false;this.oldInnerHTML=null;this.onLeaveEditMode();},onComplete:function(transport){this.leaveEditMode();this.options.onComplete.bind(this)(transport,this.element);},onEnterEditMode:function(){},onLeaveEditMode:function(){},dispose:function(){if(this.oldInnerHTML){this.element.innerHTML=this.oldInnerHTML;}
this.leaveEditMode();Event.stopObserving(this.element,'click',this.onclickListener);Event.stopObserving(this.element,'mouseover',this.mouseoverListener);Event.stopObserving(this.element,'mouseout',this.mouseoutListener);if(this.options.externalControl){Event.stopObserving(this.options.externalControl,'click',this.onclickListener);Event.stopObserving(this.options.externalControl,'mouseover',this.mouseoverListener);Event.stopObserving(this.options.externalControl,'mouseout',this.mouseoutListener);}}};Ajax.InPlaceCollectionEditor=Class.create();Object.extend(Ajax.InPlaceCollectionEditor.prototype,Ajax.InPlaceEditor.prototype);Object.extend(Ajax.InPlaceCollectionEditor.prototype,{createEditField:function(){if(!this.cached_selectTag){var selectTag=document.createElement("select");var collection=this.options.collection||[];var optionTag;collection.each(function(e,i){optionTag=document.createElement("option");optionTag.value=(e instanceof Array)?e[0]:e;if((typeof this.options.value=='undefined')&&((e instanceof Array)?this.element.innerHTML==e[1]:e==optionTag.value))optionTag.selected=true;if(this.options.value==optionTag.value)optionTag.selected=true;optionTag.appendChild(document.createTextNode((e instanceof Array)?e[1]:e));selectTag.appendChild(optionTag);}.bind(this));this.cached_selectTag=selectTag;}
this.editField=this.cached_selectTag;if(this.options.loadTextURL)this.loadExternalText();this.form.appendChild(this.editField);this.options.callback=function(form,value){return"value="+encodeURIComponent(value);}}});Form.Element.DelayedObserver=Class.create();Form.Element.DelayedObserver.prototype={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*1000);this.lastValue=$F(this.element);},onTimerEvent:function(){this.timer=null;this.callback(this.element,$F(this.element));}};if(typeof(Control)=="undefined")
Control={};Control.Modal=Class.create();Object.extend(Control.Modal,{loaded:false,loading:false,loadingTimeout:false,overlay:false,container:false,current:false,ie:false,effects:{containerFade:false,containerAppear:false,overlayFade:false,overlayAppear:false},targetRegexp:/#(.+)$/,imgRegexp:/\.(jpe?g|gif|png|tiff?)$/,overlayStyles:{position:'fixed',top:0,left:0,width:'100%',height:'100%',zIndex:9998},overlayIEStyles:{position:'absolute',top:0,left:0,zIndex:9998},disableHoverClose:false,load:function(){if(!Control.Modal.loaded){Control.Modal.loaded=true;Control.Modal.ie=!(typeof document.body.style.maxHeight!='undefined');Control.Modal.overlay=$(document.createElement('div'));Control.Modal.overlay.id='modal_overlay';Object.extend(Control.Modal.overlay.style,Control.Modal['overlay'+(Control.Modal.ie?'IE':'')+'Styles']);Control.Modal.overlay.hide();Control.Modal.container=$(document.createElement('div'));Control.Modal.container.id='modal_container';Control.Modal.container.hide();Control.Modal.loading=$(document.createElement('div'));Control.Modal.loading.id='modal_loading';Control.Modal.loading.hide();var body_tag=document.getElementsByTagName('body')[0];body_tag.appendChild(Control.Modal.overlay);body_tag.appendChild(Control.Modal.container);body_tag.appendChild(Control.Modal.loading);Control.Modal.container.observe('mouseout',function(event){if(!Control.Modal.disableHoverClose&&Control.Modal.current&&Control.Modal.current.options.hover&&!Position.within(Control.Modal.container,Event.pointerX(event),Event.pointerY(event)))
Control.Modal.close();});}},open:function(contents,options){options=options||{};if(!options.contents)
options.contents=contents;var modal_instance=new Control.Modal(false,options);modal_instance.open();return modal_instance;},close:function(force){if(typeof(force)!='boolean')
force=false;if(Control.Modal.current)
Control.Modal.current.close(force);},attachEvents:function(){Event.observe(window,'load',Control.Modal.load);Event.observe(window,'unload',Event.unloadCache,false);},center:function(element){if(!element._absolutized){element.setStyle({position:'absolute'});element._absolutized=true;}
var dimensions=element.getDimensions();Position.prepare();var offset_left=(Position.deltaX+Math.floor((Control.Modal.getWindowWidth()-dimensions.width)/2));var offset_top=(Position.deltaY+((Control.Modal.getWindowHeight()>dimensions.height)?Math.floor((Control.Modal.getWindowHeight()-dimensions.height)/2):0));element.setStyle({top:((dimensions.height<=Control.Modal.getDocumentHeight())?((offset_top!=null&&offset_top>0)?offset_top:'0')+'px':0),left:((dimensions.width<=Control.Modal.getDocumentWidth())?((offset_left!=null&&offset_left>0)?offset_left:'0')+'px':0)});},getWindowWidth:function(){return(self.innerWidth||document.documentElement.clientWidth||document.body.clientWidth||0);},getWindowHeight:function(){return(self.innerHeight||document.documentElement.clientHeight||document.body.clientHeight||0);},getDocumentWidth:function(){return Math.min(document.body.scrollWidth,Control.Modal.getWindowWidth());},getDocumentHeight:function(){return Math.max(document.body.scrollHeight,Control.Modal.getWindowHeight());},onKeyDown:function(event){if(event.keyCode==Event.KEY_ESC)
Control.Modal.close();}});Object.extend(Control.Modal.prototype,{mode:'',html:false,href:'',element:false,src:false,imageLoaded:false,ajaxRequest:false,initialize:function(element,options){this.element=$(element);this.options={beforeOpen:Prototype.emptyFunction,afterOpen:Prototype.emptyFunction,beforeClose:Prototype.emptyFunction,afterClose:Prototype.emptyFunction,onSuccess:Prototype.emptyFunction,onFailure:Prototype.emptyFunction,onException:Prototype.emptyFunction,beforeImageLoad:Prototype.emptyFunction,afterImageLoad:Prototype.emptyFunction,autoOpenIfLinked:true,contents:false,loading:false,fade:false,fadeDuration:0.75,image:false,imageCloseOnClick:true,hover:false,iframe:false,iframeTemplate:new Template('<iframe src="#{href}" width="100%" height="100%" frameborder="0" id="#{id}"></iframe>'),evalScripts:true,requestOptions:{},overlayDisplay:true,overlayClassName:'',overlayCloseOnClick:true,containerClassName:'',opacity:0.3,zIndex:9998,width:null,height:null,offsetLeft:0,offsetTop:0,position:'absolute'};Object.extend(this.options,options||{});var target_match=false;var image_match=false;if(this.element){target_match=Control.Modal.targetRegexp.exec(this.element.href);image_match=Control.Modal.imgRegexp.exec(this.element.href);}
if(this.options.position=='mouse')
this.options.hover=true;if(this.options.contents){this.mode='contents';}else if(this.options.image||image_match){this.mode='image';this.src=this.element.href;}else if(target_match){this.mode='named';var x=$(target_match[1]);this.html=x.innerHTML;x.remove();this.href=target_match[1];}else{this.mode=(this.options.iframe)?'iframe':'ajax';this.href=this.element.href;}
if(this.element){if(this.options.hover){this.element.observe('mouseover',this.open.bind(this));this.element.observe('mouseout',function(event){if(!Position.within(Control.Modal.container,Event.pointerX(event),Event.pointerY(event)))
this.close();}.bindAsEventListener(this));}else{this.element.onclick=function(event){this.open();Event.stop(event);return false;}.bindAsEventListener(this);}}
var targets=Control.Modal.targetRegexp.exec(window.location);this.position=function(event){if(this.options.position=='absolute')
Control.Modal.center(Control.Modal.container);else{var xy=(event&&this.options.position=='mouse'?[Event.pointerX(event),Event.pointerY(event)]:Position.cumulativeOffset(this.element));Control.Modal.container.setStyle({position:'absolute',top:xy[1]+(typeof(this.options.offsetTop)=='function'?this.options.offsetTop():this.options.offsetTop)+'px',left:xy[0]+(typeof(this.options.offsetLeft)=='function'?this.options.offsetLeft():this.options.offsetLeft)+'px'});}
if(Control.Modal.ie){Control.Modal.overlay.setStyle({height:Control.Modal.getDocumentHeight()+'px',width:Control.Modal.getDocumentWidth()+'px'});}}.bind(this);if(this.mode=='named'&&this.options.autoOpenIfLinked&&targets&&targets[1]&&targets[1]==this.href)
this.open();},showLoadingIndicator:function(){if(this.options.loading){Control.Modal.loadingTimeout=window.setTimeout(function(){var modal_image=$('modal_image');if(modal_image)
modal_image.hide();Control.Modal.loading.style.zIndex=this.options.zIndex+1;Control.Modal.loading.update('<img id="modal_loading" src="'+this.options.loading+'"/>');Control.Modal.loading.show();Control.Modal.center(Control.Modal.loading);}.bind(this),250);}},hideLoadingIndicator:function(){if(this.options.loading){if(Control.Modal.loadingTimeout)
window.clearTimeout(Control.Modal.loadingTimeout);var modal_image=$('modal_image');if(modal_image)
modal_image.show();Control.Modal.loading.hide();}},open:function(force){if(!force&&this.notify('beforeOpen')===false)
return;if(!Control.Modal.loaded)
Control.Modal.load();Control.Modal.close();if(!this.options.hover)
Event.observe($(document.getElementsByTagName('body')[0]),'keydown',Control.Modal.onKeyDown);Control.Modal.current=this;if(!this.options.hover)
Control.Modal.overlay.setStyle({zIndex:this.options.zIndex,opacity:this.options.opacity});Control.Modal.container.setStyle({zIndex:this.options.zIndex+1,width:(this.options.width?(typeof(this.options.width)=='function'?this.options.width():this.options.width)+'px':null),height:(this.options.height?(typeof(this.options.height)=='function'?this.options.height():this.options.height)+'px':null)});if(Control.Modal.ie&&!this.options.hover){$A(document.getElementsByTagName('select')).each(function(select){select.style.visibility='hidden';});}
Control.Modal.overlay.addClassName(this.options.overlayClassName);Control.Modal.container.addClassName(this.options.containerClassName);switch(this.mode){case'image':this.imageLoaded=false;this.notify('beforeImageLoad');this.showLoadingIndicator();var img=document.createElement('img');img.onload=function(img){this.hideLoadingIndicator();this.update([img]);if(this.options.imageCloseOnClick)
$(img).observe('click',Control.Modal.close);this.position();this.notify('afterImageLoad');img.onload=null;}.bind(this,img);img.src=this.src;img.id='modal_image';break;case'ajax':this.notify('beforeLoad');var options={method:'post',onSuccess:function(request){this.hideLoadingIndicator();this.update(request.responseText);this.notify('onSuccess',request);this.ajaxRequest=false;}.bind(this),onFailure:function(){this.notify('onFailure');}.bind(this),onException:function(){this.notify('onException');}.bind(this)};Object.extend(options,this.options.requestOptions);this.showLoadingIndicator();this.ajaxRequest=new Ajax.Request(this.href,options);break;case'iframe':this.update(this.options.iframeTemplate.evaluate({href:this.href,id:'modal_iframe'}));break;case'contents':this.update((typeof(this.options.contents)=='function'?this.options.contents():this.options.contents));break;case'named':this.update(this.html);break;}
if(!this.options.hover){if(this.options.overlayCloseOnClick&&this.options.overlayDisplay)
Control.Modal.overlay.observe('click',Control.Modal.close);if(this.options.overlayDisplay){if(this.options.fade){if(Control.Modal.effects.overlayFade)
Control.Modal.effects.overlayFade.cancel();Control.Modal.effects.overlayAppear=new Effect.Appear(Control.Modal.overlay,{queue:{position:'front',scope:'Control.Modal'},to:this.options.opacity,duration:this.options.fadeDuration/2});}else
Control.Modal.overlay.show();}}
if(this.options.position=='mouse'){this.mouseHoverListener=this.position.bindAsEventListener(this);this.element.observe('mousemove',this.mouseHoverListener);}
this.notify('afterOpen');},update:function(html){if(typeof(html)=='string')
Control.Modal.container.update(html);else{Control.Modal.container.update('');(html.each)?html.each(function(node){Control.Modal.container.appendChild(node);}):Control.Modal.container.appendChild(node);}
if(this.options.fade){if(Control.Modal.effects.containerFade)
Control.Modal.effects.containerFade.cancel();Control.Modal.effects.containerAppear=new Effect.Appear(Control.Modal.container,{queue:{position:'end',scope:'Control.Modal'},to:1,duration:this.options.fadeDuration/2});}else
Control.Modal.container.show();this.position();Event.observe(window,'resize',this.position,false);Event.observe(window,'scroll',this.position,false);},close:function(force){if(!force&&this.notify('beforeClose')===false)
return;if(this.ajaxRequest)
this.ajaxRequest.transport.abort();this.hideLoadingIndicator();if(this.mode=='image'){var modal_image=$('modal_image');if(this.options.imageCloseOnClick&&modal_image)
modal_image.stopObserving('click',Control.Modal.close);}
if(Control.Modal.ie&&!this.options.hover){$A(document.getElementsByTagName('select')).each(function(select){select.style.visibility='visible';});}
if(!this.options.hover)
Event.stopObserving(window,'keyup',Control.Modal.onKeyDown);Control.Modal.current=false;Event.stopObserving(window,'resize',this.position,false);Event.stopObserving(window,'scroll',this.position,false);if(!this.options.hover){if(this.options.overlayCloseOnClick&&this.options.overlayDisplay)
Control.Modal.overlay.stopObserving('click',Control.Modal.close);if(this.options.overlayDisplay){if(this.options.fade){if(Control.Modal.effects.overlayAppear)
Control.Modal.effects.overlayAppear.cancel();Control.Modal.effects.overlayFade=new Effect.Fade(Control.Modal.overlay,{queue:{position:'end',scope:'Control.Modal'},from:this.options.opacity,to:0,duration:this.options.fadeDuration/2});}else
Control.Modal.overlay.hide();}}
if(this.options.fade){if(Control.Modal.effects.containerAppear)
Control.Modal.effects.containerAppear.cancel();Control.Modal.effects.containerFade=new Effect.Fade(Control.Modal.container,{queue:{position:'front',scope:'Control.Modal'},from:1,to:0,duration:this.options.fadeDuration/2,afterFinish:function(){Control.Modal.container.update('');this.resetClassNameAndStyles();}.bind(this)});}else{Control.Modal.container.hide();Control.Modal.container.update('');this.resetClassNameAndStyles();}
if(this.options.position=='mouse')
this.element.stopObserving('mousemove',this.mouseHoverListener);this.notify('afterClose');},resetClassNameAndStyles:function(){Control.Modal.overlay.removeClassName(this.options.overlayClassName);Control.Modal.container.removeClassName(this.options.containerClassName);Control.Modal.container.setStyle({height:null,width:null,top:null,left:null});},notify:function(event_name){try{if(this.options[event_name])
return[this.options[event_name].apply(this.options[event_name],$A(arguments).slice(1))];}catch(e){if(e!=$break)
throw e;else
return false;}}});if(typeof(Object.Event)!='undefined')
Object.Event.extend(Control.Modal);Control.Modal.attachEvents();var niftyOk=(document.getElementById&&document.createElement&&Array.prototype.push);var niftyCss=false;String.prototype.find=function(what){return(this.indexOf(what)>=0?true:false);}
function Nifty(selector,options){if(niftyOk==false)return;var i,v=selector.split(","),h=0;if(options==null)options="";if(options.find("fixed-height"))
h=getElementsBySelector(v[0])[0].offsetHeight;for(i=0;i<v.length;i++)
Rounded(v[i],options);if(options.find("height"))SameHeight(selector,h);}
function Rounded(selector,options){var i,top="",bottom="",v=new Array();if(options!=""){options=options.replace("left","tl bl");options=options.replace("right","tr br");options=options.replace("top","tr tl");options=options.replace("bottom","br bl");options=options.replace("transparent","alias");if(options.find("tl")){top="both";if(!options.find("tr"))top="left";}
else if(options.find("tr"))top="right";if(options.find("bl")){bottom="both";if(!options.find("br"))bottom="left";}
else if(options.find("br"))bottom="right";}
if(top==""&&bottom==""&&!options.find("none")){top="both";bottom="both";}
v=getElementsBySelector(selector);for(i=0;i<v.length;i++){FixIE(v[i]);if(top!="")AddTop(v[i],top,options);if(bottom!="")AddBottom(v[i],bottom,options);}}
function AddTop(el,side,options){var d=CreateEl("b"),lim=4,border="",p,i,btype="r",bk,color;d.style.marginLeft="-"+getPadding(el,"Left")+"px";d.style.marginRight="-"+getPadding(el,"Right")+"px";if(options.find("alias")||(color=getBk(el))=="transparent"){color="transparent";bk="transparent";border=getParentBk(el);btype="t";}
else{bk=getParentBk(el);border=Mix(color,bk);}
d.style.background=bk;d.className="niftycorners";p=getPadding(el,"Top");if(options.find("small")){d.style.marginBottom=(p-2)+"px";btype+="s";lim=2;}
else if(options.find("big")){d.style.marginBottom=(p-10)+"px";btype+="b";lim=8;}
else d.style.marginBottom=(p-5)+"px";for(i=1;i<=lim;i++)
d.appendChild(CreateStrip(i,side,color,border,btype));el.style.paddingTop="0";el.insertBefore(d,el.firstChild);}
function AddBottom(el,side,options){var d=CreateEl("b"),lim=4,border="",p,i,btype="r",bk,color;d.style.marginLeft="-"+getPadding(el,"Left")+"px";d.style.marginRight="-"+getPadding(el,"Right")+"px";if(options.find("alias")||(color=getBk(el))=="transparent"){color="transparent";bk="transparent";border=getParentBk(el);btype="t";}
else{bk=getParentBk(el);border=Mix(color,bk);}
d.style.background=bk;d.className="niftycorners";p=getPadding(el,"Bottom");if(options.find("small")){d.style.marginTop=(p-2)+"px";btype+="s";lim=2;}
else if(options.find("big")){d.style.marginTop=(p-10)+"px";btype+="b";lim=8;}
else d.style.marginTop=(p-5)+"px";for(i=lim;i>0;i--)
d.appendChild(CreateStrip(i,side,color,border,btype));el.style.paddingBottom=0;el.appendChild(d);}
function CreateStrip(index,side,color,border,btype){var x=CreateEl("b");x.className=btype+index;x.style.backgroundColor=color;x.style.borderColor=border;if(side=="left"){x.style.borderRightWidth="0";x.style.marginRight="0";}
else if(side=="right"){x.style.borderLeftWidth="0";x.style.marginLeft="0";}
return(x);}
function CreateEl(x){return(document.createElement(x));}
function FixIE(el){if(el.currentStyle!=null&&el.currentStyle.hasLayout!=null&&el.currentStyle.hasLayout==false)
el.style.display="inline-block";}
function SameHeight(selector,maxh){var i,v=selector.split(","),t,j,els=[],gap;for(i=0;i<v.length;i++){t=getElementsBySelector(v[i]);els=els.concat(t);}
for(i=0;i<els.length;i++){if(els[i].offsetHeight>maxh)maxh=els[i].offsetHeight;els[i].style.height="auto";}
for(i=0;i<els.length;i++){gap=maxh-els[i].offsetHeight;if(gap>0){t=CreateEl("b");t.className="niftyfill";t.style.height=gap+"px";nc=els[i].lastChild;if(nc.className=="niftycorners")
els[i].insertBefore(t,nc);else els[i].appendChild(t);}}}
function getElementsBySelector(selector){var i,j,selid="",selclass="",tag=selector,tag2="",v2,k,f,a,s=[],objlist=[],c;if(selector.find("#")){if(selector.find(" ")){s=selector.split(" ");var fs=s[0].split("#");if(fs.length==1)return(objlist);f=document.getElementById(fs[1]);if(f){v=f.getElementsByTagName(s[1]);for(i=0;i<v.length;i++)objlist.push(v[i]);}
return(objlist);}
else{s=selector.split("#");tag=s[0];selid=s[1];if(selid!=""){f=document.getElementById(selid);if(f)objlist.push(f);return(objlist);}}}
if(selector.find(".")){s=selector.split(".");tag=s[0];selclass=s[1];if(selclass.find(" ")){s=selclass.split(" ");selclass=s[0];tag2=s[1];}}
var v=document.getElementsByTagName(tag);if(selclass==""){for(i=0;i<v.length;i++)objlist.push(v[i]);return(objlist);}
for(i=0;i<v.length;i++){c=v[i].className.split(" ");for(j=0;j<c.length;j++){if(c[j]==selclass){if(tag2=="")objlist.push(v[i]);else{v2=v[i].getElementsByTagName(tag2);for(k=0;k<v2.length;k++)objlist.push(v2[k]);}}}}
return(objlist);}
function getParentBk(x){var el=x.parentNode,c;while(el.tagName.toUpperCase()!="HTML"&&(c=getBk(el))=="transparent")
el=el.parentNode;if(c=="transparent")c="#FFFFFF";return(c);}
function getBk(x){var c=getStyleProp(x,"backgroundColor");if(c==null||c=="transparent"||c.find("rgba(0, 0, 0, 0)"))
return("transparent");if(c.find("rgb"))c=rgb2hex(c);return(c);}
function getPadding(x,side){var p=getStyleProp(x,"padding"+side);if(p==null||!p.find("px"))return(0);return(parseInt(p));}
function getStyleProp(x,prop){if(x.currentStyle)
return(x.currentStyle[prop]);if(document.defaultView.getComputedStyle)
return(document.defaultView.getComputedStyle(x,'')[prop]);return(null);}
function rgb2hex(value){var hex="",v,h,i;var regexp=/([0-9]+)[, ]+([0-9]+)[, ]+([0-9]+)/;var h=regexp.exec(value);for(i=1;i<4;i++){v=parseInt(h[i]).toString(16);if(v.length==1)hex+="0"+v;else hex+=v;}
return("#"+hex);}
function Mix(c1,c2){var i,step1,step2,x,y,r=new Array(3);if(c1.length==4)step1=1;else step1=2;if(c2.length==4)step2=1;else step2=2;for(i=0;i<3;i++){x=parseInt(c1.substr(1+step1*i,step1),16);if(step1==1)x=16*x+x;y=parseInt(c2.substr(1+step2*i,step2),16);if(step2==1)y=16*y+y;r[i]=Math.floor((x*50+y*50)/100);r[i]=r[i].toString(16);if(r[i].length==1)r[i]="0"+r[i];}
return("#"+r[0]+r[1]+r[2]);}
if(typeof(Control)=='undefined')
Control={};Control.Rating=Class.create();Object.extend(Control.Rating,{instances:[],findByElementId:function(id){return Control.Rating.instances.find(function(instance){return(instance.container.id&&instance.container.id==id);});}});Control.staticHTML=Class.create();Control.staticHTML.prototype={initialize:function(prefix){},build:function(rating){var h=[];var diff;for(var i=0;i<5;i++){diff=rating-i;if(diff>0){if(diff>=1){h.push('<a class="rating_on rating_selected"></a>');}else{h.push('<a class="rating_half rating_selected"></a>');}}else{h.push('<a class="rating_off rating_selected"></a>');}}
return h;}}
Object.extend(Control.Rating.prototype,{container:false,value:false,options:{},initialize:function(container,options){this.value=false;this.links=[];this.container=$(container);this.container.update('');this.options={min:1,max:5,rated:false,input:false,reverse:false,capture:false,multiple:false,classNames:{off:'rating_off',half:'rating_half',on:'rating_on',selected:'rating_selected'},updateUrl:false,updateParameterName:'value',afterChange:Prototype.emptyFunction};Object.extend(this.options,options||{});if(this.options.value){this.value=this.options.value;delete this.options.value;}
if(this.options.input){this.options.input=$(this.options.input);this.options.input.observe('change',function(input){this.setValueFromInput(input);}.bind(this,this.options.input));this.setValueFromInput(this.options.input,true);}
var range=$R(this.options.min,this.options.max);(this.options.reverse?$A(range).reverse():range).each(function(i){var link=this.buildLink(i);this.container.appendChild(link);this.links.push(link);}.bind(this));this.setValue(this.value||0,false,true);},buildLink:function(rating){var link=$(document.createElement('a'));link.value=rating;if(this.options.multiple||(!this.options.rated&&!this.options.multiple)){link.href='';link.onmouseover=this.mouseOver.bind(this,link);link.onmouseout=this.mouseOut.bind(this,link);link.onclick=this.click.bindAsEventListener(this,link);}else{link.style.cursor='default';link.observe('click',function(event){Event.stop(event);return false;}.bindAsEventListener(this));}
link.addClassName(this.options.classNames.off);return link;},disable:function(){this.links.each(function(link){link.onmouseover=Prototype.emptyFunction;link.onmouseout=Prototype.emptyFunction;link.onclick=Prototype.emptyFunction;link.observe('click',function(event){Event.stop(event);return false;}.bindAsEventListener(this));link.style.cursor='default';}.bind(this));},setValueFromInput:function(input,prevent_callbacks){this.setValue((input.options?input.options[input.options.selectedIndex].value:input.value),true,prevent_callbacks);},setValue:function(value,force_selected,prevent_callbacks){this.value=value;if(this.options.input){if(this.options.input.options){$A(this.options.input.options).each(function(option,i){if(option.value==this.value){this.options.input.options.selectedIndex=i;throw $break;}}.bind(this));}else
this.options.input.value=this.value;}
this.render(this.value,force_selected);if(!prevent_callbacks){if(this.options.updateUrl){var params={};params[this.options.updateParamterName]=this.value;new Ajax.Request(this.options.updateUrl,{parameters:params});}
this.notify('afterChange',this.value);}},render:function(rating,force_selected){(this.options.reverse?this.links.reverse():this.links).each(function(link){if(link.value<=Math.ceil(rating)){link.className=this.options.classNames[link.value<=rating?'on':'half'];if(this.options.rated||force_selected)
link.addClassName(this.options.classNames.selected);}else
link.className=this.options.classNames.off;}.bind(this));},mouseOver:function(link){this.render(link.value,true);},mouseOut:function(link){this.render(this.value);},click:function(event,link){this.options.rated=true;this.setValue((link.value?link.value:link),true);if(!this.options.multiple)
this.disable();if(this.options.capture){Event.stop(event);return false;}},notify:function(event_name){try{if(this.options[event_name])
return[this.options[event_name].apply(this.options[event_name],$A(arguments).slice(1))];}catch(e){if(e!=$break)
throw e;else
return false;}}});if(typeof(Object.Event)!='undefined')
Object.Event.extend(Control.Rating);if(typeof deconcept=="undefined")var deconcept=new Object();if(typeof deconcept.util=="undefined")deconcept.util=new Object();if(typeof deconcept.SWFObjectUtil=="undefined")deconcept.SWFObjectUtil=new Object();deconcept.SWFObject=function(swf,id,w,h,ver,c,quality,xiRedirectUrl,redirectUrl,detectKey){if(!document.getElementById){return;}
this.DETECT_KEY=detectKey?detectKey:'detectflash';this.skipDetect=deconcept.util.getRequestParameter(this.DETECT_KEY);this.params=new Object();this.variables=new Object();this.attributes=new Array();if(swf){this.setAttribute('swf',swf);}
if(id){this.setAttribute('id',id);}
if(w){this.setAttribute('width',w);}
if(h){this.setAttribute('height',h);}
if(ver){this.setAttribute('version',new deconcept.PlayerVersion(ver.toString().split(".")));}
this.installedVer=deconcept.SWFObjectUtil.getPlayerVersion();if(!window.opera&&document.all&&this.installedVer.major>7){deconcept.SWFObject.doPrepUnload=true;}
if(c){this.addParam('bgcolor',c);}
var q=quality?quality:'high';this.addParam('quality',q);this.setAttribute('useExpressInstall',false);this.setAttribute('doExpressInstall',false);var xir=(xiRedirectUrl)?xiRedirectUrl:window.location;this.setAttribute('xiRedirectUrl',xir);this.setAttribute('redirectUrl','');if(redirectUrl){this.setAttribute('redirectUrl',redirectUrl);}}
deconcept.SWFObject.prototype={useExpressInstall:function(path){this.xiSWFPath=!path?"expressinstall.swf":path;this.setAttribute('useExpressInstall',true);},setAttribute:function(name,value){this.attributes[name]=value;},getAttribute:function(name){return this.attributes[name];},addParam:function(name,value){this.params[name]=value;},getParams:function(){return this.params;},addVariable:function(name,value){this.variables[name]=value;},getVariable:function(name){return this.variables[name];},getVariables:function(){return this.variables;},getVariablePairs:function(){var variablePairs=new Array();var key;var variables=this.getVariables();for(key in variables){variablePairs[variablePairs.length]=key+"="+variables[key];}
return variablePairs;},getSWFHTML:function(){var swfNode="";if(navigator.plugins&&navigator.mimeTypes&&navigator.mimeTypes.length){if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","PlugIn");this.setAttribute('swf',this.xiSWFPath);}
swfNode='<embed type="application/x-shockwave-flash" src="'+this.getAttribute('swf')+'" width="'+this.getAttribute('width')+'" height="'+this.getAttribute('height')+'" style="'+this.getAttribute('style')+'"';swfNode+=' id="'+this.getAttribute('id')+'" name="'+this.getAttribute('id')+'" ';var params=this.getParams();for(var key in params){swfNode+=[key]+'="'+params[key]+'" ';}
var pairs=this.getVariablePairs().join("&");if(pairs.length>0){swfNode+='flashvars="'+pairs+'"';}
swfNode+='/>';}else{if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","ActiveX");this.setAttribute('swf',this.xiSWFPath);}
swfNode='<object id="'+this.getAttribute('id')+'" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="'+this.getAttribute('width')+'" height="'+this.getAttribute('height')+'" style="'+this.getAttribute('style')+'">';swfNode+='<param name="movie" value="'+this.getAttribute('swf')+'" />';var params=this.getParams();for(var key in params){swfNode+='<param name="'+key+'" value="'+params[key]+'" />';}
var pairs=this.getVariablePairs().join("&");if(pairs.length>0){swfNode+='<param name="flashvars" value="'+pairs+'" />';}
swfNode+="</object>";}
return swfNode;},write:function(elementId){if(this.getAttribute('useExpressInstall')){var expressInstallReqVer=new deconcept.PlayerVersion([6,0,65]);if(this.installedVer.versionIsValid(expressInstallReqVer)&&!this.installedVer.versionIsValid(this.getAttribute('version'))){this.setAttribute('doExpressInstall',true);this.addVariable("MMredirectURL",escape(this.getAttribute('xiRedirectUrl')));document.title=document.title.slice(0,47)+" - Flash Player Installation";this.addVariable("MMdoctitle",document.title);}}
if(this.skipDetect||this.getAttribute('doExpressInstall')||this.installedVer.versionIsValid(this.getAttribute('version'))){var n=(typeof elementId=='string')?document.getElementById(elementId):elementId;n.innerHTML=this.getSWFHTML();return true;}else{if(this.getAttribute('redirectUrl')!=""){document.location.replace(this.getAttribute('redirectUrl'));}}
return false;}}
deconcept.SWFObjectUtil.getPlayerVersion=function(){var PlayerVersion=new deconcept.PlayerVersion([0,0,0]);if(navigator.plugins&&navigator.mimeTypes.length){var x=navigator.plugins["Shockwave Flash"];if(x&&x.description){PlayerVersion=new deconcept.PlayerVersion(x.description.replace(/([a-zA-Z]|\s)+/,"").replace(/(\s+r|\s+b[0-9]+)/,".").split("."));}}else if(navigator.userAgent&&navigator.userAgent.indexOf("Windows CE")>=0){var axo=1;var counter=3;while(axo){try{counter++;axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash."+counter);PlayerVersion=new deconcept.PlayerVersion([counter,0,0]);}catch(e){axo=null;}}}else{try{var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");}catch(e){try{var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");PlayerVersion=new deconcept.PlayerVersion([6,0,21]);axo.AllowScriptAccess="always";}catch(e){if(PlayerVersion.major==6){return PlayerVersion;}}
try{axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash");}catch(e){}}
if(axo!=null){PlayerVersion=new deconcept.PlayerVersion(axo.GetVariable("$version").split(" ")[1].split(","));}}
return PlayerVersion;}
deconcept.PlayerVersion=function(arrVersion){this.major=arrVersion[0]!=null?parseInt(arrVersion[0]):0;this.minor=arrVersion[1]!=null?parseInt(arrVersion[1]):0;this.rev=arrVersion[2]!=null?parseInt(arrVersion[2]):0;}
deconcept.PlayerVersion.prototype.versionIsValid=function(fv){if(this.major<fv.major)return false;if(this.major>fv.major)return true;if(this.minor<fv.minor)return false;if(this.minor>fv.minor)return true;if(this.rev<fv.rev)return false;return true;}
deconcept.util={getRequestParameter:function(param){var q=document.location.search||document.location.hash;if(param==null){return q;}
if(q){var pairs=q.substring(1).split("&");for(var i=0;i<pairs.length;i++){if(pairs[i].substring(0,pairs[i].indexOf("="))==param){return pairs[i].substring((pairs[i].indexOf("=")+1));}}}
return"";}}
deconcept.SWFObjectUtil.cleanupSWFs=function(){var objects=document.getElementsByTagName("OBJECT");for(var i=objects.length-1;i>=0;i--){objects[i].style.display='none';for(var x in objects[i]){if(typeof objects[i][x]=='function'){objects[i][x]=function(){};}}}}
if(deconcept.SWFObject.doPrepUnload){if(!deconcept.unloadSet){deconcept.SWFObjectUtil.prepUnload=function(){__flash_unloadHandler=function(){};__flash_savedUnloadHandler=function(){};window.attachEvent("onunload",deconcept.SWFObjectUtil.cleanupSWFs);}
window.attachEvent("onbeforeunload",deconcept.SWFObjectUtil.prepUnload);deconcept.unloadSet=true;}}
if(!document.getElementById&&document.all){document.getElementById=function(id){return document.all[id];}}
var getQueryParamValue=deconcept.util.getRequestParameter;var FlashObject=deconcept.SWFObject;var SWFObject=deconcept.SWFObject;function xpathLog(msg){};function xsltLog(msg){};function xsltLogXml(msg){};var ajaxsltIsIE6=navigator.appVersion.match(/MSIE 6.0/);function assert(b){if(!b){throw"Assertion failed";}}
function stringSplit(s,c){var a=s.indexOf(c);if(a==-1){return[s];}
var parts=[];parts.push(s.substr(0,a));while(a!=-1){var a1=s.indexOf(c,a+1);if(a1!=-1){parts.push(s.substr(a+1,a1-a-1));}else{parts.push(s.substr(a+1));}
a=a1;}
return parts;}
function xmlImportNode(doc,node){if(node.nodeType==DOM_TEXT_NODE){return domCreateTextNode(doc,node.nodeValue);}else if(node.nodeType==DOM_CDATA_SECTION_NODE){return domCreateCDATASection(doc,node.nodeValue);}else if(node.nodeType==DOM_ELEMENT_NODE){var newNode=domCreateElement(doc,node.nodeName);for(var i=0;i<node.attributes.length;++i){var an=node.attributes[i];var name=an.nodeName;var value=an.nodeValue;domSetAttribute(newNode,name,value);}
for(var c=node.firstChild;c;c=c.nextSibling){var cn=arguments.callee(doc,c);domAppendChild(newNode,cn);}
return newNode;}else{return domCreateComment(doc,node.nodeName);}}
function Set(){this.keys=[];}
Set.prototype.size=function(){return this.keys.length;}
Set.prototype.add=function(key,opt_value){var value=opt_value||1;if(!this.contains(key)){this[':'+key]=value;this.keys.push(key);}}
Set.prototype.set=function(key,opt_value){var value=opt_value||1;if(!this.contains(key)){this[':'+key]=value;this.keys.push(key);}else{this[':'+key]=value;}}
Set.prototype.inc=function(key){if(!this.contains(key)){this[':'+key]=1;this.keys.push(key);}else{this[':'+key]++;}}
Set.prototype.get=function(key){if(this.contains(key)){return this[':'+key];}else{var undefined;return undefined;}}
Set.prototype.remove=function(key){if(this.contains(key)){delete this[':'+key];removeFromArray(this.keys,key,true);}}
Set.prototype.contains=function(entry){return typeof this[':'+entry]!='undefined';}
Set.prototype.items=function(){var list=[];for(var i=0;i<this.keys.length;++i){var k=this.keys[i];var v=this[':'+k];list.push(v);}
return list;}
Set.prototype.map=function(f){for(var i=0;i<this.keys.length;++i){var k=this.keys[i];f.call(this,k,this[':'+k]);}}
Set.prototype.clear=function(){for(var i=0;i<this.keys.length;++i){delete this[':'+this.keys[i]];}
this.keys.length=0;}
function mapExec(array,func){for(var i=0;i<array.length;++i){func.call(this,array[i],i);}}
function mapExpr(array,func){var ret=[];for(var i=0;i<array.length;++i){ret.push(func(array[i]));}
return ret;};function reverseInplace(array){for(var i=0;i<array.length/2;++i){var h=array[i];var ii=array.length-i-1;array[i]=array[ii];array[ii]=h;}}
function removeFromArray(array,value,opt_notype){var shift=0;for(var i=0;i<array.length;++i){if(array[i]===value||(opt_notype&&array[i]==value)){array.splice(i--,1);shift++;}}
return shift;}
function copyArray(dst,src){if(!src)return;var dstLength=dst.length;for(var i=src.length-1;i>=0;--i){dst[i+dstLength]=src[i];}}
function copyArrayIgnoringAttributesWithoutValue(dst,src)
{if(!src)return;for(var i=src.length-1;i>=0;--i){if(src[i].nodeValue){dst.push(src[i]);}}}
function xmlValue(node){if(!node){return'';}
var ret='';if(node.nodeType==DOM_TEXT_NODE||node.nodeType==DOM_CDATA_SECTION_NODE){ret+=node.nodeValue;}else if(node.nodeType==DOM_ATTRIBUTE_NODE){if(ajaxsltIsIE6){ret+=xmlValueIE6Hack(node);}else{ret+=node.nodeValue;}}else if(node.nodeType==DOM_ELEMENT_NODE||node.nodeType==DOM_DOCUMENT_NODE||node.nodeType==DOM_DOCUMENT_FRAGMENT_NODE){for(var i=0;i<node.childNodes.length;++i){ret+=arguments.callee(node.childNodes[i]);}}
return ret;}
function xmlValueIE6Hack(node){var nodeName=node.nodeName;var nodeValue=node.nodeValue;if(nodeName.length!=4)return nodeValue;if(!/^href$/i.test(nodeName))return nodeValue;if(!/^javascript:/.test(nodeValue))return nodeValue;return unescape(nodeValue);}
function xmlText(node,opt_cdata){var buf=[];xmlTextR(node,buf,opt_cdata);return buf.join('');}
function xmlTextR(node,buf,cdata){if(node.nodeType==DOM_TEXT_NODE){buf.push(xmlEscapeText(node.nodeValue));}else if(node.nodeType==DOM_CDATA_SECTION_NODE){if(cdata){buf.push(node.nodeValue);}else{buf.push('<![CDATA['+node.nodeValue+']]>');}}else if(node.nodeType==DOM_COMMENT_NODE){buf.push('<!--'+node.nodeValue+'-->');}else if(node.nodeType==DOM_ELEMENT_NODE){buf.push('<'+xmlFullNodeName(node));for(var i=0;i<node.attributes.length;++i){var a=node.attributes[i];if(a&&a.nodeName&&a.nodeValue){buf.push(' '+xmlFullNodeName(a)+'="'+
xmlEscapeAttr(a.nodeValue)+'"');}}
if(node.childNodes.length==0){buf.push('/>');}else{buf.push('>');for(var i=0;i<node.childNodes.length;++i){arguments.callee(node.childNodes[i],buf,cdata);}
buf.push('</'+xmlFullNodeName(node)+'>');}}else if(node.nodeType==DOM_DOCUMENT_NODE||node.nodeType==DOM_DOCUMENT_FRAGMENT_NODE){for(var i=0;i<node.childNodes.length;++i){arguments.callee(node.childNodes[i],buf,cdata);}}}
function xmlFullNodeName(n){if(n.prefix&&n.nodeName.indexOf(n.prefix+':')!=0){return n.prefix+':'+n.nodeName;}else{return n.nodeName;}}
function xmlEscapeText(s){return(''+s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');}
function xmlEscapeAttr(s){return xmlEscapeText(s).replace(/\"/g,'&quot;');}
function xmlEscapeTags(s){return s.replace(/</g,'&lt;').replace(/>/g,'&gt;');}
function xmlOwnerDocument(node){if(node.nodeType==DOM_DOCUMENT_NODE){return node;}else{return node.ownerDocument;}}
function domGetAttribute(node,name){return node.getAttribute(name);}
function domSetAttribute(node,name,value){return node.setAttribute(name,value);}
function domRemoveAttribute(node,name){return node.removeAttribute(name);}
function domAppendChild(node,child){return node.appendChild(child);}
function domRemoveChild(node,child){return node.removeChild(child);}
function domReplaceChild(node,newChild,oldChild){return node.replaceChild(newChild,oldChild);}
function domInsertBefore(node,newChild,oldChild){return node.insertBefore(newChild,oldChild);}
function domRemoveNode(node){return domRemoveChild(node.parentNode,node);}
function domCreateTextNode(doc,text){return doc.createTextNode(text);}
function domCreateElement(doc,name){return doc.createElement(name);}
function domCreateAttribute(doc,name){return doc.createAttribute(name);}
function domCreateCDATASection(doc,data){return doc.createCDATASection(data);}
function domCreateComment(doc,text){return doc.createComment(text);}
function domCreateDocumentFragment(doc){return doc.createDocumentFragment();}
function domGetElementById(doc,id){return doc.getElementById(id);}
function windowSetInterval(win,fun,time){return win.setInterval(fun,time);}
function windowClearInterval(win,id){return win.clearInterval(id);}
var REGEXP_UNICODE=function(){var tests=[' ','\u0120',-1,'!','\u0120',-1,'\u0120','\u0120',0,'\u0121','\u0120',-1,'\u0121','\u0120|\u0121',0,'\u0122','\u0120|\u0121',-1,'\u0120','[\u0120]',0,'\u0121','[\u0120]',-1,'\u0121','[\u0120\u0121]',0,'\u0122','[\u0120\u0121]',-1,'\u0121','[\u0120-\u0121]',0,'\u0122','[\u0120-\u0121]',-1];for(var i=0;i<tests.length;i+=3){if(tests[i].search(new RegExp(tests[i+1]))!=tests[i+2]){return false;}}
return true;}();var XML_S='[ \t\r\n]+';var XML_EQ='('+XML_S+')?=('+XML_S+')?';var XML_CHAR_REF='&#[0-9]+;|&#x[0-9a-fA-F]+;';var XML10_VERSION_INFO=XML_S+'version'+XML_EQ+'("1\\.0"|'+"'1\\.0')";var XML10_BASE_CHAR=(REGEXP_UNICODE)?'\u0041-\u005a\u0061-\u007a\u00c0-\u00d6\u00d8-\u00f6\u00f8-\u00ff'+'\u0100-\u0131\u0134-\u013e\u0141-\u0148\u014a-\u017e\u0180-\u01c3'+'\u01cd-\u01f0\u01f4-\u01f5\u01fa-\u0217\u0250-\u02a8\u02bb-\u02c1\u0386'+'\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03ce\u03d0-\u03d6\u03da\u03dc'+'\u03de\u03e0\u03e2-\u03f3\u0401-\u040c\u040e-\u044f\u0451-\u045c'+'\u045e-\u0481\u0490-\u04c4\u04c7-\u04c8\u04cb-\u04cc\u04d0-\u04eb'+'\u04ee-\u04f5\u04f8-\u04f9\u0531-\u0556\u0559\u0561-\u0586\u05d0-\u05ea'+'\u05f0-\u05f2\u0621-\u063a\u0641-\u064a\u0671-\u06b7\u06ba-\u06be'+'\u06c0-\u06ce\u06d0-\u06d3\u06d5\u06e5-\u06e6\u0905-\u0939\u093d'+'\u0958-\u0961\u0985-\u098c\u098f-\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2'+'\u09b6-\u09b9\u09dc-\u09dd\u09df-\u09e1\u09f0-\u09f1\u0a05-\u0a0a'+'\u0a0f-\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32-\u0a33\u0a35-\u0a36'+'\u0a38-\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8b\u0a8d'+'\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2-\u0ab3\u0ab5-\u0ab9'+'\u0abd\u0ae0\u0b05-\u0b0c\u0b0f-\u0b10\u0b13-\u0b28\u0b2a-\u0b30'+'\u0b32-\u0b33\u0b36-\u0b39\u0b3d\u0b5c-\u0b5d\u0b5f-\u0b61\u0b85-\u0b8a'+'\u0b8e-\u0b90\u0b92-\u0b95\u0b99-\u0b9a\u0b9c\u0b9e-\u0b9f\u0ba3-\u0ba4'+'\u0ba8-\u0baa\u0bae-\u0bb5\u0bb7-\u0bb9\u0c05-\u0c0c\u0c0e-\u0c10'+'\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c60-\u0c61\u0c85-\u0c8c'+'\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cde\u0ce0-\u0ce1'+'\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d28\u0d2a-\u0d39\u0d60-\u0d61'+'\u0e01-\u0e2e\u0e30\u0e32-\u0e33\u0e40-\u0e45\u0e81-\u0e82\u0e84'+'\u0e87-\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5'+'\u0ea7\u0eaa-\u0eab\u0ead-\u0eae\u0eb0\u0eb2-\u0eb3\u0ebd\u0ec0-\u0ec4'+'\u0f40-\u0f47\u0f49-\u0f69\u10a0-\u10c5\u10d0-\u10f6\u1100\u1102-\u1103'+'\u1105-\u1107\u1109\u110b-\u110c\u110e-\u1112\u113c\u113e\u1140\u114c'+'\u114e\u1150\u1154-\u1155\u1159\u115f-\u1161\u1163\u1165\u1167\u1169'+'\u116d-\u116e\u1172-\u1173\u1175\u119e\u11a8\u11ab\u11ae-\u11af'+'\u11b7-\u11b8\u11ba\u11bc-\u11c2\u11eb\u11f0\u11f9\u1e00-\u1e9b'+'\u1ea0-\u1ef9\u1f00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d'+'\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc'+'\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec'+'\u1ff2-\u1ff4\u1ff6-\u1ffc\u2126\u212a-\u212b\u212e\u2180-\u2182'+'\u3041-\u3094\u30a1-\u30fa\u3105-\u312c\uac00-\ud7a3':'A-Za-z';var XML10_IDEOGRAPHIC=(REGEXP_UNICODE)?'\u4e00-\u9fa5\u3007\u3021-\u3029':'';var XML10_COMBINING_CHAR=(REGEXP_UNICODE)?'\u0300-\u0345\u0360-\u0361\u0483-\u0486\u0591-\u05a1\u05a3-\u05b9'+'\u05bb-\u05bd\u05bf\u05c1-\u05c2\u05c4\u064b-\u0652\u0670\u06d6-\u06dc'+'\u06dd-\u06df\u06e0-\u06e4\u06e7-\u06e8\u06ea-\u06ed\u0901-\u0903\u093c'+'\u093e-\u094c\u094d\u0951-\u0954\u0962-\u0963\u0981-\u0983\u09bc\u09be'+'\u09bf\u09c0-\u09c4\u09c7-\u09c8\u09cb-\u09cd\u09d7\u09e2-\u09e3\u0a02'+'\u0a3c\u0a3e\u0a3f\u0a40-\u0a42\u0a47-\u0a48\u0a4b-\u0a4d\u0a70-\u0a71'+'\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0b01-\u0b03'+'\u0b3c\u0b3e-\u0b43\u0b47-\u0b48\u0b4b-\u0b4d\u0b56-\u0b57\u0b82-\u0b83'+'\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0c01-\u0c03\u0c3e-\u0c44'+'\u0c46-\u0c48\u0c4a-\u0c4d\u0c55-\u0c56\u0c82-\u0c83\u0cbe-\u0cc4'+'\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5-\u0cd6\u0d02-\u0d03\u0d3e-\u0d43'+'\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1'+'\u0eb4-\u0eb9\u0ebb-\u0ebc\u0ec8-\u0ecd\u0f18-\u0f19\u0f35\u0f37\u0f39'+'\u0f3e\u0f3f\u0f71-\u0f84\u0f86-\u0f8b\u0f90-\u0f95\u0f97\u0f99-\u0fad'+'\u0fb1-\u0fb7\u0fb9\u20d0-\u20dc\u20e1\u302a-\u302f\u3099\u309a':'';var XML10_DIGIT=(REGEXP_UNICODE)?'\u0030-\u0039\u0660-\u0669\u06f0-\u06f9\u0966-\u096f\u09e6-\u09ef'+'\u0a66-\u0a6f\u0ae6-\u0aef\u0b66-\u0b6f\u0be7-\u0bef\u0c66-\u0c6f'+'\u0ce6-\u0cef\u0d66-\u0d6f\u0e50-\u0e59\u0ed0-\u0ed9\u0f20-\u0f29':'0-9';var XML10_EXTENDER=(REGEXP_UNICODE)?'\u00b7\u02d0\u02d1\u0387\u0640\u0e46\u0ec6\u3005\u3031-\u3035'+'\u309d-\u309e\u30fc-\u30fe':'';var XML10_LETTER=XML10_BASE_CHAR+XML10_IDEOGRAPHIC;var XML10_NAME_CHAR=XML10_LETTER+XML10_DIGIT+'\\._:'+
XML10_COMBINING_CHAR+XML10_EXTENDER+'-';var XML10_NAME='['+XML10_LETTER+'_:]['+XML10_NAME_CHAR+']*';var XML10_ENTITY_REF='&'+XML10_NAME+';';var XML10_REFERENCE=XML10_ENTITY_REF+'|'+XML_CHAR_REF;var XML10_ATT_VALUE='"(([^<&"]|'+XML10_REFERENCE+')*)"|'+"'(([^<&']|"+XML10_REFERENCE+")*)'";var XML10_ATTRIBUTE='('+XML10_NAME+')'+XML_EQ+'('+XML10_ATT_VALUE+')';var XML11_VERSION_INFO=XML_S+'version'+XML_EQ+'("1\\.1"|'+"'1\\.1')";var XML11_NAME_START_CHAR=(REGEXP_UNICODE)?':A-Z_a-z\u00c0-\u00d6\u00d8-\u00f6\u00f8-\u02ff\u0370-\u037d'+'\u037f-\u1fff\u200c-\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff'+'\uf900-\ufdcf\ufdf0-\ufffd':':A-Z_a-z';var XML11_NAME_CHAR=XML11_NAME_START_CHAR+
((REGEXP_UNICODE)?'\\.0-9\u00b7\u0300-\u036f\u203f-\u2040-':'\\.0-9-');var XML11_NAME='['+XML11_NAME_START_CHAR+']['+XML11_NAME_CHAR+']*';var XML11_ENTITY_REF='&'+XML11_NAME+';';var XML11_REFERENCE=XML11_ENTITY_REF+'|'+XML_CHAR_REF;var XML11_ATT_VALUE='"(([^<&"]|'+XML11_REFERENCE+')*)"|'+"'(([^<&']|"+XML11_REFERENCE+")*)'";var XML11_ATTRIBUTE='('+XML11_NAME+')'+XML_EQ+'('+XML11_ATT_VALUE+')';var XML_NC_NAME_CHAR=XML10_LETTER+XML10_DIGIT+'\\._'+
XML10_COMBINING_CHAR+XML10_EXTENDER+'-';var XML_NC_NAME='['+XML10_LETTER+'_]['+XML_NC_NAME_CHAR+']*';function xmlResolveEntities(s){var parts=stringSplit(s,'&');var ret=parts[0];for(var i=1;i<parts.length;++i){var rp=parts[i].indexOf(';');if(rp==-1){ret+=parts[i];continue;}
var entityName=parts[i].substring(0,rp);var remainderText=parts[i].substring(rp+1);var ch;switch(entityName){case'lt':ch='<';break;case'gt':ch='>';break;case'amp':ch='&';break;case'quot':ch='"';break;case'apos':ch='\'';break;case'nbsp':ch=String.fromCharCode(160);break;default:var span=domCreateElement(window.document,'span');span.innerHTML='&'+entityName+'; ';ch=span.childNodes[0].nodeValue.charAt(0);}
ret+=ch+remainderText;}
return ret;}
var XML10_TAGNAME_REGEXP=new RegExp('^('+XML10_NAME+')');var XML10_ATTRIBUTE_REGEXP=new RegExp(XML10_ATTRIBUTE,'g');var XML11_TAGNAME_REGEXP=new RegExp('^('+XML11_NAME+')');var XML11_ATTRIBUTE_REGEXP=new RegExp(XML11_ATTRIBUTE,'g');function xmlParse(xml){var regex_empty=/\/$/;var regex_tagname;var regex_attribute;if(xml.match(/^<\?xml/)){if(xml.search(new RegExp(XML10_VERSION_INFO))==5){regex_tagname=XML10_TAGNAME_REGEXP;regex_attribute=XML10_ATTRIBUTE_REGEXP;}else if(xml.search(new RegExp(XML11_VERSION_INFO))==5){regex_tagname=XML11_TAGNAME_REGEXP;regex_attribute=XML11_ATTRIBUTE_REGEXP;}else{alert('VersionInfo is missing, or unknown version number.');}}else{regex_tagname=XML10_TAGNAME_REGEXP;regex_attribute=XML10_ATTRIBUTE_REGEXP;}
var xmldoc=new XDocument();var root=xmldoc;var stack=[];var parent=root;stack.push(parent);var slurp='';var x=stringSplit(xml,'<');for(var i=1;i<x.length;++i){var xx=stringSplit(x[i],'>');var tag=xx[0];var text=xmlResolveEntities(xx[1]||'');if(slurp){var end=x[i].indexOf(slurp);if(end!=-1){var data=x[i].substring(0,end);parent.nodeValue+='<'+data;stack.pop();parent=stack[stack.length-1];text=x[i].substring(end+slurp.length);slurp='';}else{parent.nodeValue+='<'+x[i];text=null;}}else if(tag.indexOf('![CDATA[')==0){var start='![CDATA['.length;var end=x[i].indexOf(']]>');if(end!=-1){var data=x[i].substring(start,end);var node=domCreateCDATASection(xmldoc,data);domAppendChild(parent,node);}else{var data=x[i].substring(start);text=null;var node=domCreateCDATASection(xmldoc,data);domAppendChild(parent,node);parent=node;stack.push(node);slurp=']]>';}}else if(tag.indexOf('!--')==0){var start='!--'.length;var end=x[i].indexOf('-->');if(end!=-1){var data=x[i].substring(start,end);var node=domCreateComment(xmldoc,data);domAppendChild(parent,node);}else{var data=x[i].substring(start);text=null;var node=domCreateComment(xmldoc,data);domAppendChild(parent,node);parent=node;stack.push(node);slurp='-->';}}else if(tag.charAt(0)=='/'){stack.pop();parent=stack[stack.length-1];}else if(tag.charAt(0)=='?'){}else if(tag.charAt(0)=='!'){}else{var empty=tag.match(regex_empty);var tagname=regex_tagname.exec(tag)[1];var node=domCreateElement(xmldoc,tagname);var att;while(att=regex_attribute.exec(tag)){var val=xmlResolveEntities(att[5]||att[7]||'');domSetAttribute(node,att[1],val);}
domAppendChild(parent,node);if(!empty){parent=node;stack.push(node);}}
if(text&&parent!=root){domAppendChild(parent,domCreateTextNode(xmldoc,text));}}
return root;}
var DOM_ELEMENT_NODE=1;var DOM_ATTRIBUTE_NODE=2;var DOM_TEXT_NODE=3;var DOM_CDATA_SECTION_NODE=4;var DOM_ENTITY_REFERENCE_NODE=5;var DOM_ENTITY_NODE=6;var DOM_PROCESSING_INSTRUCTION_NODE=7;var DOM_COMMENT_NODE=8;var DOM_DOCUMENT_NODE=9;var DOM_DOCUMENT_TYPE_NODE=10;var DOM_DOCUMENT_FRAGMENT_NODE=11;var DOM_NOTATION_NODE=12;function domTraverseElements(node,opt_pre,opt_post){var ret;if(opt_pre){ret=opt_pre.call(null,node);if(typeof ret=='boolean'&&!ret){return false;}}
for(var c=node.firstChild;c;c=c.nextSibling){if(c.nodeType==DOM_ELEMENT_NODE){ret=arguments.callee.call(this,c,opt_pre,opt_post);if(typeof ret=='boolean'&&!ret){return false;}}}
if(opt_post){ret=opt_post.call(null,node);if(typeof ret=='boolean'&&!ret){return false;}}}
function XNode(type,name,opt_value,opt_owner){this.attributes=[];this.childNodes=[];XNode.init.call(this,type,name,opt_value,opt_owner);}
XNode.init=function(type,name,value,owner){this.nodeType=type-0;this.nodeName=''+name;this.nodeValue=''+value;this.ownerDocument=owner;this.firstChild=null;this.lastChild=null;this.nextSibling=null;this.previousSibling=null;this.parentNode=null;}
XNode.unused_=[];XNode.recycle=function(node){if(!node){return;}
if(node.constructor==XDocument){XNode.recycle(node.documentElement);return;}
if(node.constructor!=this){return;}
XNode.unused_.push(node);for(var a=0;a<node.attributes.length;++a){XNode.recycle(node.attributes[a]);}
for(var c=0;c<node.childNodes.length;++c){XNode.recycle(node.childNodes[c]);}
node.attributes.length=0;node.childNodes.length=0;XNode.init.call(node,0,'','',null);}
XNode.create=function(type,name,value,owner){if(XNode.unused_.length>0){var node=XNode.unused_.pop();XNode.init.call(node,type,name,value,owner);return node;}else{return new XNode(type,name,value,owner);}}
XNode.prototype.appendChild=function(node){if(this.childNodes.length==0){this.firstChild=node;}
node.previousSibling=this.lastChild;node.nextSibling=null;if(this.lastChild){this.lastChild.nextSibling=node;}
node.parentNode=this;this.lastChild=node;this.childNodes.push(node);}
XNode.prototype.replaceChild=function(newNode,oldNode){if(oldNode==newNode){return;}
for(var i=0;i<this.childNodes.length;++i){if(this.childNodes[i]==oldNode){this.childNodes[i]=newNode;var p=oldNode.parentNode;oldNode.parentNode=null;newNode.parentNode=p;p=oldNode.previousSibling;oldNode.previousSibling=null;newNode.previousSibling=p;if(newNode.previousSibling){newNode.previousSibling.nextSibling=newNode;}
p=oldNode.nextSibling;oldNode.nextSibling=null;newNode.nextSibling=p;if(newNode.nextSibling){newNode.nextSibling.previousSibling=newNode;}
if(this.firstChild==oldNode){this.firstChild=newNode;}
if(this.lastChild==oldNode){this.lastChild=newNode;}
break;}}}
XNode.prototype.insertBefore=function(newNode,oldNode){if(oldNode==newNode){return;}
if(oldNode.parentNode!=this){return;}
if(newNode.parentNode){newNode.parentNode.removeChild(newNode);}
var newChildren=[];for(var i=0;i<this.childNodes.length;++i){var c=this.childNodes[i];if(c==oldNode){newChildren.push(newNode);newNode.parentNode=this;newNode.previousSibling=oldNode.previousSibling;oldNode.previousSibling=newNode;if(newNode.previousSibling){newNode.previousSibling.nextSibling=newNode;}
newNode.nextSibling=oldNode;if(this.firstChild==oldNode){this.firstChild=newNode;}}
newChildren.push(c);}
this.childNodes=newChildren;}
XNode.prototype.removeChild=function(node){var newChildren=[];for(var i=0;i<this.childNodes.length;++i){var c=this.childNodes[i];if(c!=node){newChildren.push(c);}else{if(c.previousSibling){c.previousSibling.nextSibling=c.nextSibling;}
if(c.nextSibling){c.nextSibling.previousSibling=c.previousSibling;}
if(this.firstChild==c){this.firstChild=c.nextSibling;}
if(this.lastChild==c){this.lastChild=c.previousSibling;}}}
this.childNodes=newChildren;}
XNode.prototype.hasAttributes=function(){return this.attributes.length>0;}
XNode.prototype.setAttribute=function(name,value){for(var i=0;i<this.attributes.length;++i){if(this.attributes[i].nodeName==name){this.attributes[i].nodeValue=''+value;return;}}
this.attributes.push(XNode.create(DOM_ATTRIBUTE_NODE,name,value,this));}
XNode.prototype.getAttribute=function(name){for(var i=0;i<this.attributes.length;++i){if(this.attributes[i].nodeName==name){return this.attributes[i].nodeValue;}}
return null;}
XNode.prototype.removeAttribute=function(name){var a=[];for(var i=0;i<this.attributes.length;++i){if(this.attributes[i].nodeName!=name){a.push(this.attributes[i]);}}
this.attributes=a;}
XNode.prototype.getElementsByTagName=function(name){var ret=[];var self=this;if("*"==name){domTraverseElements(this,function(node){if(self==node)return;ret.push(node);},null);}else{domTraverseElements(this,function(node){if(self==node)return;if(node.nodeName==name){ret.push(node);}},null);}
return ret;}
XNode.prototype.getElementById=function(id){var ret=null;domTraverseElements(this,function(node){if(node.getAttribute('id')==id){ret=node;return false;}},null);return ret;}
function XDocument(){XNode.call(this,DOM_DOCUMENT_NODE,'#document',null,null);this.documentElement=null;}
XDocument.prototype=new XNode(DOM_DOCUMENT_NODE,'#document');XDocument.prototype.clear=function(){XNode.recycle(this.documentElement);this.documentElement=null;}
XDocument.prototype.appendChild=function(node){XNode.prototype.appendChild.call(this,node);this.documentElement=this.childNodes[0];}
XDocument.prototype.createElement=function(name){return XNode.create(DOM_ELEMENT_NODE,name,null,this);}
XDocument.prototype.createDocumentFragment=function(){return XNode.create(DOM_DOCUMENT_FRAGMENT_NODE,'#document-fragment',null,this);}
XDocument.prototype.createTextNode=function(value){return XNode.create(DOM_TEXT_NODE,'#text',value,this);}
XDocument.prototype.createAttribute=function(name){return XNode.create(DOM_ATTRIBUTE_NODE,name,null,this);}
XDocument.prototype.createComment=function(data){return XNode.create(DOM_COMMENT_NODE,'#comment',data,this);}
XDocument.prototype.createCDATASection=function(data){return XNode.create(DOM_CDATA_SECTION_NODE,'#cdata-section',data,this);}
function xpathParse(expr){xpathLog('parse '+expr);xpathParseInit();var cached=xpathCacheLookup(expr);if(cached){xpathLog(' ... cached');return cached;}
if(expr.match(/^(\$|@)?\w+$/i)){var ret=makeSimpleExpr(expr);xpathParseCache[expr]=ret;xpathLog(' ... simple');return ret;}
if(expr.match(/^\w+(\/\w+)*$/i)){var ret=makeSimpleExpr2(expr);xpathParseCache[expr]=ret;xpathLog(' ... simple 2');return ret;}
var cachekey=expr;var stack=[];var ahead=null;var previous=null;var done=false;var parse_count=0;var lexer_count=0;var reduce_count=0;while(!done){parse_count++;expr=expr.replace(/^\s*/,'');previous=ahead;ahead=null;var rule=null;var match='';for(var i=0;i<xpathTokenRules.length;++i){var result=xpathTokenRules[i].re.exec(expr);lexer_count++;if(result&&result.length>0&&result[0].length>match.length){rule=xpathTokenRules[i];match=result[0];break;}}
if(rule&&(rule==TOK_DIV||rule==TOK_MOD||rule==TOK_AND||rule==TOK_OR)&&(!previous||previous.tag==TOK_AT||previous.tag==TOK_DSLASH||previous.tag==TOK_SLASH||previous.tag==TOK_AXIS||previous.tag==TOK_DOLLAR)){rule=TOK_QNAME;}
if(rule){expr=expr.substr(match.length);xpathLog('token: '+match+' -- '+rule.label);ahead={tag:rule,match:match,prec:rule.prec?rule.prec:0,expr:makeTokenExpr(match)};}else{xpathLog('DONE');done=true;}
while(xpathReduce(stack,ahead)){reduce_count++;xpathLog('stack: '+stackToString(stack));}}
xpathLog('stack: '+stackToString(stack));if(stack.length!=1){throw'XPath parse error '+cachekey+':\n'+stackToString(stack);}
var result=stack[0].expr;xpathParseCache[cachekey]=result;xpathLog('XPath parse: '+parse_count+' / '+
lexer_count+' / '+reduce_count);return result;}
var xpathParseCache={};function xpathCacheLookup(expr){return xpathParseCache[expr];}
function xpathReduce(stack,ahead){var cand=null;if(stack.length>0){var top=stack[stack.length-1];var ruleset=xpathRules[top.tag.key];if(ruleset){for(var i=0;i<ruleset.length;++i){var rule=ruleset[i];var match=xpathMatchStack(stack,rule[1]);if(match.length){cand={tag:rule[0],rule:rule,match:match};cand.prec=xpathGrammarPrecedence(cand);break;}}}}
var ret;if(cand&&(!ahead||cand.prec>ahead.prec||(ahead.tag.left&&cand.prec>=ahead.prec))){for(var i=0;i<cand.match.matchlength;++i){stack.pop();}
xpathLog('reduce '+cand.tag.label+' '+cand.prec+' ahead '+(ahead?ahead.tag.label+' '+ahead.prec+
(ahead.tag.left?' left':''):' none '));var matchexpr=mapExpr(cand.match,function(m){return m.expr;});xpathLog('going to apply '+cand.rule[3].toString());cand.expr=cand.rule[3].apply(null,matchexpr);stack.push(cand);ret=true;}else{if(ahead){xpathLog('shift '+ahead.tag.label+' '+ahead.prec+
(ahead.tag.left?' left':'')+' over '+(cand?cand.tag.label+' '+
cand.prec:' none'));stack.push(ahead);}
ret=false;}
return ret;}
function xpathMatchStack(stack,pattern){var S=stack.length;var P=pattern.length;var p,s;var match=[];match.matchlength=0;var ds=0;for(p=P-1,s=S-1;p>=0&&s>=0;--p,s-=ds){ds=0;var qmatch=[];if(pattern[p]==Q_MM){p-=1;match.push(qmatch);while(s-ds>=0&&stack[s-ds].tag==pattern[p]){qmatch.push(stack[s-ds]);ds+=1;match.matchlength+=1;}}else if(pattern[p]==Q_01){p-=1;match.push(qmatch);while(s-ds>=0&&ds<2&&stack[s-ds].tag==pattern[p]){qmatch.push(stack[s-ds]);ds+=1;match.matchlength+=1;}}else if(pattern[p]==Q_1M){p-=1;match.push(qmatch);if(stack[s].tag==pattern[p]){while(s-ds>=0&&stack[s-ds].tag==pattern[p]){qmatch.push(stack[s-ds]);ds+=1;match.matchlength+=1;}}else{return[];}}else if(stack[s].tag==pattern[p]){match.push(stack[s]);ds+=1;match.matchlength+=1;}else{return[];}
reverseInplace(qmatch);qmatch.expr=mapExpr(qmatch,function(m){return m.expr;});}
reverseInplace(match);if(p==-1){return match;}else{return[];}}
function xpathTokenPrecedence(tag){return tag.prec||2;}
function xpathGrammarPrecedence(frame){var ret=0;if(frame.rule){if(frame.rule.length>=3&&frame.rule[2]>=0){ret=frame.rule[2];}else{for(var i=0;i<frame.rule[1].length;++i){var p=xpathTokenPrecedence(frame.rule[1][i]);ret=Math.max(ret,p);}}}else if(frame.tag){ret=xpathTokenPrecedence(frame.tag);}else if(frame.length){for(var j=0;j<frame.length;++j){var p=xpathGrammarPrecedence(frame[j]);ret=Math.max(ret,p);}}
return ret;}
function stackToString(stack){var ret='';for(var i=0;i<stack.length;++i){if(ret){ret+='\n';}
ret+=stack[i].tag.label;}
return ret;}
function ExprContext(node,opt_position,opt_nodelist,opt_parent,opt_caseInsensitive,opt_ignoreAttributesWithoutValue){this.node=node;this.position=opt_position||0;this.nodelist=opt_nodelist||[node];this.variables={};this.parent=opt_parent||null;this.caseInsensitive=opt_caseInsensitive||false;this.ignoreAttributesWithoutValue=opt_ignoreAttributesWithoutValue||false;if(opt_parent){this.root=opt_parent.root;}else if(this.node.nodeType==DOM_DOCUMENT_NODE){this.root=node;}else{this.root=node.ownerDocument;}}
ExprContext.prototype.clone=function(opt_node,opt_position,opt_nodelist){return new ExprContext(opt_node||this.node,typeof opt_position!='undefined'?opt_position:this.position,opt_nodelist||this.nodelist,this,this.caseInsensitive,this.ignoreAttributesWithoutValue);};ExprContext.prototype.setVariable=function(name,value){if(value instanceof StringValue||value instanceof BooleanValue||value instanceof NumberValue||value instanceof NodeSetValue){this.variables[name]=value;return;}
if('true'===value){this.variables[name]=new BooleanValue(true);}else if('false'===value){this.variables[name]=new BooleanValue(false);}else if(TOK_NUMBER.re.test(value)){this.variables[name]=new NumberValue(value);}else{this.variables[name]=new StringValue(value);}};ExprContext.prototype.getVariable=function(name){if(typeof this.variables[name]!='undefined'){return this.variables[name];}else if(this.parent){return this.parent.getVariable(name);}else{return null;}};ExprContext.prototype.setNode=function(position){this.node=this.nodelist[position];this.position=position;};ExprContext.prototype.contextSize=function(){return this.nodelist.length;};ExprContext.prototype.isCaseInsensitive=function(){return this.caseInsensitive;};ExprContext.prototype.setCaseInsensitive=function(caseInsensitive){return this.caseInsensitive=caseInsensitive;};ExprContext.prototype.isIgnoreAttributesWithoutValue=function(){return this.ignoreAttributesWithoutValue;};ExprContext.prototype.setIgnoreAttributesWithoutValue=function(ignore){return this.ignoreAttributesWithoutValue=ignore;};function StringValue(value){this.value=value;this.type='string';}
StringValue.prototype.stringValue=function(){return this.value;}
StringValue.prototype.booleanValue=function(){return this.value.length>0;}
StringValue.prototype.numberValue=function(){return this.value-0;}
StringValue.prototype.nodeSetValue=function(){throw this;}
function BooleanValue(value){this.value=value;this.type='boolean';}
BooleanValue.prototype.stringValue=function(){return''+this.value;}
BooleanValue.prototype.booleanValue=function(){return this.value;}
BooleanValue.prototype.numberValue=function(){return this.value?1:0;}
BooleanValue.prototype.nodeSetValue=function(){throw this;}
function NumberValue(value){this.value=value;this.type='number';}
NumberValue.prototype.stringValue=function(){return''+this.value;}
NumberValue.prototype.booleanValue=function(){return!!this.value;}
NumberValue.prototype.numberValue=function(){return this.value-0;}
NumberValue.prototype.nodeSetValue=function(){throw this;}
function NodeSetValue(value){this.value=value;this.type='node-set';}
NodeSetValue.prototype.stringValue=function(){if(this.value.length==0){return'';}else{return xmlValue(this.value[0]);}}
NodeSetValue.prototype.booleanValue=function(){return this.value.length>0;}
NodeSetValue.prototype.numberValue=function(){return this.stringValue()-0;}
NodeSetValue.prototype.nodeSetValue=function(){return this.value;};function TokenExpr(m){this.value=m;}
TokenExpr.prototype.evaluate=function(){return new StringValue(this.value);};function LocationExpr(){this.absolute=false;this.steps=[];}
LocationExpr.prototype.appendStep=function(s){var combinedStep=this._combineSteps(this.steps[this.steps.length-1],s);if(combinedStep){this.steps[this.steps.length-1]=combinedStep;}else{this.steps.push(s);}}
LocationExpr.prototype.prependStep=function(s){var combinedStep=this._combineSteps(s,this.steps[0]);if(combinedStep){this.steps[0]=combinedStep;}else{this.steps.unshift(s);}};LocationExpr.prototype._combineSteps=function(prevStep,nextStep){if(!prevStep)return null;if(!nextStep)return null;var hasPredicates=(prevStep.predicates&&prevStep.predicates.length>0);if(prevStep.nodetest instanceof NodeTestAny&&!hasPredicates){if(prevStep.axis==xpathAxis.DESCENDANT_OR_SELF){if(nextStep.axis==xpathAxis.CHILD){nextStep.axis=xpathAxis.DESCENDANT;return nextStep;}else if(nextStep.axis==xpathAxis.SELF){nextStep.axis=xpathAxis.DESCENDANT_OR_SELF;return nextStep;}}else if(prevStep.axis==xpathAxis.DESCENDANT){if(nextStep.axis==xpathAxis.SELF){nextStep.axis=xpathAxis.DESCENDANT;return nextStep;}}}
return null;}
LocationExpr.prototype.evaluate=function(ctx){var start;if(this.absolute){start=ctx.root;}else{start=ctx.node;}
var nodes=[];xPathStep(nodes,this.steps,0,start,ctx);return new NodeSetValue(nodes);};function xPathStep(nodes,steps,step,input,ctx){var s=steps[step];var ctx2=ctx.clone(input);var nodelist=s.evaluate(ctx2).nodeSetValue();for(var i=0;i<nodelist.length;++i){if(step==steps.length-1){nodes.push(nodelist[i]);}else{xPathStep(nodes,steps,step+1,nodelist[i],ctx);}}}
function StepExpr(axis,nodetest,opt_predicate){this.axis=axis;this.nodetest=nodetest;this.predicate=opt_predicate||[];}
StepExpr.prototype.appendPredicate=function(p){this.predicate.push(p);}
StepExpr.prototype.evaluate=function(ctx){var input=ctx.node;var nodelist=[];var skipNodeTest=false;if(this.nodetest instanceof NodeTestAny){skipNodeTest=true;}
if(this.axis==xpathAxis.ANCESTOR_OR_SELF){nodelist.push(input);for(var n=input.parentNode;n;n=n.parentNode){nodelist.push(n);}}else if(this.axis==xpathAxis.ANCESTOR){for(var n=input.parentNode;n;n=n.parentNode){nodelist.push(n);}}else if(this.axis==xpathAxis.ATTRIBUTE){if(ctx.ignoreAttributesWithoutValue){copyArrayIgnoringAttributesWithoutValue(nodelist,input.attributes);}
else{copyArray(nodelist,input.attributes);}}else if(this.axis==xpathAxis.CHILD){copyArray(nodelist,input.childNodes);}else if(this.axis==xpathAxis.DESCENDANT_OR_SELF){if(this.nodetest.evaluate(ctx).booleanValue()){nodelist.push(input);}
var tagName=xpathExtractTagNameFromNodeTest(this.nodetest);xpathCollectDescendants(nodelist,input,tagName);if(tagName)skipNodeTest=true;}else if(this.axis==xpathAxis.DESCENDANT){var tagName=xpathExtractTagNameFromNodeTest(this.nodetest);xpathCollectDescendants(nodelist,input,tagName);if(tagName)skipNodeTest=true;}else if(this.axis==xpathAxis.FOLLOWING){for(var n=input;n;n=n.parentNode){for(var nn=n.nextSibling;nn;nn=nn.nextSibling){nodelist.push(nn);xpathCollectDescendants(nodelist,nn);}}}else if(this.axis==xpathAxis.FOLLOWING_SIBLING){for(var n=input.nextSibling;n;n=n.nextSibling){nodelist.push(n);}}else if(this.axis==xpathAxis.NAMESPACE){alert('not implemented: axis namespace');}else if(this.axis==xpathAxis.PARENT){if(input.parentNode){nodelist.push(input.parentNode);}}else if(this.axis==xpathAxis.PRECEDING){for(var n=input;n;n=n.parentNode){for(var nn=n.previousSibling;nn;nn=nn.previousSibling){nodelist.push(nn);xpathCollectDescendantsReverse(nodelist,nn);}}}else if(this.axis==xpathAxis.PRECEDING_SIBLING){for(var n=input.previousSibling;n;n=n.previousSibling){nodelist.push(n);}}else if(this.axis==xpathAxis.SELF){nodelist.push(input);}else{throw'ERROR -- NO SUCH AXIS: '+this.axis;}
if(!skipNodeTest){var nodelist0=nodelist;nodelist=[];for(var i=0;i<nodelist0.length;++i){var n=nodelist0[i];if(this.nodetest.evaluate(ctx.clone(n,i,nodelist0)).booleanValue()){nodelist.push(n);}}}
for(var i=0;i<this.predicate.length;++i){var nodelist0=nodelist;nodelist=[];for(var ii=0;ii<nodelist0.length;++ii){var n=nodelist0[ii];if(this.predicate[i].evaluate(ctx.clone(n,ii,nodelist0)).booleanValue()){nodelist.push(n);}}}
return new NodeSetValue(nodelist);};function NodeTestAny(){this.value=new BooleanValue(true);}
NodeTestAny.prototype.evaluate=function(ctx){return this.value;};function NodeTestElementOrAttribute(){}
NodeTestElementOrAttribute.prototype.evaluate=function(ctx){return new BooleanValue(ctx.node.nodeType==DOM_ELEMENT_NODE||ctx.node.nodeType==DOM_ATTRIBUTE_NODE);}
function NodeTestText(){}
NodeTestText.prototype.evaluate=function(ctx){return new BooleanValue(ctx.node.nodeType==DOM_TEXT_NODE);}
function NodeTestComment(){}
NodeTestComment.prototype.evaluate=function(ctx){return new BooleanValue(ctx.node.nodeType==DOM_COMMENT_NODE);}
function NodeTestPI(target){this.target=target;}
NodeTestPI.prototype.evaluate=function(ctx){return new
BooleanValue(ctx.node.nodeType==DOM_PROCESSING_INSTRUCTION_NODE&&(!this.target||ctx.node.nodeName==this.target));}
function NodeTestNC(nsprefix){this.regex=new RegExp("^"+nsprefix+":");this.nsprefix=nsprefix;}
NodeTestNC.prototype.evaluate=function(ctx){var n=ctx.node;return new BooleanValue(this.regex.match(n.nodeName));}
function NodeTestName(name){this.name=name;this.re=new RegExp('^'+name+'$',"i");}
NodeTestName.prototype.evaluate=function(ctx){var n=ctx.node;if(ctx.caseInsensitive){if(n.nodeName.length!=this.name.length)return new BooleanValue(false);return new BooleanValue(this.re.test(n.nodeName));}else{return new BooleanValue(n.nodeName==this.name);}}
function PredicateExpr(expr){this.expr=expr;}
PredicateExpr.prototype.evaluate=function(ctx){var v=this.expr.evaluate(ctx);if(v.type=='number'){return new BooleanValue(ctx.position==v.numberValue()-1);}else{return new BooleanValue(v.booleanValue());}};function FunctionCallExpr(name){this.name=name;this.args=[];}
FunctionCallExpr.prototype.appendArg=function(arg){this.args.push(arg);};FunctionCallExpr.prototype.evaluate=function(ctx){var fn=''+this.name.value;var f=this.xpathfunctions[fn];if(f){return f.call(this,ctx);}else{xpathLog('XPath NO SUCH FUNCTION '+fn);return new BooleanValue(false);}};FunctionCallExpr.prototype.xpathfunctions={'last':function(ctx){assert(this.args.length==0);return new NumberValue(ctx.contextSize());},'position':function(ctx){assert(this.args.length==0);return new NumberValue(ctx.position+1);},'count':function(ctx){assert(this.args.length==1);var v=this.args[0].evaluate(ctx);return new NumberValue(v.nodeSetValue().length);},'id':function(ctx){assert(this.args.length==1);var e=this.args[0].evaluate(ctx);var ret=[];var ids;if(e.type=='node-set'){ids=[];var en=e.nodeSetValue();for(var i=0;i<en.length;++i){var v=xmlValue(en[i]).split(/\s+/);for(var ii=0;ii<v.length;++ii){ids.push(v[ii]);}}}else{ids=e.stringValue().split(/\s+/);}
var d=ctx.root;for(var i=0;i<ids.length;++i){var n=d.getElementById(ids[i]);if(n){ret.push(n);}}
return new NodeSetValue(ret);},'local-name':function(ctx){alert('not implmented yet: XPath function local-name()');},'namespace-uri':function(ctx){alert('not implmented yet: XPath function namespace-uri()');},'name':function(ctx){assert(this.args.length==1||this.args.length==0);var n;if(this.args.length==0){n=[ctx.node];}else{n=this.args[0].evaluate(ctx).nodeSetValue();}
if(n.length==0){return new StringValue('');}else{return new StringValue(n[0].nodeName);}},'string':function(ctx){assert(this.args.length==1||this.args.length==0);if(this.args.length==0){return new StringValue(new NodeSetValue([ctx.node]).stringValue());}else{return new StringValue(this.args[0].evaluate(ctx).stringValue());}},'concat':function(ctx){var ret='';for(var i=0;i<this.args.length;++i){ret+=this.args[i].evaluate(ctx).stringValue();}
return new StringValue(ret);},'starts-with':function(ctx){assert(this.args.length==2);var s0=this.args[0].evaluate(ctx).stringValue();var s1=this.args[1].evaluate(ctx).stringValue();return new BooleanValue(s0.indexOf(s1)==0);},'contains':function(ctx){assert(this.args.length==2);var s0=this.args[0].evaluate(ctx).stringValue();var s1=this.args[1].evaluate(ctx).stringValue();return new BooleanValue(s0.indexOf(s1)!=-1);},'substring-before':function(ctx){assert(this.args.length==2);var s0=this.args[0].evaluate(ctx).stringValue();var s1=this.args[1].evaluate(ctx).stringValue();var i=s0.indexOf(s1);var ret;if(i==-1){ret='';}else{ret=s0.substr(0,i);}
return new StringValue(ret);},'substring-after':function(ctx){assert(this.args.length==2);var s0=this.args[0].evaluate(ctx).stringValue();var s1=this.args[1].evaluate(ctx).stringValue();var i=s0.indexOf(s1);var ret;if(i==-1){ret='';}else{ret=s0.substr(i+s1.length);}
return new StringValue(ret);},'substring':function(ctx){assert(this.args.length==2||this.args.length==3);var s0=this.args[0].evaluate(ctx).stringValue();var s1=this.args[1].evaluate(ctx).numberValue();var ret;if(this.args.length==2){var i1=Math.max(0,Math.round(s1)-1);ret=s0.substr(i1);}else{var s2=this.args[2].evaluate(ctx).numberValue();var i0=Math.round(s1)-1;var i1=Math.max(0,i0);var i2=Math.round(s2)-Math.max(0,-i0);ret=s0.substr(i1,i2);}
return new StringValue(ret);},'string-length':function(ctx){var s;if(this.args.length>0){s=this.args[0].evaluate(ctx).stringValue();}else{s=new NodeSetValue([ctx.node]).stringValue();}
return new NumberValue(s.length);},'normalize-space':function(ctx){var s;if(this.args.length>0){s=this.args[0].evaluate(ctx).stringValue();}else{s=new NodeSetValue([ctx.node]).stringValue();}
s=s.replace(/^\s*/,'').replace(/\s*$/,'').replace(/\s+/g,' ');return new StringValue(s);},'translate':function(ctx){assert(this.args.length==3);var s0=this.args[0].evaluate(ctx).stringValue();var s1=this.args[1].evaluate(ctx).stringValue();var s2=this.args[2].evaluate(ctx).stringValue();for(var i=0;i<s1.length;++i){s0=s0.replace(new RegExp(s1.charAt(i),'g'),s2.charAt(i));}
return new StringValue(s0);},'boolean':function(ctx){assert(this.args.length==1);return new BooleanValue(this.args[0].evaluate(ctx).booleanValue());},'not':function(ctx){assert(this.args.length==1);var ret=!this.args[0].evaluate(ctx).booleanValue();return new BooleanValue(ret);},'true':function(ctx){assert(this.args.length==0);return new BooleanValue(true);},'false':function(ctx){assert(this.args.length==0);return new BooleanValue(false);},'lang':function(ctx){assert(this.args.length==1);var lang=this.args[0].evaluate(ctx).stringValue();var xmllang;var n=ctx.node;while(n&&n!=n.parentNode){xmllang=n.getAttribute('xml:lang');if(xmllang){break;}
n=n.parentNode;}
if(!xmllang){return new BooleanValue(false);}else{var re=new RegExp('^'+lang+'$','i');return new BooleanValue(xmllang.match(re)||xmllang.replace(/_.*$/,'').match(re));}},'number':function(ctx){assert(this.args.length==1||this.args.length==0);if(this.args.length==1){return new NumberValue(this.args[0].evaluate(ctx).numberValue());}else{return new NumberValue(new NodeSetValue([ctx.node]).numberValue());}},'sum':function(ctx){assert(this.args.length==1);var n=this.args[0].evaluate(ctx).nodeSetValue();var sum=0;for(var i=0;i<n.length;++i){sum+=xmlValue(n[i])-0;}
return new NumberValue(sum);},'floor':function(ctx){assert(this.args.length==1);var num=this.args[0].evaluate(ctx).numberValue();return new NumberValue(Math.floor(num));},'ceiling':function(ctx){assert(this.args.length==1);var num=this.args[0].evaluate(ctx).numberValue();return new NumberValue(Math.ceil(num));},'round':function(ctx){assert(this.args.length==1);var num=this.args[0].evaluate(ctx).numberValue();return new NumberValue(Math.round(num));},'ext-join':function(ctx){assert(this.args.length==2);var nodes=this.args[0].evaluate(ctx).nodeSetValue();var delim=this.args[1].evaluate(ctx).stringValue();var ret='';for(var i=0;i<nodes.length;++i){if(ret){ret+=delim;}
ret+=xmlValue(nodes[i]);}
return new StringValue(ret);},'ext-if':function(ctx){assert(this.args.length==3);if(this.args[0].evaluate(ctx).booleanValue()){return this.args[1].evaluate(ctx);}else{return this.args[2].evaluate(ctx);}},'ext-cardinal':function(ctx){assert(this.args.length>=1);var c=this.args[0].evaluate(ctx).numberValue();var ret=[];for(var i=0;i<c;++i){ret.push(ctx.node);}
return new NodeSetValue(ret);}};function UnionExpr(expr1,expr2){this.expr1=expr1;this.expr2=expr2;}
UnionExpr.prototype.evaluate=function(ctx){var nodes1=this.expr1.evaluate(ctx).nodeSetValue();var nodes2=this.expr2.evaluate(ctx).nodeSetValue();var I1=nodes1.length;for(var i2=0;i2<nodes2.length;++i2){var n=nodes2[i2];var inBoth=false;for(var i1=0;i1<I1;++i1){if(nodes1[i1]==n){inBoth=true;i1=I1;}}
if(!inBoth){nodes1.push(n);}}
return new NodeSetValue(nodes1);};function PathExpr(filter,rel){this.filter=filter;this.rel=rel;}
PathExpr.prototype.evaluate=function(ctx){var nodes=this.filter.evaluate(ctx).nodeSetValue();var nodes1=[];for(var i=0;i<nodes.length;++i){var nodes0=this.rel.evaluate(ctx.clone(nodes[i],i,nodes)).nodeSetValue();for(var ii=0;ii<nodes0.length;++ii){nodes1.push(nodes0[ii]);}}
return new NodeSetValue(nodes1);};function FilterExpr(expr,predicate){this.expr=expr;this.predicate=predicate;}
FilterExpr.prototype.evaluate=function(ctx){var nodes=this.expr.evaluate(ctx).nodeSetValue();for(var i=0;i<this.predicate.length;++i){var nodes0=nodes;nodes=[];for(var j=0;j<nodes0.length;++j){var n=nodes0[j];if(this.predicate[i].evaluate(ctx.clone(n,j,nodes0)).booleanValue()){nodes.push(n);}}}
return new NodeSetValue(nodes);}
function UnaryMinusExpr(expr){this.expr=expr;}
UnaryMinusExpr.prototype.evaluate=function(ctx){return new NumberValue(-this.expr.evaluate(ctx).numberValue());};function BinaryExpr(expr1,op,expr2){this.expr1=expr1;this.expr2=expr2;this.op=op;}
BinaryExpr.prototype.evaluate=function(ctx){var ret;switch(this.op.value){case'or':ret=new BooleanValue(this.expr1.evaluate(ctx).booleanValue()||this.expr2.evaluate(ctx).booleanValue());break;case'and':ret=new BooleanValue(this.expr1.evaluate(ctx).booleanValue()&&this.expr2.evaluate(ctx).booleanValue());break;case'+':ret=new NumberValue(this.expr1.evaluate(ctx).numberValue()+
this.expr2.evaluate(ctx).numberValue());break;case'-':ret=new NumberValue(this.expr1.evaluate(ctx).numberValue()-
this.expr2.evaluate(ctx).numberValue());break;case'*':ret=new NumberValue(this.expr1.evaluate(ctx).numberValue()*this.expr2.evaluate(ctx).numberValue());break;case'mod':ret=new NumberValue(this.expr1.evaluate(ctx).numberValue()%this.expr2.evaluate(ctx).numberValue());break;case'div':ret=new NumberValue(this.expr1.evaluate(ctx).numberValue()/this.expr2.evaluate(ctx).numberValue());break;case'=':ret=this.compare(ctx,function(x1,x2){return x1==x2;});break;case'!=':ret=this.compare(ctx,function(x1,x2){return x1!=x2;});break;case'<':ret=this.compare(ctx,function(x1,x2){return x1<x2;});break;case'<=':ret=this.compare(ctx,function(x1,x2){return x1<=x2;});break;case'>':ret=this.compare(ctx,function(x1,x2){return x1>x2;});break;case'>=':ret=this.compare(ctx,function(x1,x2){return x1>=x2;});break;default:alert('BinaryExpr.evaluate: '+this.op.value);}
return ret;};BinaryExpr.prototype.compare=function(ctx,cmp){var v1=this.expr1.evaluate(ctx);var v2=this.expr2.evaluate(ctx);var ret;if(v1.type=='node-set'&&v2.type=='node-set'){var n1=v1.nodeSetValue();var n2=v2.nodeSetValue();ret=false;for(var i1=0;i1<n1.length;++i1){for(var i2=0;i2<n2.length;++i2){if(cmp(xmlValue(n1[i1]),xmlValue(n2[i2]))){ret=true;i2=n2.length;i1=n1.length;}}}}else if(v1.type=='node-set'||v2.type=='node-set'){if(v1.type=='number'){var s=v1.numberValue();var n=v2.nodeSetValue();ret=false;for(var i=0;i<n.length;++i){var nn=xmlValue(n[i])-0;if(cmp(s,nn)){ret=true;break;}}}else if(v2.type=='number'){var n=v1.nodeSetValue();var s=v2.numberValue();ret=false;for(var i=0;i<n.length;++i){var nn=xmlValue(n[i])-0;if(cmp(nn,s)){ret=true;break;}}}else if(v1.type=='string'){var s=v1.stringValue();var n=v2.nodeSetValue();ret=false;for(var i=0;i<n.length;++i){var nn=xmlValue(n[i]);if(cmp(s,nn)){ret=true;break;}}}else if(v2.type=='string'){var n=v1.nodeSetValue();var s=v2.stringValue();ret=false;for(var i=0;i<n.length;++i){var nn=xmlValue(n[i]);if(cmp(nn,s)){ret=true;break;}}}else{ret=cmp(v1.booleanValue(),v2.booleanValue());}}else if(v1.type=='boolean'||v2.type=='boolean'){ret=cmp(v1.booleanValue(),v2.booleanValue());}else if(v1.type=='number'||v2.type=='number'){ret=cmp(v1.numberValue(),v2.numberValue());}else{ret=cmp(v1.stringValue(),v2.stringValue());}
return new BooleanValue(ret);}
function LiteralExpr(value){this.value=value;}
LiteralExpr.prototype.evaluate=function(ctx){return new StringValue(this.value);};function NumberExpr(value){this.value=value;}
NumberExpr.prototype.evaluate=function(ctx){return new NumberValue(this.value);};function VariableExpr(name){this.name=name;}
VariableExpr.prototype.evaluate=function(ctx){return ctx.getVariable(this.name);}
function makeTokenExpr(m){return new TokenExpr(m);}
function passExpr(e){return e;}
function makeLocationExpr1(slash,rel){rel.absolute=true;return rel;}
function makeLocationExpr2(dslash,rel){rel.absolute=true;rel.prependStep(makeAbbrevStep(dslash.value));return rel;}
function makeLocationExpr3(slash){var ret=new LocationExpr();ret.appendStep(makeAbbrevStep('.'));ret.absolute=true;return ret;}
function makeLocationExpr4(dslash){var ret=new LocationExpr();ret.absolute=true;ret.appendStep(makeAbbrevStep(dslash.value));return ret;}
function makeLocationExpr5(step){var ret=new LocationExpr();ret.appendStep(step);return ret;}
function makeLocationExpr6(rel,slash,step){rel.appendStep(step);return rel;}
function makeLocationExpr7(rel,dslash,step){rel.appendStep(makeAbbrevStep(dslash.value));rel.appendStep(step);return rel;}
function makeStepExpr1(dot){return makeAbbrevStep(dot.value);}
function makeStepExpr2(ddot){return makeAbbrevStep(ddot.value);}
function makeStepExpr3(axisname,axis,nodetest){return new StepExpr(axisname.value,nodetest);}
function makeStepExpr4(at,nodetest){return new StepExpr('attribute',nodetest);}
function makeStepExpr5(nodetest){return new StepExpr('child',nodetest);}
function makeStepExpr6(step,predicate){step.appendPredicate(predicate);return step;}
function makeAbbrevStep(abbrev){switch(abbrev){case'//':return new StepExpr('descendant-or-self',new NodeTestAny);case'.':return new StepExpr('self',new NodeTestAny);case'..':return new StepExpr('parent',new NodeTestAny);}}
function makeNodeTestExpr1(asterisk){return new NodeTestElementOrAttribute;}
function makeNodeTestExpr2(ncname,colon,asterisk){return new NodeTestNC(ncname.value);}
function makeNodeTestExpr3(qname){return new NodeTestName(qname.value);}
function makeNodeTestExpr4(typeo,parenc){var type=typeo.value.replace(/\s*\($/,'');switch(type){case'node':return new NodeTestAny;case'text':return new NodeTestText;case'comment':return new NodeTestComment;case'processing-instruction':return new NodeTestPI('');}}
function makeNodeTestExpr5(typeo,target,parenc){var type=typeo.replace(/\s*\($/,'');if(type!='processing-instruction'){throw type;}
return new NodeTestPI(target.value);}
function makePredicateExpr(pareno,expr,parenc){return new PredicateExpr(expr);}
function makePrimaryExpr(pareno,expr,parenc){return expr;}
function makeFunctionCallExpr1(name,pareno,parenc){return new FunctionCallExpr(name);}
function makeFunctionCallExpr2(name,pareno,arg1,args,parenc){var ret=new FunctionCallExpr(name);ret.appendArg(arg1);for(var i=0;i<args.length;++i){ret.appendArg(args[i]);}
return ret;}
function makeArgumentExpr(comma,expr){return expr;}
function makeUnionExpr(expr1,pipe,expr2){return new UnionExpr(expr1,expr2);}
function makePathExpr1(filter,slash,rel){return new PathExpr(filter,rel);}
function makePathExpr2(filter,dslash,rel){rel.prependStep(makeAbbrevStep(dslash.value));return new PathExpr(filter,rel);}
function makeFilterExpr(expr,predicates){if(predicates.length>0){return new FilterExpr(expr,predicates);}else{return expr;}}
function makeUnaryMinusExpr(minus,expr){return new UnaryMinusExpr(expr);}
function makeBinaryExpr(expr1,op,expr2){return new BinaryExpr(expr1,op,expr2);}
function makeLiteralExpr(token){var value=token.value.substring(1,token.value.length-1);return new LiteralExpr(value);}
function makeNumberExpr(token){return new NumberExpr(token.value);}
function makeVariableReference(dollar,name){return new VariableExpr(name.value);}
function makeSimpleExpr(expr){if(expr.charAt(0)=='$'){return new VariableExpr(expr.substr(1));}else if(expr.charAt(0)=='@'){var a=new NodeTestName(expr.substr(1));var b=new StepExpr('attribute',a);var c=new LocationExpr();c.appendStep(b);return c;}else if(expr.match(/^[0-9]+$/)){return new NumberExpr(expr);}else{var a=new NodeTestName(expr);var b=new StepExpr('child',a);var c=new LocationExpr();c.appendStep(b);return c;}}
function makeSimpleExpr2(expr){var steps=stringSplit(expr,'/');var c=new LocationExpr();for(var i=0;i<steps.length;++i){var a=new NodeTestName(steps[i]);var b=new StepExpr('child',a);c.appendStep(b);}
return c;}
var xpathAxis={ANCESTOR_OR_SELF:'ancestor-or-self',ANCESTOR:'ancestor',ATTRIBUTE:'attribute',CHILD:'child',DESCENDANT_OR_SELF:'descendant-or-self',DESCENDANT:'descendant',FOLLOWING_SIBLING:'following-sibling',FOLLOWING:'following',NAMESPACE:'namespace',PARENT:'parent',PRECEDING_SIBLING:'preceding-sibling',PRECEDING:'preceding',SELF:'self'};var xpathAxesRe=[xpathAxis.ANCESTOR_OR_SELF,xpathAxis.ANCESTOR,xpathAxis.ATTRIBUTE,xpathAxis.CHILD,xpathAxis.DESCENDANT_OR_SELF,xpathAxis.DESCENDANT,xpathAxis.FOLLOWING_SIBLING,xpathAxis.FOLLOWING,xpathAxis.NAMESPACE,xpathAxis.PARENT,xpathAxis.PRECEDING_SIBLING,xpathAxis.PRECEDING,xpathAxis.SELF].join('|');var TOK_PIPE={label:"|",prec:17,re:new RegExp("^\\|")};var TOK_DSLASH={label:"//",prec:19,re:new RegExp("^//")};var TOK_SLASH={label:"/",prec:30,re:new RegExp("^/")};var TOK_AXIS={label:"::",prec:20,re:new RegExp("^::")};var TOK_COLON={label:":",prec:1000,re:new RegExp("^:")};var TOK_AXISNAME={label:"[axis]",re:new RegExp('^('+xpathAxesRe+')')};var TOK_PARENO={label:"(",prec:34,re:new RegExp("^\\(")};var TOK_PARENC={label:")",re:new RegExp("^\\)")};var TOK_DDOT={label:"..",prec:34,re:new RegExp("^\\.\\.")};var TOK_DOT={label:".",prec:34,re:new RegExp("^\\.")};var TOK_AT={label:"@",prec:34,re:new RegExp("^@")};var TOK_COMMA={label:",",re:new RegExp("^,")};var TOK_OR={label:"or",prec:10,re:new RegExp("^or\\b")};var TOK_AND={label:"and",prec:11,re:new RegExp("^and\\b")};var TOK_EQ={label:"=",prec:12,re:new RegExp("^=")};var TOK_NEQ={label:"!=",prec:12,re:new RegExp("^!=")};var TOK_GE={label:">=",prec:13,re:new RegExp("^>=")};var TOK_GT={label:">",prec:13,re:new RegExp("^>")};var TOK_LE={label:"<=",prec:13,re:new RegExp("^<=")};var TOK_LT={label:"<",prec:13,re:new RegExp("^<")};var TOK_PLUS={label:"+",prec:14,re:new RegExp("^\\+"),left:true};var TOK_MINUS={label:"-",prec:14,re:new RegExp("^\\-"),left:true};var TOK_DIV={label:"div",prec:15,re:new RegExp("^div\\b"),left:true};var TOK_MOD={label:"mod",prec:15,re:new RegExp("^mod\\b"),left:true};var TOK_BRACKO={label:"[",prec:32,re:new RegExp("^\\[")};var TOK_BRACKC={label:"]",re:new RegExp("^\\]")};var TOK_DOLLAR={label:"$",re:new RegExp("^\\$")};var TOK_NCNAME={label:"[ncname]",re:new RegExp('^'+XML_NC_NAME)};var TOK_ASTERISK={label:"*",prec:15,re:new RegExp("^\\*"),left:true};var TOK_LITERALQ={label:"[litq]",prec:20,re:new RegExp("^'[^\\']*'")};var TOK_LITERALQQ={label:"[litqq]",prec:20,re:new RegExp('^"[^\\"]*"')};var TOK_NUMBER={label:"[number]",prec:35,re:new RegExp('^\\d+(\\.\\d*)?')};var TOK_QNAME={label:"[qname]",re:new RegExp('^('+XML_NC_NAME+':)?'+XML_NC_NAME)};var TOK_NODEO={label:"[nodetest-start]",re:new RegExp('^(processing-instruction|comment|text|node)\\(')};var xpathTokenRules=[TOK_DSLASH,TOK_SLASH,TOK_DDOT,TOK_DOT,TOK_AXIS,TOK_COLON,TOK_AXISNAME,TOK_NODEO,TOK_PARENO,TOK_PARENC,TOK_BRACKO,TOK_BRACKC,TOK_AT,TOK_COMMA,TOK_OR,TOK_AND,TOK_NEQ,TOK_EQ,TOK_GE,TOK_GT,TOK_LE,TOK_LT,TOK_PLUS,TOK_MINUS,TOK_ASTERISK,TOK_PIPE,TOK_MOD,TOK_DIV,TOK_LITERALQ,TOK_LITERALQQ,TOK_NUMBER,TOK_QNAME,TOK_NCNAME,TOK_DOLLAR];var XPathLocationPath={label:"LocationPath"};var XPathRelativeLocationPath={label:"RelativeLocationPath"};var XPathAbsoluteLocationPath={label:"AbsoluteLocationPath"};var XPathStep={label:"Step"};var XPathNodeTest={label:"NodeTest"};var XPathPredicate={label:"Predicate"};var XPathLiteral={label:"Literal"};var XPathExpr={label:"Expr"};var XPathPrimaryExpr={label:"PrimaryExpr"};var XPathVariableReference={label:"Variablereference"};var XPathNumber={label:"Number"};var XPathFunctionCall={label:"FunctionCall"};var XPathArgumentRemainder={label:"ArgumentRemainder"};var XPathPathExpr={label:"PathExpr"};var XPathUnionExpr={label:"UnionExpr"};var XPathFilterExpr={label:"FilterExpr"};var XPathDigits={label:"Digits"};var xpathNonTerminals=[XPathLocationPath,XPathRelativeLocationPath,XPathAbsoluteLocationPath,XPathStep,XPathNodeTest,XPathPredicate,XPathLiteral,XPathExpr,XPathPrimaryExpr,XPathVariableReference,XPathNumber,XPathFunctionCall,XPathArgumentRemainder,XPathPathExpr,XPathUnionExpr,XPathFilterExpr,XPathDigits];var Q_01={label:"?"};var Q_MM={label:"*"};var Q_1M={label:"+"};var ASSOC_LEFT=true;var xpathGrammarRules=[[XPathLocationPath,[XPathRelativeLocationPath],18,passExpr],[XPathLocationPath,[XPathAbsoluteLocationPath],18,passExpr],[XPathAbsoluteLocationPath,[TOK_SLASH,XPathRelativeLocationPath],18,makeLocationExpr1],[XPathAbsoluteLocationPath,[TOK_DSLASH,XPathRelativeLocationPath],18,makeLocationExpr2],[XPathAbsoluteLocationPath,[TOK_SLASH],0,makeLocationExpr3],[XPathAbsoluteLocationPath,[TOK_DSLASH],0,makeLocationExpr4],[XPathRelativeLocationPath,[XPathStep],31,makeLocationExpr5],[XPathRelativeLocationPath,[XPathRelativeLocationPath,TOK_SLASH,XPathStep],31,makeLocationExpr6],[XPathRelativeLocationPath,[XPathRelativeLocationPath,TOK_DSLASH,XPathStep],31,makeLocationExpr7],[XPathStep,[TOK_DOT],33,makeStepExpr1],[XPathStep,[TOK_DDOT],33,makeStepExpr2],[XPathStep,[TOK_AXISNAME,TOK_AXIS,XPathNodeTest],33,makeStepExpr3],[XPathStep,[TOK_AT,XPathNodeTest],33,makeStepExpr4],[XPathStep,[XPathNodeTest],33,makeStepExpr5],[XPathStep,[XPathStep,XPathPredicate],33,makeStepExpr6],[XPathNodeTest,[TOK_ASTERISK],33,makeNodeTestExpr1],[XPathNodeTest,[TOK_NCNAME,TOK_COLON,TOK_ASTERISK],33,makeNodeTestExpr2],[XPathNodeTest,[TOK_QNAME],33,makeNodeTestExpr3],[XPathNodeTest,[TOK_NODEO,TOK_PARENC],33,makeNodeTestExpr4],[XPathNodeTest,[TOK_NODEO,XPathLiteral,TOK_PARENC],33,makeNodeTestExpr5],[XPathPredicate,[TOK_BRACKO,XPathExpr,TOK_BRACKC],33,makePredicateExpr],[XPathPrimaryExpr,[XPathVariableReference],33,passExpr],[XPathPrimaryExpr,[TOK_PARENO,XPathExpr,TOK_PARENC],33,makePrimaryExpr],[XPathPrimaryExpr,[XPathLiteral],30,passExpr],[XPathPrimaryExpr,[XPathNumber],30,passExpr],[XPathPrimaryExpr,[XPathFunctionCall],31,passExpr],[XPathFunctionCall,[TOK_QNAME,TOK_PARENO,TOK_PARENC],-1,makeFunctionCallExpr1],[XPathFunctionCall,[TOK_QNAME,TOK_PARENO,XPathExpr,XPathArgumentRemainder,Q_MM,TOK_PARENC],-1,makeFunctionCallExpr2],[XPathArgumentRemainder,[TOK_COMMA,XPathExpr],-1,makeArgumentExpr],[XPathUnionExpr,[XPathPathExpr],20,passExpr],[XPathUnionExpr,[XPathUnionExpr,TOK_PIPE,XPathPathExpr],20,makeUnionExpr],[XPathPathExpr,[XPathLocationPath],20,passExpr],[XPathPathExpr,[XPathFilterExpr],19,passExpr],[XPathPathExpr,[XPathFilterExpr,TOK_SLASH,XPathRelativeLocationPath],19,makePathExpr1],[XPathPathExpr,[XPathFilterExpr,TOK_DSLASH,XPathRelativeLocationPath],19,makePathExpr2],[XPathFilterExpr,[XPathPrimaryExpr,XPathPredicate,Q_MM],31,makeFilterExpr],[XPathExpr,[XPathPrimaryExpr],16,passExpr],[XPathExpr,[XPathUnionExpr],16,passExpr],[XPathExpr,[TOK_MINUS,XPathExpr],-1,makeUnaryMinusExpr],[XPathExpr,[XPathExpr,TOK_OR,XPathExpr],-1,makeBinaryExpr],[XPathExpr,[XPathExpr,TOK_AND,XPathExpr],-1,makeBinaryExpr],[XPathExpr,[XPathExpr,TOK_EQ,XPathExpr],-1,makeBinaryExpr],[XPathExpr,[XPathExpr,TOK_NEQ,XPathExpr],-1,makeBinaryExpr],[XPathExpr,[XPathExpr,TOK_LT,XPathExpr],-1,makeBinaryExpr],[XPathExpr,[XPathExpr,TOK_LE,XPathExpr],-1,makeBinaryExpr],[XPathExpr,[XPathExpr,TOK_GT,XPathExpr],-1,makeBinaryExpr],[XPathExpr,[XPathExpr,TOK_GE,XPathExpr],-1,makeBinaryExpr],[XPathExpr,[XPathExpr,TOK_PLUS,XPathExpr],-1,makeBinaryExpr,ASSOC_LEFT],[XPathExpr,[XPathExpr,TOK_MINUS,XPathExpr],-1,makeBinaryExpr,ASSOC_LEFT],[XPathExpr,[XPathExpr,TOK_ASTERISK,XPathExpr],-1,makeBinaryExpr,ASSOC_LEFT],[XPathExpr,[XPathExpr,TOK_DIV,XPathExpr],-1,makeBinaryExpr,ASSOC_LEFT],[XPathExpr,[XPathExpr,TOK_MOD,XPathExpr],-1,makeBinaryExpr,ASSOC_LEFT],[XPathLiteral,[TOK_LITERALQ],-1,makeLiteralExpr],[XPathLiteral,[TOK_LITERALQQ],-1,makeLiteralExpr],[XPathNumber,[TOK_NUMBER],-1,makeNumberExpr],[XPathVariableReference,[TOK_DOLLAR,TOK_QNAME],200,makeVariableReference]];var xpathRules=[];function xpathParseInit(){if(xpathRules.length){return;}
xpathGrammarRules.sort(function(a,b){var la=a[1].length;var lb=b[1].length;if(la<lb){return 1;}else if(la>lb){return-1;}else{return 0;}});var k=1;for(var i=0;i<xpathNonTerminals.length;++i){xpathNonTerminals[i].key=k++;}
for(i=0;i<xpathTokenRules.length;++i){xpathTokenRules[i].key=k++;}
xpathLog('XPath parse INIT: '+k+' rules');function push_(array,position,element){if(!array[position]){array[position]=[];}
array[position].push(element);}
for(i=0;i<xpathGrammarRules.length;++i){var rule=xpathGrammarRules[i];var pattern=rule[1];for(var j=pattern.length-1;j>=0;--j){if(pattern[j]==Q_1M){push_(xpathRules,pattern[j-1].key,rule);break;}else if(pattern[j]==Q_MM||pattern[j]==Q_01){push_(xpathRules,pattern[j-1].key,rule);--j;}else{push_(xpathRules,pattern[j].key,rule);break;}}}
xpathLog('XPath parse INIT: '+xpathRules.length+' rule bins');var sum=0;mapExec(xpathRules,function(i){if(i){sum+=i.length;}});xpathLog('XPath parse INIT: '+(sum/xpathRules.length)+' average bin size');}
function xpathCollectDescendants(nodelist,node,opt_tagName){if(opt_tagName&&node.getElementsByTagName){copyArray(nodelist,node.getElementsByTagName(opt_tagName));return;}
for(var n=node.firstChild;n;n=n.nextSibling){nodelist.push(n);xpathCollectDescendants(nodelist,n);}}
function xpathExtractTagNameFromNodeTest(nodetest){if(nodetest instanceof NodeTestName){return nodetest.name;}else if(nodetest instanceof NodeTestAny||nodetest instanceof NodeTestElementOrAttribute){return"*";}}
function xpathCollectDescendantsReverse(nodelist,node){for(var n=node.lastChild;n;n=n.previousSibling){nodelist.push(n);xpathCollectDescendantsReverse(nodelist,n);}}
function xpathDomEval(expr,node){var expr1=xpathParse(expr);var ret=expr1.evaluate(new ExprContext(node));return ret;}
function xpathSort(input,sort){if(sort.length==0){return;}
var sortlist=[];for(var i=0;i<input.contextSize();++i){var node=input.nodelist[i];var sortitem={node:node,key:[]};var context=input.clone(node,0,[node]);for(var j=0;j<sort.length;++j){var s=sort[j];var value=s.expr.evaluate(context);var evalue;if(s.type=='text'){evalue=value.stringValue();}else if(s.type=='number'){evalue=value.numberValue();}
sortitem.key.push({value:evalue,order:s.order});}
sortitem.key.push({value:i,order:'ascending'});sortlist.push(sortitem);}
sortlist.sort(xpathSortByKey);var nodes=[];for(var i=0;i<sortlist.length;++i){nodes.push(sortlist[i].node);}
input.nodelist=nodes;input.setNode(0);}
function xpathSortByKey(v1,v2){for(var i=0;i<v1.key.length;++i){var o=v1.key[i].order=='descending'?-1:1;if(v1.key[i].value>v2.key[i].value){return+1*o;}else if(v1.key[i].value<v2.key[i].value){return-1*o;}}
return 0;}
function xpathEval(select,context){var expr=xpathParse(select);var ret=expr.evaluate(context);return ret;}
function xsltProcess(xmlDoc,stylesheet){var output=domCreateDocumentFragment(new XDocument);xsltProcessContext(new ExprContext(xmlDoc),stylesheet,output);var ret=xmlText(output);return ret;}
function xsltProcessContext(input,template,output){var outputDocument=xmlOwnerDocument(output);var nodename=template.nodeName.split(/:/);if(nodename.length==1||nodename[0]!='xsl'){xsltPassThrough(input,template,output,outputDocument);}else{switch(nodename[1]){case'apply-imports':alert('not implemented: '+nodename[1]);break;case'apply-templates':var select=xmlGetAttribute(template,'select');var nodes;if(select){nodes=xpathEval(select,input).nodeSetValue();}else{nodes=input.node.childNodes;}
var sortContext=input.clone(nodes[0],0,nodes);xsltWithParam(sortContext,template);xsltSort(sortContext,template);var mode=xmlGetAttribute(template,'mode');var top=template.ownerDocument.documentElement;var templates=[];for(var i=0;i<top.childNodes.length;++i){var c=top.childNodes[i];if(c.nodeType==DOM_ELEMENT_NODE&&c.nodeName=='xsl:template'&&c.getAttribute('mode')==mode){templates.push(c);}}
for(var j=0;j<sortContext.contextSize();++j){var nj=sortContext.nodelist[j];for(var i=0;i<templates.length;++i){xsltProcessContext(sortContext.clone(nj,j),templates[i],output);}}
break;case'attribute':var nameexpr=xmlGetAttribute(template,'name');var name=xsltAttributeValue(nameexpr,input);var node=domCreateDocumentFragment(outputDocument);xsltChildNodes(input,template,node);var value=xmlValue(node);domSetAttribute(output,name,value);break;case'attribute-set':alert('not implemented: '+nodename[1]);break;case'call-template':var name=xmlGetAttribute(template,'name');var top=template.ownerDocument.documentElement;var paramContext=input.clone();xsltWithParam(paramContext,template);for(var i=0;i<top.childNodes.length;++i){var c=top.childNodes[i];if(c.nodeType==DOM_ELEMENT_NODE&&c.nodeName=='xsl:template'&&domGetAttribute(c,'name')==name){xsltChildNodes(paramContext,c,output);break;}}
break;case'choose':xsltChoose(input,template,output);break;case'comment':var node=domCreateDocumentFragment(outputDocument);xsltChildNodes(input,template,node);var commentData=xmlValue(node);var commentNode=domCreateComment(outputDocument,commentData);output.appendChild(commentNode);break;case'copy':var node=xsltCopy(output,input.node,outputDocument);if(node){xsltChildNodes(input,template,node);}
break;case'copy-of':var select=xmlGetAttribute(template,'select');var value=xpathEval(select,input);if(value.type=='node-set'){var nodes=value.nodeSetValue();for(var i=0;i<nodes.length;++i){xsltCopyOf(output,nodes[i],outputDocument);}}else{var node=domCreateTextNode(outputDocument,value.stringValue());domAppendChild(output,node);}
break;case'decimal-format':alert('not implemented: '+nodename[1]);break;case'element':var nameexpr=xmlGetAttribute(template,'name');var name=xsltAttributeValue(nameexpr,input);var node=domCreateElement(outputDocument,name);domAppendChild(output,node);xsltChildNodes(input,template,node);break;case'fallback':alert('not implemented: '+nodename[1]);break;case'for-each':xsltForEach(input,template,output);break;case'if':var test=xmlGetAttribute(template,'test');if(xpathEval(test,input).booleanValue()){xsltChildNodes(input,template,output);}
break;case'import':alert('not implemented: '+nodename[1]);break;case'include':alert('not implemented: '+nodename[1]);break;case'key':alert('not implemented: '+nodename[1]);break;case'message':alert('not implemented: '+nodename[1]);break;case'namespace-alias':alert('not implemented: '+nodename[1]);break;case'number':alert('not implemented: '+nodename[1]);break;case'otherwise':alert('error if here: '+nodename[1]);break;case'output':break;case'preserve-space':alert('not implemented: '+nodename[1]);break;case'processing-instruction':alert('not implemented: '+nodename[1]);break;case'sort':break;case'strip-space':alert('not implemented: '+nodename[1]);break;case'stylesheet':case'transform':xsltChildNodes(input,template,output);break;case'template':var match=xmlGetAttribute(template,'match');if(match&&xsltMatch(match,input)){xsltChildNodes(input,template,output);}
break;case'text':var text=xmlValue(template);var node=domCreateTextNode(outputDocument,text);output.appendChild(node);break;case'value-of':var select=xmlGetAttribute(template,'select');var value=xpathEval(select,input).stringValue();var node=domCreateTextNode(outputDocument,value);output.appendChild(node);break;case'param':xsltVariable(input,template,false);break;case'variable':xsltVariable(input,template,true);break;case'when':alert('error if here: '+nodename[1]);break;case'with-param':alert('error if here: '+nodename[1]);break;default:alert('error if here: '+nodename[1]);break;}}}
function xsltWithParam(input,template){for(var i=0;i<template.childNodes.length;++i){var c=template.childNodes[i];if(c.nodeType==DOM_ELEMENT_NODE&&c.nodeName=='xsl:with-param'){xsltVariable(input,c,true);}}}
function xsltSort(input,template){var sort=[];for(var i=0;i<template.childNodes.length;++i){var c=template.childNodes[i];if(c.nodeType==DOM_ELEMENT_NODE&&c.nodeName=='xsl:sort'){var select=xmlGetAttribute(c,'select');var expr=xpathParse(select);var type=xmlGetAttribute(c,'data-type')||'text';var order=xmlGetAttribute(c,'order')||'ascending';sort.push({expr:expr,type:type,order:order});}}
xpathSort(input,sort);}
function xsltVariable(input,template,override){var name=xmlGetAttribute(template,'name');var select=xmlGetAttribute(template,'select');var value;if(template.childNodes.length>0){var root=domCreateDocumentFragment(template.ownerDocument);xsltChildNodes(input,template,root);value=new NodeSetValue([root]);}else if(select){value=xpathEval(select,input);}else{value=new StringValue('');}
if(override||!input.getVariable(name)){input.setVariable(name,value);}}
function xsltChoose(input,template,output){for(var i=0;i<template.childNodes.length;++i){var childNode=template.childNodes[i];if(childNode.nodeType!=DOM_ELEMENT_NODE){continue;}else if(childNode.nodeName=='xsl:when'){var test=xmlGetAttribute(childNode,'test');if(xpathEval(test,input).booleanValue()){xsltChildNodes(input,childNode,output);break;}}else if(childNode.nodeName=='xsl:otherwise'){xsltChildNodes(input,childNode,output);break;}}}
function xsltForEach(input,template,output){var select=xmlGetAttribute(template,'select');var nodes=xpathEval(select,input).nodeSetValue();var sortContext=input.clone(nodes[0],0,nodes);xsltSort(sortContext,template);for(var i=0;i<sortContext.contextSize();++i){var ni=sortContext.nodelist[i];xsltChildNodes(sortContext.clone(ni,i),template,output);}}
function xsltChildNodes(input,template,output){var context=input.clone();for(var i=0;i<template.childNodes.length;++i){xsltProcessContext(context,template.childNodes[i],output);}}
function xsltPassThrough(input,template,output,outputDocument){if(template.nodeType==DOM_TEXT_NODE){if(xsltPassText(template)){var node=domCreateTextNode(outputDocument,template.nodeValue);domAppendChild(output,node);}}else if(template.nodeType==DOM_ELEMENT_NODE){var node=domCreateElement(outputDocument,template.nodeName);for(var i=0;i<template.attributes.length;++i){var a=template.attributes[i];if(a){var name=a.nodeName;var value=xsltAttributeValue(a.nodeValue,input);domSetAttribute(node,name,value);}}
domAppendChild(output,node);xsltChildNodes(input,template,node);}else{xsltChildNodes(input,template,output);}}
function xsltPassText(template){if(!template.nodeValue.match(/^\s*$/)){return true;}
var element=template.parentNode;if(element.nodeName=='xsl:text'){return true;}
while(element&&element.nodeType==DOM_ELEMENT_NODE){var xmlspace=domGetAttribute(element,'xml:space');if(xmlspace){if(xmlspace=='default'){return false;}else if(xmlspace=='preserve'){return true;}}
element=element.parentNode;}
return false;}
function xsltAttributeValue(value,context){var parts=stringSplit(value,'{');if(parts.length==1){return value;}
var ret='';for(var i=0;i<parts.length;++i){var rp=stringSplit(parts[i],'}');if(rp.length!=2){ret+=parts[i];continue;}
var val=xpathEval(rp[0],context).stringValue();ret+=val+rp[1];}
return ret;}
function xmlGetAttribute(node,name){var value=domGetAttribute(node,name);if(value){return xmlResolveEntities(value);}else{return value;}};function xsltCopyOf(dst,src,dstDocument){if(src.nodeType==DOM_DOCUMENT_FRAGMENT_NODE||src.nodeType==DOM_DOCUMENT_NODE){for(var i=0;i<src.childNodes.length;++i){arguments.callee(dst,src.childNodes[i],dstDocument);}}else{var node=xsltCopy(dst,src,dstDocument);if(node){for(var i=0;i<src.attributes.length;++i){arguments.callee(node,src.attributes[i],dstDocument);}
for(var i=0;i<src.childNodes.length;++i){arguments.callee(node,src.childNodes[i],dstDocument);}}}}
function xsltCopy(dst,src,dstDocument){if(src.nodeType==DOM_ELEMENT_NODE){var node=domCreateElement(dstDocument,src.nodeName);domAppendChild(dst,node);return node;}
if(src.nodeType==DOM_TEXT_NODE){var node=domCreateTextNode(dstDocument,src.nodeValue);domAppendChild(dst,node);}else if(src.nodeType==DOM_CDATA_SECTION_NODE){var node=domCreateCDATASection(dstDocument,src.nodeValue);domAppendChild(dst,node);}else if(src.nodeType==DOM_COMMENT_NODE){var node=domCreateComment(dstDocument,src.nodeValue);domAppendChild(dst,node);}else if(src.nodeType==DOM_ATTRIBUTE_NODE){domSetAttribute(dst,src.nodeName,src.nodeValue);}
return null;}
function xsltMatch(match,context){var expr=xpathParse(match);var ret;if(expr.steps&&!expr.absolute&&expr.steps.length==1&&expr.steps[0].axis=='child'&&expr.steps[0].predicate.length==0){ret=expr.steps[0].nodetest.evaluate(context).booleanValue();}else{ret=false;var node=context.node;while(!ret&&node){var result=expr.evaluate(context.clone(node,0,[node])).nodeSetValue();for(var i=0;i<result.length;++i){if(result[i]==context.node){ret=true;break;}}
node=node.parentNode;}}
return ret;}
var SWFUpload=function(init_settings){this.initSWFUpload(init_settings);};SWFUpload.prototype.initSWFUpload=function(init_settings){try{document.execCommand('BackgroundImageCache',false,true);}catch(ex1){}
try{this.customSettings={};this.settings={};this.eventQueue=[];this.movieName="SWFUpload_"+SWFUpload.movieCount++;this.movieElement=null;SWFUpload.instances[this.movieName]=this;this.initSettings(init_settings);this.loadFlash();this.displayDebugInfo();}catch(ex2){this.debug(ex2);}}
SWFUpload.instances={};SWFUpload.movieCount=0;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};SWFUpload.FILE_STATUS={QUEUED:-1,IN_PROGRESS:-2,ERROR:-3,COMPLETE:-4,CANCELLED:-5};SWFUpload.prototype.initSettings=function(init_settings){this.addSetting("upload_url",init_settings.upload_url,"");this.addSetting("file_post_name",init_settings.file_post_name,"Filedata");this.addSetting("post_params",init_settings.post_params,{});this.addSetting("file_types",init_settings.file_types,"*.*");this.addSetting("file_types_description",init_settings.file_types_description,"All Files");this.addSetting("file_size_limit",init_settings.file_size_limit,"1024");this.addSetting("file_upload_limit",init_settings.file_upload_limit,"0");this.addSetting("file_queue_limit",init_settings.file_queue_limit,"0");this.addSetting("flash_url",init_settings.flash_url,"swfupload.swf");this.addSetting("flash_width",init_settings.flash_width,"1px");this.addSetting("flash_height",init_settings.flash_height,"1px");this.addSetting("flash_color",init_settings.flash_color,"#FFFFFF");this.addSetting("debug_enabled",init_settings.debug,false);this.flashReady_handler=SWFUpload.flashReady;this.swfUploadLoaded_handler=this.retrieveSetting(init_settings.swfupload_loaded_handler,SWFUpload.swfUploadLoaded);this.fileDialogStart_handler=this.retrieveSetting(init_settings.file_dialog_start_handler,SWFUpload.fileDialogStart);this.fileQueued_handler=this.retrieveSetting(init_settings.file_queued_handler,SWFUpload.fileQueued);this.fileQueueError_handler=this.retrieveSetting(init_settings.file_queue_error_handler,SWFUpload.fileQueueError);this.fileDialogComplete_handler=this.retrieveSetting(init_settings.file_dialog_complete_handler,SWFUpload.fileDialogComplete);this.uploadStart_handler=this.retrieveSetting(init_settings.upload_start_handler,SWFUpload.uploadStart);this.uploadProgress_handler=this.retrieveSetting(init_settings.upload_progress_handler,SWFUpload.uploadProgress);this.uploadError_handler=this.retrieveSetting(init_settings.upload_error_handler,SWFUpload.uploadError);this.uploadSuccess_handler=this.retrieveSetting(init_settings.upload_success_handler,SWFUpload.uploadSuccess);this.uploadComplete_handler=this.retrieveSetting(init_settings.upload_complete_handler,SWFUpload.uploadComplete);this.debug_handler=this.retrieveSetting(init_settings.debug_handler,SWFUpload.debug);this.customSettings=this.retrieveSetting(init_settings.custom_settings,{});};SWFUpload.prototype.loadFlash=function(){var html,target_element,container;if(document.getElementById(this.movieName)!==null){return false;}
try{target_element=document.getElementsByTagName("body")[0];if(typeof(target_element)==="undefined"||target_element===null){this.debug('Could not find the BODY element. SWFUpload failed to load.');return false;}}catch(ex){return false;}
container=document.createElement("div");container.style.width=this.getSetting("flash_width");container.style.height=this.getSetting("flash_height");target_element.appendChild(container);container.innerHTML=this.getFlashHTML();};SWFUpload.prototype.getFlashHTML=function(){var html="";if(navigator.plugins&&navigator.mimeTypes&&navigator.mimeTypes.length){html='<embed type="application/x-shockwave-flash" src="'+this.getSetting("flash_url")+'" width="'+this.getSetting("flash_width")+'" height="'+this.getSetting("flash_height")+'"';html+=' id="'+this.movieName+'" name="'+this.movieName+'" ';html+='bgcolor="'+this.getSetting("flash_color")+'" quality="high" menu="false" flashvars="';html+=this.getFlashVars();html+='" />';}else{html='<object id="'+this.movieName+'" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="'+this.getSetting("flash_width")+'" height="'+this.getSetting("flash_height")+'">';html+='<param name="movie" value="'+this.getSetting("flash_url")+'">';html+='<param name="bgcolor" value="'+this.getSetting("flash_color")+'" />';html+='<param name="quality" value="high" />';html+='<param name="menu" value="false" />';html+='<param name="flashvars" value="'+this.getFlashVars()+'" />';html+='</object>';}
return html;};SWFUpload.prototype.getFlashVars=function(){var param_string=this.buildParamString();var html="";html+="movieName="+encodeURIComponent(this.movieName);html+="&uploadURL="+encodeURIComponent(this.getSetting("upload_url"));html+="&params="+encodeURIComponent(param_string);html+="&filePostName="+encodeURIComponent(this.getSetting("file_post_name"));html+="&fileTypes="+encodeURIComponent(this.getSetting("file_types"));html+="&fileTypesDescription="+encodeURIComponent(this.getSetting("file_types_description"));html+="&fileSizeLimit="+encodeURIComponent(this.getSetting("file_size_limit"));html+="&fileUploadLimit="+encodeURIComponent(this.getSetting("file_upload_limit"));html+="&fileQueueLimit="+encodeURIComponent(this.getSetting("file_queue_limit"));html+="&debugEnabled="+encodeURIComponent(this.getSetting("debug_enabled"));return html;};SWFUpload.prototype.getMovieElement=function(){if(typeof(this.movieElement)==="undefined"||this.movieElement===null){this.movieElement=document.getElementById(this.movieName);}
return this.movieElement;};SWFUpload.prototype.buildParamString=function(){var post_params=this.getSetting("post_params");var param_string_pairs=[];var i,value,name;if(typeof(post_params)==="object"){for(name in post_params){if(post_params.hasOwnProperty(name)){if(typeof(post_params[name])==="string"){param_string_pairs.push(encodeURIComponent(name)+"="+encodeURIComponent(post_params[name]));}}}}
return param_string_pairs.join("&");};SWFUpload.prototype.addSetting=function(name,value,default_value){if(typeof(value)==="undefined"||value===null){this.settings[name]=default_value;}else{this.settings[name]=value;}
return this.settings[name];};SWFUpload.prototype.getSetting=function(name){if(typeof(this.settings[name])==="undefined"){return"";}else{return this.settings[name];}};SWFUpload.prototype.retrieveSetting=function(value,default_value){if(typeof(value)==="undefined"||value===null){return default_value;}else{return value;}};SWFUpload.prototype.displayDebugInfo=function(){var key,debug_message="";debug_message+="----- SWFUPLOAD SETTINGS     ----\nID: "+this.moveName+"\n";debug_message+=this.outputObject(this.settings);debug_message+="----- SWFUPLOAD SETTINGS END ----\n";debug_message+="\n";this.debug(debug_message);};SWFUpload.prototype.outputObject=function(object,prefix){var output="",key;if(typeof(prefix)!=="string"){prefix="";}
if(typeof(object)!=="object"){return"";}
for(key in object){if(object.hasOwnProperty(key)){if(typeof(object[key])==="object"){output+=(prefix+key+": { \n"+this.outputObject(object[key],"\t"+prefix)+prefix+"}"+"\n");}else{output+=(prefix+key+": "+object[key]+"\n");}}}
return output;};SWFUpload.prototype.selectFile=function(){var movie_element=this.getMovieElement();if(movie_element!==null&&typeof(movie_element.SelectFile)==="function"){try{movie_element.SelectFile();}
catch(ex){this.debug("Could not call SelectFile: "+ex);}}else{this.debug("Could not find Flash element");}};SWFUpload.prototype.selectFiles=function(){var movie_element=this.getMovieElement();if(movie_element!==null&&typeof(movie_element.SelectFiles)==="function"){try{movie_element.SelectFiles();}
catch(ex){this.debug("Could not call SelectFiles: "+ex);}}else{this.debug("Could not find Flash element");}};SWFUpload.prototype.startUpload=function(file_id){var self=this;var movie_element=this.getMovieElement();if(movie_element!==null&&typeof(movie_element.StartUpload)==="function"){setTimeout(function(){try{movie_element.StartUpload(file_id);}
catch(ex){self.debug("Could not call StartUpload: "+ex);}},0);}else{this.debug("Could not find Flash element");}};SWFUpload.prototype.cancelUpload=function(file_id){var movie_element=this.getMovieElement();if(movie_element!==null&&typeof(movie_element.CancelUpload)==="function"){try{movie_element.CancelUpload(file_id);}
catch(ex){this.debug("Could not call CancelUpload: "+ex);}}else{this.debug("Could not find Flash element");}};SWFUpload.prototype.stopUpload=function(){var movie_element=this.getMovieElement();if(movie_element!==null&&typeof(movie_element.StopUpload)==="function"){try{movie_element.StopUpload();}
catch(ex){this.debug("Could not call StopUpload: "+ex);}}else{this.debug("Could not find Flash element");}};SWFUpload.prototype.getStats=function(){var movie_element=this.getMovieElement();if(movie_element!==null&&typeof(movie_element.GetStats)==="function"){try{return movie_element.GetStats();}
catch(ex){this.debug("Could not call GetStats");}}else{this.debug("Could not find Flash element");}};SWFUpload.prototype.setStats=function(stats_object){var movie_element=this.getMovieElement();if(movie_element!==null&&typeof(movie_element.SetStats)==="function"){try{movie_element.SetStats(stats_object);}
catch(ex){this.debug("Could not call SetStats");}}else{this.debug("Could not find Flash element");}};SWFUpload.prototype.setCredentials=function(name,password){var movie_element=this.getMovieElement();if(movie_element!==null&&typeof(movie_element.SetCredentials)==="function"){try{return movie_element.SetCredentials(name,password);}
catch(ex){this.debug("Could not call SetCredentials");}}else{this.debug("Could not find Flash element");}};SWFUpload.prototype.getFile=function(file_id){var movie_element=this.getMovieElement();if(typeof(file_id)==="number"){if(movie_element!==null&&typeof(movie_element.GetFileByIndex)==="function"){try{return movie_element.GetFileByIndex(file_id);}
catch(ex){this.debug("Could not call GetFileByIndex");}}else{this.debug("Could not find Flash element");}}else{if(movie_element!==null&&typeof(movie_element.GetFile)==="function"){try{return movie_element.GetFile(file_id);}
catch(ex){this.debug("Could not call GetFile");}}else{this.debug("Could not find Flash element");}}};SWFUpload.prototype.addFileParam=function(file_id,name,value){var movie_element=this.getMovieElement();if(movie_element!==null&&typeof(movie_element.AddFileParam)==="function"){try{return movie_element.AddFileParam(file_id,name,value);}
catch(ex){this.debug("Could not call AddFileParam");}}else{this.debug("Could not find Flash element");}};SWFUpload.prototype.removeFileParam=function(file_id,name){var movie_element=this.getMovieElement();if(movie_element!==null&&typeof(movie_element.RemoveFileParam)==="function"){try{return movie_element.RemoveFileParam(file_id,name);}
catch(ex){this.debug("Could not call AddFileParam");}}else{this.debug("Could not find Flash element");}};SWFUpload.prototype.setUploadURL=function(url){var movie_element=this.getMovieElement();if(movie_element!==null&&typeof(movie_element.SetUploadURL)==="function"){try{this.addSetting("upload_url",url);movie_element.SetUploadURL(this.getSetting("upload_url"));}
catch(ex){this.debug("Could not call SetUploadURL");}}else{this.debug("Could not find Flash element in setUploadURL");}};SWFUpload.prototype.setPostParams=function(param_object){var movie_element=this.getMovieElement();if(movie_element!==null&&typeof(movie_element.SetPostParams)==="function"){try{this.addSetting("post_params",param_object);movie_element.SetPostParams(this.getSetting("post_params"));}
catch(ex){this.debug("Could not call SetPostParams");}}else{this.debug("Could not find Flash element in SetPostParams");}};SWFUpload.prototype.setFileTypes=function(types,description){var movie_element=this.getMovieElement();if(movie_element!==null&&typeof(movie_element.SetFileTypes)==="function"){try{this.addSetting("file_types",types);this.addSetting("file_types_description",description);movie_element.SetFileTypes(this.getSetting("file_types"),this.getSetting("file_types_description"));}
catch(ex){this.debug("Could not call SetFileTypes");}}else{this.debug("Could not find Flash element in SetFileTypes");}};SWFUpload.prototype.setFileSizeLimit=function(file_size_limit){var movie_element=this.getMovieElement();if(movie_element!==null&&typeof(movie_element.SetFileSizeLimit)==="function"){try{this.addSetting("file_size_limit",file_size_limit);movie_element.SetFileSizeLimit(this.getSetting("file_size_limit"));}
catch(ex){this.debug("Could not call SetFileSizeLimit");}}else{this.debug("Could not find Flash element in SetFileSizeLimit");}};SWFUpload.prototype.setFileUploadLimit=function(file_upload_limit){var movie_element=this.getMovieElement();if(movie_element!==null&&typeof(movie_element.SetFileUploadLimit)==="function"){try{this.addSetting("file_upload_limit",file_upload_limit);movie_element.SetFileUploadLimit(this.getSetting("file_upload_limit"));}
catch(ex){this.debug("Could not call SetFileUploadLimit");}}else{this.debug("Could not find Flash element in SetFileUploadLimit");}};SWFUpload.prototype.setFileQueueLimit=function(file_queue_limit){var movie_element=this.getMovieElement();if(movie_element!==null&&typeof(movie_element.SetFileQueueLimit)==="function"){try{this.addSetting("file_queue_limit",file_queue_limit);movie_element.SetFileQueueLimit(this.getSetting("file_queue_limit"));}
catch(ex){this.debug("Could not call SetFileQueueLimit");}}else{this.debug("Could not find Flash element in SetFileQueueLimit");}};SWFUpload.prototype.setFilePostName=function(file_post_name){var movie_element=this.getMovieElement();if(movie_element!==null&&typeof(movie_element.SetFilePostName)==="function"){try{this.addSetting("file_post_name",file_post_name);movie_element.SetFilePostName(this.getSetting("file_post_name"));}
catch(ex){this.debug("Could not call SetFilePostName");}}else{this.debug("Could not find Flash element in SetFilePostName");}};SWFUpload.prototype.setDebugEnabled=function(debug_enabled){var movie_element=this.getMovieElement();if(movie_element!==null&&typeof(movie_element.SetDebugEnabled)==="function"){try{this.addSetting("debug_enabled",debug_enabled);movie_element.SetDebugEnabled(this.getSetting("debug_enabled"));}
catch(ex){this.debug("Could not call SetDebugEnabled");}}else{this.debug("Could not find Flash element in SetDebugEnabled");}};SWFUpload.prototype.flashReady=function(){var movie_element=this.getMovieElement();if(movie_element===null||typeof(movie_element.StartUpload)!=="function"){this.debug("ExternalInterface methods failed to initialize.");return;}
var self=this;if(typeof(self.flashReady_handler)==="function"){this.eventQueue[this.eventQueue.length]=function(){self.flashReady_handler();};setTimeout(function(){self.executeNextEvent();},0);}else{this.debug("flashReady_handler event not defined");}};SWFUpload.prototype.executeNextEvent=function(){var f=this.eventQueue.shift();if(typeof(f)==="function"){f();}}
SWFUpload.prototype.fileDialogStart=function(){var self=this;if(typeof(self.fileDialogStart_handler)==="function"){this.eventQueue[this.eventQueue.length]=function(){self.fileDialogStart_handler();};setTimeout(function(){self.executeNextEvent();},0);}else{this.debug("fileDialogStart event not defined");}};SWFUpload.prototype.fileQueued=function(file){var self=this;if(typeof(self.fileQueued_handler)==="function"){this.eventQueue[this.eventQueue.length]=function(){self.fileQueued_handler(file);};setTimeout(function(){self.executeNextEvent();},0);}else{this.debug("fileQueued event not defined");}};SWFUpload.prototype.fileQueueError=function(file,error_code,message){var self=this;if(typeof(self.fileQueueError_handler)==="function"){this.eventQueue[this.eventQueue.length]=function(){self.fileQueueError_handler(file,error_code,message);};setTimeout(function(){self.executeNextEvent();},0);}else{this.debug("fileQueueError event not defined");}};SWFUpload.prototype.fileDialogComplete=function(num_files_selected){var self=this;if(typeof(self.fileDialogComplete_handler)==="function"){this.eventQueue[this.eventQueue.length]=function(){self.fileDialogComplete_handler(num_files_selected);};setTimeout(function(){self.executeNextEvent();},0);}else{this.debug("fileDialogComplete event not defined");}};SWFUpload.prototype.uploadStart=function(file){var self=this;if(typeof(self.fileDialogComplete_handler)==="function"){this.eventQueue[this.eventQueue.length]=function(){self.returnUploadStart(self.uploadStart_handler(file));};setTimeout(function(){self.executeNextEvent();},0);}else{this.debug("uploadStart event not defined");}};SWFUpload.prototype.returnUploadStart=function(return_value){var movie_element=this.getMovieElement();if(movie_element!==null&&typeof(movie_element.ReturnUploadStart)==="function"){try{movie_element.ReturnUploadStart(return_value);}
catch(ex){this.debug("Could not call ReturnUploadStart");}}else{this.debug("Could not find Flash element in returnUploadStart");}};SWFUpload.prototype.uploadProgress=function(file,bytes_complete,bytes_total){var self=this;if(typeof(self.uploadProgress_handler)==="function"){this.eventQueue[this.eventQueue.length]=function(){self.uploadProgress_handler(file,bytes_complete,bytes_total);};setTimeout(function(){self.executeNextEvent();},0);}else{this.debug("uploadProgress event not defined");}};SWFUpload.prototype.uploadError=function(file,error_code,message){var self=this;if(typeof(this.uploadError_handler)==="function"){this.eventQueue[this.eventQueue.length]=function(){self.uploadError_handler(file,error_code,message);};setTimeout(function(){self.executeNextEvent();},0);}else{this.debug("uploadError event not defined");}};SWFUpload.prototype.uploadSuccess=function(file,server_data){var self=this;if(typeof(self.uploadSuccess_handler)==="function"){this.eventQueue[this.eventQueue.length]=function(){self.uploadSuccess_handler(file,server_data);};setTimeout(function(){self.executeNextEvent();},0);}else{this.debug("uploadSuccess event not defined");}};SWFUpload.prototype.uploadComplete=function(file){var self=this;if(typeof(self.uploadComplete_handler)==="function"){this.eventQueue[this.eventQueue.length]=function(){self.uploadComplete_handler(file);};setTimeout(function(){self.executeNextEvent();},0);}else{this.debug("uploadComplete event not defined");}};SWFUpload.prototype.debug=function(message){var self=this;if(typeof(self.debug_handler)==="function"){this.eventQueue[this.eventQueue.length]=function(){self.debug_handler(message);};setTimeout(function(){self.executeNextEvent();},0);}else{this.eventQueue[this.eventQueue.length]=function(){self.debugMessage(message);};setTimeout(function(){self.executeNextEvent();},0);}};SWFUpload.flashReady=function(){try{this.debug("Flash called back and is ready.");if(typeof(this.swfUploadLoaded_handler)==="function"){this.swfUploadLoaded_handler();}}catch(ex){this.debug(ex);}};SWFUpload.swfUploadLoaded=function(){};SWFUpload.fileDialogStart=function(){};SWFUpload.fileQueued=function(file){};SWFUpload.fileQueueError=function(file,error_code,message){try{switch(error_code){case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:this.debug("Error Code: File too big, File name: "+file.name+", File size: "+file.size+", Message: "+message);break;case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:this.debug("Error Code: Zero Byte File, File name: "+file.name+", File size: "+file.size+", Message: "+message);break;case SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED:this.debug("Error Code: Upload limit reached, File name: "+file.name+", File size: "+file.size+", Message: "+message);break;case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:this.debug("Error Code: File extension is not allowed, Message: "+message);break;default:this.debug("Error Code: Unhandled error occured. Errorcode: "+error_code);}}catch(ex){this.debug(ex);}};SWFUpload.fileDialogComplete=function(num_files_selected){};SWFUpload.uploadStart=function(file){return true;};SWFUpload.uploadProgress=function(file,bytes_complete,bytes_total){this.debug("File Progress: "+file.id+", Bytes: "+bytes_complete+". Total: "+bytes_total);};SWFUpload.uploadSuccess=function(file,server_data){};SWFUpload.uploadComplete=function(file){};SWFUpload.debug=function(message){if(this.getSetting("debug_enabled")){this.debugMessage(message);}};SWFUpload.uploadError=function(file,error_code,message){try{switch(errcode){case SWFUpload.UPLOAD_ERROR.SPECIFIED_FILE_ID_NOT_FOUND:this.debug("Error Code: File ID specified for upload was not found, Message: "+msg);break;case SWFUpload.UPLOAD_ERROR.HTTP_ERROR:this.debug("Error Code: HTTP Error, File name: "+file.name+", Message: "+msg);break;case SWFUpload.UPLOAD_ERROR.MISSING_UPLOAD_URL:this.debug("Error Code: No backend file, File name: "+file.name+", Message: "+msg);break;case SWFUpload.UPLOAD_ERROR.IO_ERROR:this.debug("Error Code: IO Error, File name: "+file.name+", Message: "+msg);break;case SWFUpload.UPLOAD_ERROR.SECURITY_ERROR:this.debug("Error Code: Security Error, File name: "+file.name+", Message: "+msg);break;case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:this.debug("Error Code: Upload limit reached, File name: "+file.name+", File size: "+file.size+", Message: "+msg);break;case SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED:this.debug("Error Code: Upload Initialization exception, File name: "+file.name+", File size: "+file.size+", Message: "+msg);break;case SWFUpload.UPLOAD_ERROR.FILE_VALIDATION_FAILED:this.debug("Error Code: uploadStart callback returned false, File name: "+file.name+", File size: "+file.size+", Message: "+msg);break;case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED:this.debug("Error Code: The file upload was cancelled, File name: "+file.name+", File size: "+file.size+", Message: "+msg);break;case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED:this.debug("Error Code: The file upload was stopped, File name: "+file.name+", File size: "+file.size+", Message: "+msg);break;default:this.debug("Error Code: Unhandled error occured. Errorcode: "+errcode);}}catch(ex){this.debug(ex);}};SWFUpload.prototype.debugMessage=function(message){var exception_message,exception_values;if(typeof(message)==="object"&&typeof(message.name)==="string"&&typeof(message.message)==="string"){exception_message="";exception_values=[];for(var key in message){exception_values.push(key+": "+message[key]);}
exception_message=exception_values.join("\n");exception_values=exception_message.split("\n");exception_message="EXCEPTION: "+exception_values.join("\nEXCEPTION: ");SWFUpload.Console.writeLine(exception_message);}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);}};var Timezone={set:function(){var date=new Date();var timezone="timezone="+-date.getTimezoneOffset()*60;date.setTime(date.getTime()+(1000*24*60*60*1000));var expires="; expires="+date.toGMTString();document.cookie=timezone+expires+"; path=/";}}
function setIdeasCount(num){var elt=$('ideabook_text');if(elt){elt.update(''+num+' ideas');}}
function db(sValue){if(window.console){console.log(sValue);}else if(BB.debug==true){oDiv=$('debug_div');if(!oDiv){oDiv=document.createElement('div');oDiv.id='debug_div';document.body.appendChild(oDiv);}
oDiv.innerHTML+='<br />'+sValue;}}
function getMovie(embedName){var isIE=navigator.appName.indexOf("Microsoft")!=-1;return(isIE)?window[embedName]:document[embedName];}
function flashplayer_missing(){setTimeout('show_flashplayer_missing()','5000');}
function show_flashplayer_missing(){var obj=$('flashplayer_missing');if(obj)obj.show();}
function goToUrl(url){location.href=url;}
function prettyPrint(oObj)
{for(var key in oObj)
{if(typeof oObj[key]=='object')
{prettyPrint(oObj[key]);}
else
{db(key+' => '+oObj[key]);}}}
function get_page_size(){var x,y;if(self.innerHeight){x=self.innerWidth;y=self.innerHeight;}else if(document.documentElement&&document.documentElement.clientHeight){x=document.documentElement.clientWidth;y=document.documentElement.clientHeight;}else if(document.body){x=document.body.clientWidth;y=document.body.clientHeight;}
return[x,y]}
var BB={currentAlbumId:null,albumType:'',currentEditField:null,debug:true}
var DragDrop={addSortable:function(album_id,container){if(!container)var container='album_photos';Sortable.create(container,{constraint:'',overlap:'horizontal',tag:'img',zIndex:1000,onUpdate:function(){new Ajax.Request('/albums/sort/'+album_id,{method:'post',parameters:{ids:Sortable.serialize(container),album_type:BB.albumType},onComplete:function(request){new Effect.Highlight(container)}})}});},dropSortable:function(container){Sortable.destroy($(container));},addDraggable:function(obj){var id=(typeof(obj)=='object')?obj.id:obj;new Draggable(id,{zIndex:1000,ghosting:true,revert:true});},addDroppableAlbum:function(album_id){Droppables.add('album',{accept:'thumbnail_small',onDrop:function(drag){new Ajax.Request("/albums/add/"+album_id,{method:'post',parameters:{photo_id:drag.id,album_type:BB.albumType},onSuccess:function(transport){var add_ids=transport.responseText.evalJSON();blissbook.browser.BrowserWidget.addAlbumPhoto(album_id,add_ids[0]['photo_id'],add_ids[0]['album_photo_id']);new Effect.Highlight("album");}});}});},addDroppableRemove:function(album_id){Droppables.add('remove',{accept:'album_photo',onDrop:function(drag){new Ajax.Request("/albums/remove/"+album_id,{method:'post',parameters:{photo_id:drag.id,album_type:BB.albumType},onSuccess:function(transport){$(drag.id).remove();DragDrop.addSortable(album_id);}});}});}}
var PublishNav={album_id:null,active:null,speed:.2,set:function(id){if(PublishNav.isCurrent(id))return;if(PublishNav.active){PublishNav.hide(id);}else{PublishNav.show(id);}},hide:function(id){var e=$(PublishNav.active+'_img')
e.src=e.src.replace('_sel','');Effect.BlindUp(PublishNav.active+'_content',{duration:PublishNav.speed});PublishNav.show(id);},show:function(id){var e=$(id+'_img')
e.src=e.src.replace('.gif','_sel.gif');Effect.BlindDown(id+'_content',{duration:PublishNav.speed});PublishNav.active=id;},isCurrent:function(id){return PublishNav.active==id;}}
var WeddingVendorNav={active:null,set:function(id){if(WeddingVendorNav.active==id)return;if(WeddingVendorNav.active)$(WeddingVendorNav.active).className='wedding_vendor_nav';WeddingVendorNav.active=id;$(id).className='wedding_vendor_nav_sel';},hoverOn:function(id){if(WeddingVendorNav.active==id)return;$(id).className='wedding_vendor_nav_sel';},hoverOff:function(id){if(WeddingVendorNav.active==id)return;$(id).className='wedding_vendor_nav';}}
var TagSelector=Class.create();TagSelector.prototype={initialize:function(prefix){this.prefix=prefix;this.tagInput=$(this.prefix+'_tag_names');this.highlighted=$H();this.orig=$A();this.cleanTags();this.setHighlights();},tag:function(tag_name){this.cleanTags();var index=this.orig.indexOf(tag_name);if(index!=-1){this.removeTag(index)}else{this.addTag(tag_name);}
this.renderTags();this.setHighlights();},cleanTags:function(){var orig=this.tagInput.value;orig=orig.split(",");orig=orig.collect(function(o){return o.strip()});this.orig=orig.compact();this.orig=orig.without("");},addTag:function(tag_name){this.orig.push(tag_name);},removeTag:function(index){this.orig[index]=null;this.orig=this.orig.compact();},renderTags:function(){var suffix=(this.orig.length>0)?", ":"";this.tagInput.value=this.orig.join(", ")+suffix;},setHighlights:function(){this.clearHighlights();var self=this;this.orig.each(function(o){var r=$(self.prefix+'_recommended_'+o);if(r)r.addClassName('t_sel');var p=$(self.prefix+'_popular_'+o);if(p)p.addClassName('t_sel');if(r||p)self.highlighted[o]=''});},clearHighlights:function(){var self=this;this.highlighted.each(function(h){var r=$(self.prefix+'_recommended_'+h.key);if(r)r.removeClassName('t_sel');var p=$(self.prefix+'_popular_'+h.key);if(p)p.removeClassName('t_sel');});this.highlighted=$H();}}
var ImageNav=Class.create();ImageNav.prototype={initialize:function(ext){this.ext=ext||'.png';this.active='';},set:function(id){if(this.active==id)return;if(this.active)this.clear();this.select(id);this.active=id;},clear:function(){this.unselect(this.active);this.active='';},hoverOn:function(id){if(this.active==id)return;this.select(id);},select:function(id){e=$(id);if(e&&!e.src.match('_sel'))e.src=e.src.replace(this.ext,'_sel'+this.ext);},hoverOff:function(id){if(this.active==id)return;this.unselect(id);},unselect:function(id){e=$(id);if(e&&e.src.match('_sel'))e.src=e.src.replace('_sel','');}};var CSSImageNav=Class.create();CSSImageNav.prototype={initialize:function(){this.active='';},set:function(id){if(this.active==id)return;if(this.active)this.clear();this.select(id);this.active=id;},clear:function(){this.unselect(this.active);this.active='';},hoverOn:function(id){if(this.active==id)return;this.select(id);},select:function(id){e=$(id);if(e)e.className=id+'_sel';},hoverOff:function(id){if(this.active==id)return;this.unselect(id);},unselect:function(id){e=$(id);if(e)e.className=id;}};var FlashMsg={h:[],set:function(type,msg,bDisplay){FlashMsg.build(type,msg);if(bDisplay)FlashMsg.display();},setAll:function(flash,bDisplay){if(flash['success'])FlashMsg.build('success',flash['success']);if(flash['notice'])FlashMsg.build('notice',flash['notice'])
if(flash['error'])FlashMsg.build('error',flash['error'])
if(bDisplay)FlashMsg.display();},build:function(type,msg){FlashMsg.h.push(msg);},display:function(){var obj=$('flash_msg');if(obj){obj.update(FlashMsg.h.join("\n"));if(FlashMsg.h.length>0){obj.show();FlashMsg.h=[];window.scrollTo(0,0);}}},clear:function(){obj=$('flash_msg');if(obj){obj.update();obj.hide();}}}
var Tagging={initialize:function(options){Tagging.bCtrlKey=false;Tagging.bShiftKey=false;Tagging.bEscKey=false;Tagging.aPhotos=$A();Tagging.hPhotos=$H();Tagging.sLastPhotoDomId='';Tagging.options=options||{};Tagging.startListeners();},loadPhoto:function(domId){Tagging.aPhotos.push(domId)},startListeners:function(){Event.observe(document,"keydown",Tagging.keyDown);Event.observe(document,"keyup",Tagging.keyUp);},keyDown:function(event){event=event||window.event;if(event.keyCode==16&&!Tagging.bShiftKey)Tagging.bShiftKey=true;if(event.keyCode==17&&!Tagging.bCtrlKey)Tagging.bCtrlKey=true;if(event.keyCode==27&&!Tagging.bEscKey)Tagging.bCtrlKey=true;},keyUp:function(event){event=event||window.event;if(event.keyCode==16)Tagging.bShiftKey=false;if(event.keyCode==17)Tagging.bCtrlKey=false;if(event.keyCode==27){Tagging.bEscKey=false;Tagging.clearAll();}},updatePhotoDetails:function(id,p){alert('public/javascripts/Tagging.js#updatePhotoDetails: - deprecated');},updatePhotoTags:function(id,tags){alert('public/javascripts/Tagging.js#updatePhotoTags: - deprecated');},selectPhoto:function(domId){if(Tagging.bShiftKey){Tagging.findRange(domId)}else if(Tagging.bCtrlKey){if(domId in Tagging.hPhotos){Tagging.removePhoto(domId);}else{Tagging.addPhoto(domId);}}else{if(domId in Tagging.hPhotos){if(Tagging.hPhotos.keys().length>1){Tagging.clearAll();Tagging.addPhoto(domId);}else{Tagging.clearAll();Tagging.sLastPhotoDomId='';}}else{Tagging.clearAll();Tagging.addPhoto(domId);}}
Tagging.setRenderEdit(domId);},addPhoto:function(domId){Tagging.hPhotos[domId]='';Tagging.sLastPhotoDomId=domId;blissbook.browser.BrowserWidget.onPhotoSelectedForTagging(domId);},removePhoto:function(domId){Tagging.hPhotos.remove(domId);blissbook.browser.BrowserWidget.onPhotoUnselectedForTagging(domId);},findRange:function(id){var last=Tagging.sLastPhotoDomId||id;var a=Tagging.aPhotos.indexOf(last);var b=Tagging.aPhotos.indexOf(id);if(b>a){Tagging.addPhotoRange(a,b);}else{Tagging.addPhotoRange(b,a);}
Tagging.sLastPhotoDomId=last;},addPhotoRange:function(a,b){Tagging.clearAll();for(var i=a;i<=b;i++){Tagging.addPhoto(Tagging.aPhotos[i]);}},clearAll:function(){Tagging.hPhotos.each(function(pair){Tagging.removePhoto(pair.key);});},setRenderEdit:function(id){var selectionLength=Tagging.hPhotos.keys().length;if(selectionLength<=0||selectionLength>1){if($('photo_edit'))$('photo_edit').hide();Tagging.clearRenderEdit();}else{if($('photo_edit'))$('photo_edit').show();Tagging.renderEdit(id);}},renderEdit:function(id){alert('public/javascripts/Tagging.js#renderEdit - deprecated');},clearRenderEdit:function(){if($('photo_edit')){$('photo_title').value=null;$('photo_description').value=null;$('current_tag_container').hide();$('current_tags').innerHTML=null;}},getSelectedPhotoIds:function(){alert('public/javascripts/Tagging.js#getSelectedPhotoIds - deprecated');},addToAlbum:function(){var ids=Tagging.getSelectedPhotoIds();return ids;},addAllToAlbum:function(){alert('public/javascripts/Tagging.js#addAllToAlbum - deprecated');},addAlbumPhotos:function(transport){var add_ids=transport.responseText.evalJSON();var album_id=null;add_ids.each(function(i){if(!album_id)album_id=i['album_id'];blissbook.browser.BrowserWidget.addAlbumPhoto(i['album_id'],i['photo_id'],i['album_photo_id'],true);});DragDrop.addSortable(album_id);new Effect.Highlight("album");}};var Cookie=Class.create();Cookie.prototype={initialize:function(sName){this.sName=sName||'defaultCookieName';this.nExpires=null;this.sPath='/';this.sDomain='';this.bValid=false;this.aData=$H();this.read();},read:function(){this.aData=$H();this.bValid=false;var aAll=document.cookie.split(';');var sFull='';var aFull=$A();if(aAll){var sPattern='(^'+this.sName+'=)';var oReg=new RegExp(sPattern,'g');for(var i=0;i<aAll.length;i++){if(oReg.test(aAll[i].strip())){sFull=aAll[i].strip();break;}}
if(sFull){aFull=sFull.split('=');aFull=unescape(aFull[1]);this.aData=$H(aFull.evalJSON(true));this.bValid=true;}}},setExpires:function(nExpires){var oExpDate=new Date();oExpDate.setTime(oExpDate.getTime()+nExpires);this.nExpires=oExpDate.toGMTString();},setPath:function(sPath){this.sPath=sPath;},setDomain:function(sDomain){this.sDomain=sDomain;},inspect:function(){return this.sName+":\n"+this.aData.inspect();},set:function(sName,sValue){this.aData[sName]=sValue;this.write();},get:function(sName){return(this.aData[sName]);},isValid:function(){return this.bValid;},write:function(){var sValue=this.aData.toJSON();var aCookie=$A();aCookie.push(this.sName+"="+escape(sValue)+';');if(this.nExpires)aCookie.push('expires='+this.nExpires+';');aCookie.push('path='+this.sPath+';');if(this.sDomain.length>0)aCookie.push('domain='+this.sDomain+';');document.cookie=aCookie.join('');this.bValid=true;},clear:function(){this.aData=$H();this.write();this.read();},remove:function(){this.setExpires(-1);this.write();}}
if(typeof blissbook==='undefined')
{var blissbook={};}
blissbook.namespace=function(nspace)
{if(!nspace)
{return;}
if((/(^\.|\.\.|\.$)/).test(nspace))
{throw'blissbook.namespace(): illegal namespace: '+nspace;}
var n=nspace.split('.');var o=window;for(var i=0;i<n.length;i++)
{o[n[i]]=o[n[i]]||{};o=o[n[i]];}
return o;};blissbook.namespace('blissbook.util');blissbook.util.Event=(function(){var _idCounter=0;var _listenersMap={};var _elementsMap={};var _addListener=function(element,eventType,func){element=$(element);var uid=[eventType,'_',++_idCounter].join('');_listenersMap[uid]=func;_elementsMap[uid]=element;Event.observe(element,eventType,func);return uid;};var _removeListener=function(uid){var func=_listenersMap[uid];var element=_elementsMap[uid];var eventType=uid.split('_')[0];Event.stopObserving(element,eventType,func);_listenersMap[uid]=null;_elementsMap[uid]=null;};var _delegateUntil=function(element,eventType,func){element=$(element);return _addListener(element,eventType,function(event){var target=_getTarget(event);while(target&&target!==element){if(func.call(func,target)){return;}else{target=target.parentNode;}}});};var _resolveTextNode=function(node){if(node&&3==node.nodeType){return node.parentNode;}else{return node;}};var _getTarget=function(ev){var t=ev.target||ev.srcElement;return _resolveTextNode(t);};var _getRelatedTarget=function(ev){var t=ev.relatedTarget;if(!t){if(ev.type=='mouseout'){t=ev.toElement;}else if(ev.type=='mouseover'){t=ev.fromElement;}}
return _resolveTextNode(t);};return{unsubscribe:function(uid){_removeListener(uid);},onClickDelegateUntil:function(el,func){return _delegateUntil(el,'click',func);},onMouseoverDelegateUntil:function(el,func){return _delegateUntil(el,'mouseover',func);},onMouseoutDelegateUntil:function(el,func){return _delegateUntil(el,'mouseout',func);},getTarget:function(ev){return _getTarget(ev);},getRelatedTarget:function(ev){return _getRelatedTarget(ev);}};})();blissbook.namespace('blissbook.util');blissbook.util.EffectUtils={HIGHLIGHT_IF_NOT_HIGHLIGHTED_FLAG:'blissbook_util_EffectUtils_hIfNotH',highlightIfNotHighlighted:function(el,o){var p=blissbook.util.EffectUtils.HIGHLIGHT_IF_NOT_HIGHLIGHTED_FLAG;o=o||{};el=$(el);if(!el||el[p]){return;}
var beforeStart=o.beforeStart;o.beforeStart=function(effect){el[p]=true;if(beforeStart){beforeStart.call(null,effect);}};var afterFinish=o.afterFinish;o.afterFinish=function(effect){if(afterFinish){afterFinish.call(null,effect);}
el[p]=null;};new Effect.Highlight(el,o);}};blissbook.namespace('blissbook.util');blissbook.util.LangUtils={};blissbook.util.LangUtils.isArray=function(o){if(o){var l=blissbook.util.LangUtils;return l.isNumber(o.length)&&l.isFunction(o.splice)&&l.isFunction(o.push)&&l.isFunction(o.pop);}
return false;};blissbook.util.LangUtils.isNotArray=function(o){return!blissbook.util.LangUtils.isArray(o);};blissbook.util.LangUtils.isBoolean=function(o){return typeof o==='boolean';};blissbook.util.LangUtils.isNotBoolean=function(o){return!blissbook.util.LangUtils.isBoolean(o);};blissbook.util.LangUtils.isNumber=function(o){return typeof o==='number'&&isFinite(o);};blissbook.util.LangUtils.isNotNumber=function(o){return!blissbook.util.LangUtils.isNumber(o);};blissbook.util.LangUtils.isString=function(o){return typeof o==='string';};blissbook.util.LangUtils.isNotString=function(o){return!blissbook.util.LangUtils.isString(o);};blissbook.util.LangUtils.isFunction=function(o){return typeof o==='function';};blissbook.util.LangUtils.isNotFunction=function(o){return!blissbook.util.LangUtils.isFunction(o);};blissbook.util.LangUtils.isNull=function(o){return o===null;};blissbook.util.LangUtils.isObject=function(o){return(o&&(typeof o==='object'||blissbook.util.LangUtils.isFunction(o)))||false;};blissbook.util.LangUtils.isUndefined=function(o){return typeof o==='undefined';};blissbook.util.LangUtils.isNotUndefined=function(o){return!blissbook.util.LangUtils.isUndefined(o);};blissbook.util.LangUtils.isValue=function(o){var l=blissbook.util.LangUtils;return(l.isObject(o)||l.isString(o)||l.isNumber(o)||l.isBoolean(o));};blissbook.util.LangUtils.isNotValue=function(o){return!blissbook.util.LangUtils.isValue(o);};blissbook.util.LangUtils.isCoreObject=function(f){return(f===Array||f===Boolean||f===Date||f===Error||f===EvalError||f===Function||f===Math||f===Number||f===Object||f===RangeError||f===ReferenceError||f===RegExp||f===String||f===SyntaxError||f===TypeError||f===URIError);};blissbook.util.LangUtils.hasFunction=function(o,funcName,numArgs){var self=blissbook.util.LangUtils;if(self.isFunction(o))
o=o.prototype;return(funcName in o)&&(self.isFunction(o[funcName]))&&(!self.isNumber(numArgs)||o[funcName].length===numArgs);};blissbook.util.LangUtils.doesNotHaveFunction=function(o,funcName,numArgs){return!blissbook.util.LangUtils.hasFunction(o,funcName,numArgs);};blissbook.util.LangUtils.hasInterface=function(impl,iface,ignoreArgs){var self=blissbook.util.LangUtils;if(!impl||self.isCoreObject(iface)){return false;}
if(self.isFunction(iface)){iface=iface.prototype;}
ignoreArgs=self.isBoolean(ignoreArgs)&&ignoreArgs;for(var p in iface){var method=iface[p];if(!self.isFunction(method)){continue;}
if(!self.hasFunction(impl,p,ignoreArgs?null:method.length)){return false;}}
return true;};blissbook.util.LangUtils.doesNotHaveInterface=function(impl,iface,ignoreArgs){return!blissbook.util.LangUtils.hasInterface(impl,iface,ignoreArgs);};blissbook.util.LangUtils.getMethodsNotImplemented=function(impl,iface,ignoreArgs){if(!iface){return'ERROR: interface arg was null/undefined';}
if(!impl){return'ERROR: implementation was null/undefined';}
var self=blissbook.util.LangUtils;if(self.isCoreObject(iface)){return'ERROR: interface was a core javascript object';}
if(self.isFunction(iface)){iface=iface.prototype;}
ignoreArgs=self.isBoolean(ignoreArgs)&&ignoreArgs;var result=[];for(var p in iface){var method=iface[p];if(!self.isFunction(method)){continue;}
if(!self.hasFunction(impl,p,ignoreArgs?null:method.length)){result.push(p);}}
return result.join(', ');};blissbook.util.LangUtils.toStringOrEmpty=function(o){return blissbook.util.LangUtils.isValue(o)?o+'':'';};blissbook.namespace('blissbook.util');blissbook.util.StringUtils={};blissbook.util.StringUtils.PATH_SEPARATOR='/';blissbook.util.StringUtils.EXTENSION_SEPARATOR='.';blissbook.util.StringUtils.TOP_PATH='..';blissbook.util.StringUtils.CURRENT_PATH='.';blissbook.util.StringUtils.defaultString=function(s){return blissbook.util.LangUtils.isValue(s)?s:'';};blissbook.util.StringUtils.areEqual=function(s1,s2){var l=blissbook.util.LangUtils;return!l.isValue(s1)?!l.isValue(s2):s1===s2;};blissbook.util.StringUtils.areEqualIgnoreCase=function(s1,s2){var l=blissbook.util.LangUtils;if(!l.isValue(s1)){return!l.isValue(s2);}else{return l.isValue(s2)?s1.toUpperCase()===s2.toUpperCase():false;}};blissbook.util.StringUtils.isEmpty=function(str){var l=blissbook.util.LangUtils;return l.isNotValue(str)||str.length===0;};blissbook.util.StringUtils.isNotEmpty=function(str){return!blissbook.util.StringUtils.isEmpty(str);};blissbook.util.StringUtils.isBlank=function(str){var s=blissbook.util.StringUtils;if(s.isNotEmpty(str)){return false;}
for(var i=0,n=str.length;i<n;i++){if(!s._isWhitespaceCharacter(str.charAt(i))){return false;}}
return true;};blissbook.util.StringUtils.isNotBlank=function(str){return!blissbook.util.StringUtils.isBlank(str);};blissbook.util.StringUtils.contains=function(str,sub){var l=blissbook.util.LangUtils;if(!l.isValue(str)||!l.isValue(sub)){return false;}
return str.indexOf(sub)>=0;};blissbook.util.StringUtils.containsIgnoreCase=function(str,sub){var l=blissbook.util.LangUtils;if(!l.isValue(str)||!l.isValue(sub)){return false;}
return blissbook.util.StringUtils.contains(str.toUpperCase(),sub.toUpperCase());};blissbook.util.StringUtils.containsWhitespace=function(str){var self=blissbook.util.StringUtils;if(self.isEmpty(str)){return false;}
for(var i=0,n=str.length;i<n;i++){if(self._isWhitespaceCharacter(str.charAt(i))){return true;}}
return false;};blissbook.util.StringUtils._isWhitespaceCharacter=function(c){return(/\s/).test(c);};blissbook.util.StringUtils.regionMatches=function(str,toffset,other,ooffset,len){return blissbook.util.StringUtils._regionMatches(str,toffset,other,ooffset,len,false);};blissbook.util.StringUtils.regionMatchesIgnoreCase=function(str,toffset,other,ooffset,len){return blissbook.util.StringUtils._regionMatches(str,toffset,other,ooffset,len,true);};blissbook.util.StringUtils._regionMatches=function(str,toffset,other,ooffset,len,ignoreCase){var l=blissbook.util.LangUtils;if(!l.isValue(str)||!l.isValue(other)){return!l.isValue(str)&&!l.isValue(other);}
if(toffset<0||ooffset<0){return false;}
if(str.length<toffset+len||other.length<ooffset+len){return false;}
var self=blissbook.util.StringUtils;var s1=str.substring(toffset,toffset+len);var s2=other.substring(ooffset,ooffset+len);return ignoreCase?self.areEqualIgnoreCase(s1,s2):self.areEqual(s1,s2);};blissbook.util.StringUtils.startsWith=function(str,prefix){return blissbook.util.StringUtils._startsWith(str,prefix,false);};blissbook.util.StringUtils.startsWithIgnoreCase=function(str,prefix){return blissbook.util.StringUtils._startsWith(str,prefix,true);};blissbook.util.StringUtils._startsWith=function(str,prefix,ignoreCase){var l=blissbook.util.LangUtils;if(!l.isValue(str)||!l.isValue(prefix)){return(!l.isValue(str)&&!l.isValue(prefix));}
if(prefix.length>str.length){return false;}
var self=blissbook.util.StringUtils;if(ignoreCase){return self.regionMatchesIgnoreCase(str,0,prefix,0,prefix.length);}else{return self.regionMatches(str,0,prefix,0,prefix.length);}};blissbook.util.StringUtils.endsWith=function(str,suffix){return blissbook.util.StringUtils._endsWith(str,suffix,false);};blissbook.util.StringUtils.endsWithIgnoreCase=function(str,suffix){return blissbook.util.StringUtils._endsWith(str,suffix,true);};blissbook.util.StringUtils._endsWith=function(str,suffix,ignoreCase){var l=blissbook.util.LangUtils;if(!l.isValue(str)||!l.isValue(suffix)){return!l.isValue(str)&&!l.isValue(suffix);}
if(suffix.length>str.length){return false;}
var self=blissbook.util.StringUtils;var offset=str.length-suffix.length;if(ignoreCase){return self.regionMatchesIgnoreCase(str,offset,suffix,0,suffix.length);}else{return self.regionMatches(str,offset,suffix,0,suffix.length);}};blissbook.util.StringUtils.trimToEmpty=function(str){return blissbook.util.StringUtils.trimWhitespace(str)||'';};blissbook.util.StringUtils.trimWhitespace=function(str){if(blissbook.util.StringUtils.isEmpty(str)){return str;}
return str.replace(/^\s+|\s+$/g,'');};blissbook.util.StringUtils.trimAllWhitespace=function(str){var self=blissbook.util.StringUtils;if(self.isEmpty(str)){return str;}
var sb=[];for(var i=0,n=str.length;i<n;i++){if(!self._isWhitespaceCharacter(str.charAt(i))){sb.push(str.charAt(i));}}
return sb.join('');};blissbook.util.StringUtils.trimLeadingWhitespace=function(str){if(blissbook.util.StringUtils.isEmpty(str)){return str;}
return str.replace(/^\s+/g,'');};blissbook.util.StringUtils.trimTrailingWhitespace=function(str){if(blissbook.util.StringUtils.isEmpty(str)){return str;}
return str.replace(/\s+$/g,'');};blissbook.util.StringUtils.trimTokens=function(s,d){var SU=blissbook.util.StringUtils;s=SU.defaultString(s);if(SU.isEmpty(d)){return s;}
var a=s.split(d);var sb=[];for(var i=0,n=a.length;i<n;i++){a[i]=SU.trimWhitespace(a[i]);if(SU.isNotEmpty(a[i])){sb.push(a[i]);}}
return sb.join(d);};blissbook.util.StringUtils.removeStart=function(str,remove){var self=blissbook.util.StringUtils;if(self.isEmpty(str)||self.isEmpty(remove)){return str;}
if(self.startsWith(str,remove)){return str.substring(remove.length);}
return str;};blissbook.util.StringUtils.removeStartIgnoreCase=function(str,remove){var self=blissbook.util.StringUtils;if(self.isEmpty(str)||self.isEmpty(remove)){return str;}
if(self.startsWithIgnoreCase(str,remove)){return str.substring(remove.length);}
return str;};blissbook.util.StringUtils.removeEnd=function(str,remove){var self=blissbook.util.StringUtils;if(self.isEmpty(str)||self.isEmpty(remove)){return str;}
if(self.endsWith(str,remove)){return str.substring(0,str.length-remove.length);}
return str;};blissbook.util.StringUtils.removeEndIgnoreCase=function(str,remove){var self=blissbook.util.StringUtils;if(self.isEmpty(str)||self.isEmpty(remove)){return str;}
if(self.endsWithIgnoreCase(str,remove)){return str.substring(str,str.length-remove.length);}
return str;};blissbook.util.StringUtils.capitalize=function(str){return blissbook.util.StringUtils._changeFirstCharacter(str,true);};blissbook.util.StringUtils.uncapitalize=function(str){return blissbook.util.StringUtils._changeFirstCharacter(str,false);};blissbook.util.StringUtils._changeFirstCharacter=function(str,capitalize){if(blissbook.util.StringUtils.isEmpty(str)){return str;}
if(capitalize){return str.replace(/^\w/,function(c){return c.toUpperCase();});}
else{return str.replace(/^\w/,function(c){return c.toLowerCase();});}};blissbook.util.StringUtils.getFilename=function(path){var self=blissbook.util.StringUtils;if(self.isEmpty(path)){return path;}
var separatorIndex=path.lastIndexOf(self.PATH_SEPARATOR);return(separatorIndex!==-1?path.substring(separatorIndex+1):path);};blissbook.util.StringUtils.getFilenameExtension=function(path){var self=blissbook.util.StringUtils;if(self.isEmpty(path)){return path;}
var sepIndex=path.lastIndexOf(self.EXTENSION_SEPARATOR);return(sepIndex!==-1?path.substring(sepIndex+1):null);};blissbook.util.StringUtils.stripFilenameExtension=function(path){var self=blissbook.util.StringUtils;if(self.isEmpty(path)){return path;}
var sepIndex=path.lastIndexOf(self.EXTENSION_SEPARATOR);return(sepIndex!==-1?path.substring(0,sepIndex):path);};blissbook.util.StringUtils.joinPath=function(base,pathToAdd){var self=blissbook.util.StringUtils;if(self.isEmpty(base)){return self.isNotEmpty(pathToAdd)?pathToAdd:'';}
if(self.isEmpty(pathToAdd)){return self.isNotEmpty(base)?base:'';}
var sep=self.PATH_SEPARATOR;return[self.removeEnd(base,sep),sep,self.removeStart(pathToAdd,sep)].join('');};blissbook.util.StringUtils.countOccurrencesOf=function(str,sub){var self=blissbook.util.StringUtils;if(self.isEmpty(str)||self.isEmpty(sub)){return 0;}
var count=0,pos=0,idx=0;while((idx=str.indexOf(sub,pos))!==-1){++count;pos=idx+sub.length;}
return count;};blissbook.util.StringUtils.deleteAny=function(inString,charsToDelete){var self=blissbook.util.StringUtils;if(self.isEmpty(inString)||self.isEmpty(charsToDelete)){return inString;}
var sb=[];for(var i=0,n=inString.length;i<n;i++){var c=inString.charAt(i);if(!self.contains(charsToDelete,c)){sb.push(c);}}
return sb.join('');};blissbook.namespace('blissbook.util');blissbook.util.StringEscapeUtils={};blissbook.util.StringEscapeUtils.escapeXML=function(str)
{if(blissbook.util.StringUtils.isEmpty(str)){return str;}
var sb=[];for(var i=0,n=str.length;i<n;i++){var c=str.charAt(i);if('<'===c){sb.push('&lt;');}else if('>'===c){sb.push('&gt;');}else if('&'===c){sb.push('&amp;');}else if('"'===c){sb.push('&quot;');}else if("'"===c){sb.push('&apos;');}else{sb.push(c);}}
return sb.join('');};blissbook.util.StringEscapeUtils.unescapeXML=function(str)
{var u=blissbook.util.StringUtils;if(u.isEmpty(str)){return str;}
var sb=[];var i=0;var n=str.length;while(i<n){if(u.regionMatches(str,i,'&lt;',0,4)){sb.push('<');i+=4;}else if(u.regionMatches(str,i,'&gt;',0,4)){sb.push('>');i+=4;}else if(u.regionMatches(str,i,'&amp;',0,5)){sb.push('&');i+=5;}else if(u.regionMatches(str,i,'&quot;',0,6)){sb.push('"');i+=6;}else if(u.regionMatches(str,i,'&apos;',0,6)){sb.push("'");i+=6;}else{sb.push(str.charAt(i));i++;}}
return sb.join('');};blissbook.namespace('blissbook.util');blissbook.util.Assert={isTrue:function(expression,message){blissbook.util.Assert.isBoolean(expression,'blissbook.utilAssert.isTrue: expression must be a primitive boolean '+expression);if(!expression){throw new Error(message||'[Assertion failed] - this expression must be true');}},isValue:function(obj,message){if(blissbook.util.LangUtils.isNotValue(obj)){throw new Error(message||'[Assertion failed] - this object cannot be null/undefined/NaN');}},allValues:function(values,message){values=values||[];message=message||'';var l=blissbook.util.LangUtils;for(var i=0,n=values.length;i<n;i++){if(l.isNotValue(values[i])){throw new Error(message+'[Assertion failed] - the object at index '+i+' cannot be null/undefined/NaN');}}},isInstanceOf:function(obj,clazz,message){blissbook.util.Assert.isValue(clazz,'blissbook.util.Assert.isValue: Class to check against must not be null/undefined/NaN');if(!(obj instanceof clazz)){throw new Error(message||'[Assertion failed] this object must be an instance of the provided class. object: '+obj+' class: '+clazz);}},isTypeOf:function(obj,type,message){if(typeof obj!==type){throw new Error(message||'[Assertion failed] - the object must a type of '+type);}},isArray:function(obj,message){if(blissbook.util.LangUtils.isNotArray(obj)){throw new Error(message||'[Assertion failed] - this object must be an array. '+obj);}},isBoolean:function(obj,message){if(blissbook.util.LangUtils.isNotBoolean(obj)){throw new Error(message||'[Assertion failed] - this object must be a primitive boolean. object: '+obj);}},isNumber:function(obj,message){if(blissbook.util.LangUtils.isNotNumber(obj)){throw new Error(message||'[Assertion failed] - this object must be a primitive number. object: '+obj);}},isString:function(obj,message){if(blissbook.util.LangUtils.isNotString(obj)){throw new Error(message||'[Assertion failed] - this object must be a primitive string. object: '+obj);}},isFunction:function(o,message){if(blissbook.util.LangUtils.isNotFunction(o)){throw new Error(message||'[Assertion failed] - this object must be a function '+o);}},hasFunction:function(obj,funcName,numArgs,message){blissbook.util.Assert.isNumber(numArgs,'[Assertion failed] - must specify numArgs or use hasFunctionIgnoreArgs');if(blissbook.util.LangUtils.doesNotHaveFunction(obj,funcName,numArgs)){throw new Error(message||'[Assertion failed] - this object must implement '+funcName);}},hasFunctionIgnoreArgs:function(obj,funcName,message){if(blissbook.util.LangUtils.doesNotHaveFunction(obj,funcName,null)){throw new Error(message||'[Assertion failed] - this object must implement '+funcName);}},hasInterface:function(impl,iface,message){if(blissbook.util.LangUtils.doesNotHaveInterface(impl,iface,false)){var methods=blissbook.util.LangUtils.getMethodsNotImplemented(impl,iface,false);throw new Error(message||''+'[Assertion failed] - this object does not implement the provided interface. Missing: '+methods);}},hasInterfaceIgnoreArgs:function(impl,iface,message){if(!blissbook.util.LangUtils.hasInterface(impl,iface,true)){var methods=blissbook.util.LangUtils.getMethodsNotImplemented(impl,iface,true);throw new Error(message||''+'[Assertion failed] - this object does not implement the provided interface. Missing: '+methods);}},notEmpty:function(text,message){var m='[Assertion failed] - this string must have length; it must not be null, undefined or empty';blissbook.util.Assert.isString(text,message||m);if(blissbook.util.StringUtils.isEmpty(text)){throw new Error(message||m);}},notBlank:function(text,message){var m='[Assertion failed] - this string must have text; it must not be null, undefined or blank.';blissbook.util.Assert.isString(text,message||m);if(blissbook.util.StringUtils.isBlank(text)){throw new Error(message||m);}},id:function(id,message){blissbook.util.Assert.isValue(document.getElementById(id),message||'[Assertion failed] - no such element with id: '+id);}};blissbook.namespace('blissbook.util');blissbook.util.RequestQueue=function(limit){limit=parseInt(limit);if(blissbook.util.LangUtils.isNumber(limit)){blissbook.util.Assert.isTrue(limit>0,'RequestQueue.constructor: limit '+limit);}
this.QUEUE_LIMIT=limit||20;this._queue=[];this._isRequestInProgress=false;};blissbook.util.RequestQueue.prototype={add:function(url,o){if(!url){return;}
if(this._queue.length>this.QUEUE_LIMIT){alert('Too many requests');return;}
o=o||{};if(this._isRequestInProgress){this._queue.push({url:url,o:o});}else{this._fireRequest(url,o);}},_fireRequest:function(url,o){this._isRequestInProgress=true;var f=o.onComplete;o.onComplete=function(http,xjson){if(f)f(http,xjson);this._advanceQueue();}.bind(this);new Ajax.Request(url,o);},_advanceQueue:function(){if(this._queue.length===0){this._isRequestInProgress=false;return;}
var params=this._queue.shift();this._fireRequest(params.url,params.o);}};blissbook.namespace('blissbook.browser.dao');blissbook.browser.dao.IPhotoDAO={rotatePhoto:function(serverId,degrees,o){throw'IPhotoDAO.rotatePhoto: abstract method';},getPage:function(pageNum,o){throw'IPhotoDAO.getPage: abstract method';},deletePhoto:function(serverId,pageNum,o){throw'IPhotoDAO.deletePhoto: abstract method';},markPhotoAsBlurry:function(serverId,o){throw'IPhotoDAO.markPhotoAsBlurry: abstract method';},markPhotoAsExplicit:function(serverId,o){throw'IPhotoDAO.markPhotoAsExplicit: abstract method';},updatePhotoDescription:function(serverId,desc,o){throw'IPhotoDAO.updatePhotoDescription: abstract method';},updatePhotoTitle:function(serverId,title,o){throw'IPhotoDAO.updatePhotoTitle: abstract method';},updatePhotoPrivacy:function(serverId,isPrivate,o){throw'IPhotoDAO.updatePhotoPrivacy: abstract method';},addTags:function(serverId,tags,o){throw'IPhotoDAO.addTags: abstract method';},confirmTags:function(serverId,tags,o){throw'IPhotoDAO.confirmTags: abstract method';},removeTag:function(serverId,tag,o){throw'IPhotoDAO.removeTag: abstract method';},removeIdeaTag:function(serverId,tag,o){},updateIdea:function(serverId,ideaNotes,ideaTags,resourceType,o){},removeAllIdeas:function(serverId,pageNum,o){}};blissbook.namespace('blissbook.browser.dao.impl');blissbook.browser.dao.impl.AbstractPhotoDAO=Class.create();blissbook.browser.dao.impl.AbstractPhotoDAO.prototype={initialize:function(){},rotatePhoto:function(serverId,degrees,o){blissbook.util.Assert.isFunction(o.callback,'AbstractPhotoDAO.rotatePhoto: no callback');this.post('/browser/rotate',{params:{degrees:degrees,photo_id:serverId},callback:function(http){o.callback(http.responseText);},errback:o.errback});},markPhotoAsBlurry:function(serverId,o){blissbook.util.Assert.isFunction(o.callback,'AbstractPhotoDAO.markPhotoAsBlurry: no callback');this.post('/browser/blurry',{params:{photo_id:serverId},callback:function(http){o.callback(http.responseText);},errback:o.errback});},markPhotoAsExplicit:function(serverId,o){blissbook.util.Assert.isFunction(o.callback,'AbstractPhotoDAO.markPhotoAsExplicit: no callback');this.post('/browser/explicit',{params:{photo_id:serverId},callback:function(http){o.callback(http.responseText);},errback:o.errback});},updatePhotoDescription:function(serverId,desc,o){blissbook.util.Assert.isFunction(o.callback,'AbstractPhotoDAO.updatePhotoDescription: no callback');this.post('/browser/update_description',{params:{description:desc,photo_id:serverId},callback:function(http){o.callback(http.responseText);},errback:o.errback});},updatePhotoTitle:function(serverId,title,o){blissbook.util.Assert.isFunction(o.callback,'AbstractPhotoDAO.updatePhotoTitle: no callback');this.post('/browser/update_title',{params:{title:title,photo_id:serverId},callback:function(http){o.callback(http.responseText);},errback:o.errback});},updatePhotoPrivacy:function(serverId,isPrivate,o){blissbook.util.Assert.isFunction(o.callback,'AbstractPhotoDAO.updatePhotoPrivacy: no callback');this.post('/browser/update_privacy',{params:{is_private:isPrivate,photo_id:serverId},callback:function(http){o.callback(http.responseText.strip().toLowerCase()==='true');},errback:o.errback});},updatePhotoProfessional:function(serverId,isProfessional,o){blissbook.util.Assert.isFunction(o.callback,'AbstractPhotoDAO.updateProfessional: no callback');this.post('/browser/update_professional',{params:{photo_id:serverId,professional:isProfessional},callback:function(http){var h=http.responseText.evalJSON();o.callback({isPro:h.is_pro,vendors:blissbook.browser.domain.Vendor.toVendors(h.vendors,h.listings)});},errback:o.errback});},addTags:function(serverId,tags,o){var Assert=blissbook.util.Assert;Assert.isFunction(o.callback,'AbstractPhotoDAO.addTags: no callback');Assert.notBlank(tags,'AbstractPhotoDAO.addTags: blank tags');this.post('/browser/add_tags',{params:{tags:tags,photo_id:serverId},callback:function(http){var h=http.responseText.evalJSON();o.callback({tags:h.tags,vendors:blissbook.browser.domain.Vendor.toVendors(h.vendors,h.listings)});},errback:o.errback});},confirmTags:function(serverId,tags,o){var Assert=blissbook.util.Assert;Assert.isFunction(o.callback,'AbstractPhotoDAO.confirmTags: no callback');Assert.notBlank(tags,'AbstractPhotoDAO.confirmTags: blank tags');this.post('/browser/confirm_tags',{params:{tags:tags,photo_id:serverId},callback:function(http){o.callback();},errback:o.errback});},removeTag:function(serverId,tag,o){var Assert=blissbook.util.Assert;Assert.isFunction(o.callback,'AbstractPhotoDAO.removeTag: no callback');Assert.notBlank(tag,'AbstractPhotoDAO.removeTag: blank tags');this.post('/browser/remove_tag',{params:{tag:tag,photo_id:serverId},callback:function(http){var h=http.responseText.evalJSON();o.callback({tags:h.tags,vendors:blissbook.browser.domain.Vendor.toVendors(h.vendors,h.listings)});},errback:o.errback});},removeIdeaTag:function(serverId,tag,o){blissbook.util.Assert.isFunction(o.callback,'AbstractPhotoDAO.removeIdeaTag: no callback');blissbook.util.Assert.notBlank(tag,'AbstractPhotoDAO.removeIdeaTag: blank tag');this.post('/browser/remove_idea_tag',{params:{tag:tag,photo_id:serverId},callback:function(http){o.callback(http.responseText.evalJSON());},errback:o.errback});},updateIdea:function(serverId,ideaNotes,ideaTags,resourceType,o){this.post('/browser/update_idea',{params:{resource_id:serverId,resource_type:resourceType,notes:ideaNotes,tag_names:ideaTags},callback:function(http){var p=new blissbook.browser.domain.Photo(http.responseText.evalJSON());o.callback(p);},errback:o.errback});},removeAllIdeas:function(serverId,pageNum,o){this.post('/browser/remove_all_ideas',{params:{resource_id:serverId,page:pageNum},callback:function(http){o.callback({pageNeedsUpdating:false,photos:null,totalPages:null});},errback:o.errback});},getPage:function(pageNum,o){throw'AbstractPhotoDAO.getPage: abstract method must be overidden';},deletePhoto:function(serverId,pageNum,o){throw'AbstractPhotoDAO.deletePhoto: abstract method must be overidden';},post:function(url,o){blissbook.util.Assert.isString(url,'AbstractPhotoDAO.post: url '+url);o=o||{};blissbook.browser.event.EventBus.fireProgressChange(true);this._getRequestQueue().add(url,{method:'post',parameters:o.params,onSuccess:function(http){blissbook.browser.event.EventBus.fireProgressChange(false);if(o.callback){o.callback(http);}},onFailure:function(http){blissbook.browser.event.EventBus.fireProgressChange(false);if(o.errback){o.errback(http.statusText);}},onException:function(req,ex){blissbook.browser.event.EventBus.fireProgressChange(false);if(typeof console!=='undefined'){console.error(ex);}else{alert('Error: '+ex.message);}}});},_getRequestQueue:function(){var queue=new blissbook.util.RequestQueue();this._getRequestQueue=function(){return queue;};return queue;}};blissbook.namespace('blissbook.browser.dao.impl');blissbook.browser.dao.impl.AlbumScopedPhotoDAO=Class.create();blissbook.browser.dao.impl.AlbumScopedPhotoDAO.prototype=Object.extend(new blissbook.browser.dao.impl.AbstractPhotoDAO(),{initialize:function(albumId){this._albumId=albumId;},getPage:function(pageNum,o){var Assert=blissbook.util.Assert;Assert.isTrue(pageNum>=1,'AlbumScopedPhotoDAO.getPage: pageNum '+pageNum);Assert.isFunction(o.callback,'AlbumScopedPhotoDAO.getPage: no callback');var albumId=this._albumId;this.post('/browser/find_page_by_album_id',{params:{page:pageNum,album_id:albumId},callback:function(http){var h=http.responseText.evalJSON();var photos=blissbook.browser.domain.Photo.toPhotos(h['metadata']);o.callback({photos:photos,totalPages:parseInt(h['total_pages'])});},errback:o.errback});},deletePhoto:function(serverId,pageNum,o){var Assert=blissbook.util.Assert;Assert.isTrue(pageNum>=1,'AlbumScopedPhotoDAO.deletePhoto: pageNum '+pageNum);Assert.isFunction(o.callback,'AlbumScopedPhotoDAO.deletePhoto: no callback');var albumId=this._albumId;this.post('/browser/delete_photo_and_find_page_by_album_id',{params:{page:pageNum,album_id:albumId,photo_id:serverId},callback:function(http){var h=http.responseText.evalJSON();var photos=blissbook.browser.domain.Photo.toPhotos(h['metadata']);o.callback({photos:photos,totalPages:parseInt(h['total_pages'])});},errback:o.errback});}});blissbook.namespace('blissbook.browser.dao.impl');blissbook.browser.dao.impl.UserScopedIdeasBookDAO=Class.create();blissbook.browser.dao.impl.UserScopedIdeasBookDAO.prototype=Object.extend(new blissbook.browser.dao.impl.AbstractPhotoDAO(),{initialize:function(userId){this._userId=userId;},getPage:function(pageNum,o){var Assert=blissbook.util.Assert;Assert.isTrue(pageNum>=1,'UserScopedIdeasBookDAO.getPage: pageNum '+pageNum);Assert.isFunction(o.callback,'UserScopedIdeasBookDAO.getPage: no callback');var userId=this._userId;this.post('/browser/find_page_by_ideasbook_user',{params:{page:pageNum,user_id:userId},callback:function(http){var h=http.responseText.evalJSON();var photos=blissbook.browser.domain.Photo.toPhotos(h['metadata']);o.callback({photos:photos,totalPages:parseInt(h['total_pages'])});},errback:o.errback});},deletePhoto:function(serverId,pageNum,o){throw'UserScopedIdeasBookDAO.deletePhoto: unsupported operation';},removeAllIdeas:function(serverId,pageNum,o){var userId=this._userId;this.post('/browser/remove_all_ideas_and_find_page_by_ideasbook_user',{params:{page:pageNum,user_id:userId,resource_id:serverId},callback:function(http){var h=http.responseText.evalJSON();o.callback({pageNeedsUpdating:true,photos:blissbook.browser.domain.Photo.toPhotos(h['metadata']),totalPages:parseInt(h['total_pages'])})}});}})
blissbook.namespace('blissbook.browser.dao.impl');blissbook.browser.dao.impl.UserScopedPhotoDAO=Class.create();blissbook.browser.dao.impl.UserScopedPhotoDAO.prototype=Object.extend(new blissbook.browser.dao.impl.AbstractPhotoDAO(),{initialize:function(userId){this._userId=userId;},getPage:function(pageNum,o){var Assert=blissbook.util.Assert;Assert.isTrue(pageNum>=1,'UserScopedPhotoDAO.getPage: pageNum '+pageNum);Assert.isFunction(o.callback,'UserScopedPhotoDAO.getPage: no callback');var userId=this._userId;this.post('/browser/find_page_by_user_id',{params:{page:pageNum,user_id:userId},callback:function(http){var h=http.responseText.evalJSON();var photos=blissbook.browser.domain.Photo.toPhotos(h['metadata']);o.callback({photos:photos,totalPages:parseInt(h['total_pages'])});},errback:o.errback});},deletePhoto:function(serverId,pageNum,o){var Assert=blissbook.util.Assert;Assert.isTrue(pageNum>=1,'UserScopedPhotoDAO.deletePhoto: pageNum '+pageNum);Assert.isFunction(o.callback,'UserScopedPhotoDAO.deletePhoto: no callback');var userId=this._userId;this.post('/browser/delete_photo_and_find_page_by_user_id',{params:{page:pageNum,user_id:userId,photo_id:serverId},callback:function(http){var h=http.responseText.evalJSON();var photos=blissbook.browser.domain.Photo.toPhotos(h['metadata']);o.callback({photos:photos,totalPages:parseInt(h['total_pages'])});},errback:o.errback});}});blissbook.namespace('blissbook.browser.dao.impl');blissbook.browser.dao.impl.TagScopedIdeasBookDAO=Class.create();blissbook.browser.dao.impl.TagScopedIdeasBookDAO.prototype=Object.extend(new blissbook.browser.dao.impl.AbstractPhotoDAO(),{initialize:function(tag){this._tag=tag||'';},getPage:function(pageNum,o){var Assert=blissbook.util.Assert;Assert.isTrue(pageNum>=1,'TagScopedIdeasBookDAO.getPage: pageNum '+pageNum);Assert.isFunction(o.callback,'TagScopedIdeasBookDAO.getPage: no callback');var tag=this._tag;this.post('/browser/find_page_by_ideasbook_tag',{params:{page:pageNum,tag:tag},callback:function(http){var h=http.responseText.evalJSON();var photos=blissbook.browser.domain.Photo.toPhotos(h['metadata']);o.callback({photos:photos,totalPages:parseInt(h['total_pages'])});},errback:o.errback});},deletePhoto:function(serverId,pageNum,o){throw'TagScopedIdeasBookDAO.deletePhoto: unsupported operation';},removeAllIdeas:function(serverId,pageNum,o){var tag=this._tag;this.post('/browser/remove_all_ideas_and_find_page_by_ideas_book_tag',{params:{page:pageNum,tag:tag,resource_id:serverId},callback:function(http){var h=http.responseText.evalJSON();o.callback({pageNeedsUpdating:true,photos:blissbook.browser.domain.Photo.toPhotos(h['metadata']),totalPages:parseInt(h['total_pages'])});},errback:o.errback});}});blissbook.namespace('blissbook.browser.dao.impl');blissbook.browser.dao.impl.TagScopedPhotoDAO=Class.create();blissbook.browser.dao.impl.TagScopedPhotoDAO.prototype=Object.extend(new blissbook.browser.dao.impl.AbstractPhotoDAO(),{initialize:function(tag,sortBy){this._tag=tag||'';this._sortBy=sortBy;},getPage:function(pageNum,o){var Assert=blissbook.util.Assert;Assert.isTrue(pageNum>=1,'TagScopedPhotoDAO.getPage: pageNum '+pageNum);Assert.isFunction(o.callback,'TagScopedPhotoDAO.getPage: no callback');var self=this;this.post('/browser/find_page_by_tag',{params:{page:pageNum,tag:self._tag,sort_by:self._sortBy},callback:function(http){var h=http.responseText.evalJSON();var photos=blissbook.browser.domain.Photo.toPhotos(h['metadata']);o.callback({photos:photos,totalPages:parseInt(h['total_pages'])});},errback:o.errback});},deletePhoto:function(serverId,pageNum,o){var Assert=blissbook.util.Assert;Assert.isTrue(pageNum>=1,'TagScopedPhotoDAO.deletePhoto: pageNum '+pageNum);Assert.isFunction(o.callback,'TagScopedPhotoDAO.deletePhoto: no callback');var self=this;this.post('/browser/delete_photo_and_find_page_by_tag',{params:{page:pageNum,tag:self._tag,sort_by:self._sortBy,photo_id:serverId},callback:function(http){var h=http.responseText.evalJSON();var photos=blissbook.browser.domain.Photo.toPhotos(h['metadata']);o.callback({photos:photos,totalPages:parseInt(h['total_pages'])});},errback:o.errback});}});blissbook.namespace('blissbook.browser.dao.impl');blissbook.browser.dao.impl.TextSearchScopedIdeasBookDAO=Class.create();blissbook.browser.dao.impl.TextSearchScopedIdeasBookDAO.prototype=Object.extend(new blissbook.browser.dao.impl.AbstractPhotoDAO(),{initialize:function(query){this._query=query||'';},getPage:function(pageNum,o){var Assert=blissbook.util.Assert;Assert.isTrue(pageNum>=1,'TextSearchScopedPhotoDAO.getPage: pageNum '+pageNum);Assert.isFunction(o.callback,'TextSearchScopedPhotoDAO.getPage: no callback');var query=this._query;this.post('/browser/find_page_by_ideasbook_text_search',{params:{page:pageNum,query:query},callback:function(http){var h=http.responseText.evalJSON();var photos=blissbook.browser.domain.Photo.toPhotos(h['metadata']);o.callback({photos:photos,totalPages:parseInt(h['total_pages'])});},errback:o.errback});},deletePhoto:function(serverId,pageNum,o){throw'TextSearchScopedIdeasBookDAO.deletePhoto: unsupported operation';},removeAllIdeas:function(serverId,pageNum,o){var query=this._query;this.post('/browser/remove_all_ideas_and_find_page_by_ideasbook_text_search',{params:{page:pageNum,query:query,resource_id:serverId},callback:function(http){var h=http.responseText.evalJSON();var photos=blissbook.browser.domain.Photo.toPhotos(h['metadata']);o.callback({pageNeedsUpdating:true,photos:photos,totalPages:parseInt(h['total_pages'])});},errback:o.errback});}});blissbook.namespace('blissbook.browser.dao.impl');blissbook.browser.dao.impl.TextSearchScopedPhotoDAO=Class.create();blissbook.browser.dao.impl.TextSearchScopedPhotoDAO.prototype=Object.extend(new blissbook.browser.dao.impl.AbstractPhotoDAO(),{initialize:function(query,sortBy){sortBy=sortBy.toLowerCase();blissbook.util.Assert.isTrue(['id','score','ideas_count'].include(sortBy),'TextSearchScopedPhotoDAO.initialize: sortBy '+sortBy);this._query=query;this._sortBy=sortBy;},getPage:function(pageNum,o){var Assert=blissbook.util.Assert;Assert.isTrue(pageNum>=1,'TextSearchScopedPhotoDAO.getPage: pageNum '+pageNum);Assert.isFunction(o.callback,'TextSearchScopedPhotoDAO.getPage: no callback');var self=this;this.post('/browser/find_page_by_text_search',{params:{page:pageNum,query:self._query,sort_by:self._sortBy},callback:function(http){var h=http.responseText.evalJSON();var photos=blissbook.browser.domain.Photo.toPhotos(h['metadata']);o.callback({photos:photos,totalPages:parseInt(h['total_pages'])});},errback:o.errback});},deletePhoto:function(serverId,pageNum,o){var Assert=blissbook.util.Assert;Assert.isTrue(pageNum>=1,'TextSearchScopedPhotoDAO.deletePhoto: pageNum '+pageNum);Assert.isFunction(o.callback,'TextSearchScopedPhotoDAO.deletePhoto: no callback');var self=this;this.post('/browser/delete_photo_and_find_page_by_text_search',{params:{query:self._query,page:pageNum,sort_by:self._sortBy,photo_id:serverId},callback:function(http){var h=http.responseText.evalJSON();var photos=blissbook.browser.domain.Photo.toPhotos(h['metadata']);o.callback({photos:photos,totalPages:parseInt(h['total_pages'])});},errback:o.errback});}});blissbook.namespace('blissbook.browser.dao.impl');blissbook.browser.dao.impl.WeddingScopedPhotoDAO=Class.create();blissbook.browser.dao.impl.WeddingScopedPhotoDAO.prototype=Object.extend(new blissbook.browser.dao.impl.AbstractPhotoDAO(),{initialize:function(weddingId){this._weddingId=weddingId;},getPage:function(pageNum,o){var Assert=blissbook.util.Assert;Assert.isTrue(pageNum>=1,'WeddingScopedPhotoDAO.getPage: pageNum '+pageNum);Assert.isFunction(o.callback,'WeddingScopedPhotoDAO.getPage: no callback');var weddingId=this._weddingId;this.post('/browser/find_page_by_wedding_id',{params:{page:pageNum,wedding_id:weddingId},callback:function(http){var h=http.responseText.evalJSON();var photos=blissbook.browser.domain.Photo.toPhotos(h['metadata']);o.callback({photos:photos,totalPages:parseInt(h['total_pages'])});},errback:o.errback});},deletePhoto:function(serverId,pageNum,o){var Assert=blissbook.util.Assert;Assert.isTrue(pageNum>=1,'WeddingScopedPhotoDAO.deletePhoto: pageNum '+pageNum);Assert.isFunction(o.callback,'WeddingScopedPhotoDAO.deletePhoto: no callback');var weddingId=this._weddingId;this.post('/browser/delete_photo_and_find_page_by_wedding_id',{params:{page:pageNum,wedding_id:weddingId,photo_id:serverId},callback:function(http){var h=http.responseText.evalJSON();var photos=blissbook.browser.domain.Photo.toPhotos(h['metadata']);o.callback({photos:photos,totalPages:h['total_pages']});},errback:o.errback});}});blissbook.namespace('blissbook.browser.domain');blissbook.browser.domain.Photo=function(to){to=to||{};this._canEdit=to.can_edit||false;this._canEditIdea=to.can_edit_idea||false;this._createdString=to.created_str;this._description=to.description;this._domId=to.dom_id;this._fileLocation=to.file_location;this._fileName=to.file_name;this._hasIdea=to.has_idea||false;this._homePage=to.homepage;this._ideaNotes=to.idea_notes;this._ideaTags=to.idea_tags||[];this._ideaType=to.idea_type;this._serverId=parseInt(to.id);this._ownerId=parseInt(to.owner_id);this._ownerName=to.owner_name;this._isPrivate=to.is_private||false;this._isProfessional=to.professional||false;this._tags=to.tags||[];this._title=to.title;this._url=to.url;this._vendorId=parseInt(to.vendorId);this._vendors=blissbook.browser.domain.Vendor.toVendors(to.vendors,to.listings);this._weddingId=parseInt(to.wedding_id);this._xml;};blissbook.browser.domain.Photo.toPhotos=function(transferObjects){transferObjects=transferObjects||[];var result=[];for(var i=0,n=transferObjects.length;i<n;i++){result.push(new blissbook.browser.domain.Photo(transferObjects[i]));}
return result;};blissbook.browser.domain.Photo.prototype={canEdit:function(){return this._canEdit;},setDescription:function(s){this._markDirty();this._description=s;},setFileName:function(s){this._markDirty();this._fileName=s;this._updateUrl(s);},removeAllIdeas:function(){this._markDirty();this._hasIdea=false;this._canEditIdea=false;this._ideaTags=[];},isPrivate:function(){return this._isPrivate;},setPrivate:function(b){this._markDirty();this._isPrivate=b||false;},setProfessional:function(b){this._markDirty();this._isProfessional=b||false;},getServerId:function(){return this._serverId;},setTags:function(tags){this._markDirty();this._tags=tags||[];},setIdeaTags:function(tags){this._markDirty();this._ideaTags=tags||[];},getTitle:function(){return this._title;},setTitle:function(s){this._markDirty();this._title=s;},setVendors:function(vendors){this._markDirty();this._vendors=vendors||[];},_updateUrl:function(fileName){this._markDirty();var i=this._url.lastIndexOf('/');this._url=this._url.substring(0,i+1)+fileName;},getThumbnailImageURL:function(){return['/images/',this._fileLocation,'thumb/',this._fileName].join('');},getSmallImageURL:function(){return['/images/',this._fileLocation,'small/',this._fileName].join('');},getMediumImageURL:function(){return['/images/',this._fileLocation,'medium/',this._fileName].join('');},toTransferObject:function(){var o={};o.can_edit=this._canEdit;o.can_edit_idea=this._canEditIdea;o.created_str=this._createdString;o.description=this._description;o.dom_id=this._domId;o.file_location=this._fileLocation;o.file_name=this._fileName;o.has_idea=this._hasIdea;o.homepage=this._homePage;o.idea_notes=this._ideaNotes;o.idea_type=this._ideaType;o.idea_tags=this._ideaTags.clone();o.id=this._serverId;o.owner_id=this._ownerId;o.owner_name=this._ownerName;o.is_private=this._isPrivate;o.professional=this._isProfessional;o.tags=this._tags.clone();o.title=this._title;o.url=this._url;o.vendorId=this._vendorId;o.vendors=[];o.listings=[];for(var i=0,n=this._vendors.length;i<n;i++){o.vendors.push(this._vendors[i].toVendorTO());o.listings.push(this._vendors[i].toListingTO());}
o.wedding_id=this._weddingId;return o;},toString:function(){var sb=[];sb.push('blissbook.browser.domain.Photo {','\n');sb.push('canEdit: ',this._canEdit,'\n');sb.push('canEditIdea: ',this._canEditIdea,'\n');sb.push('createdString: ',this._createdString,'\n');sb.push('description: ',this._description,'\n');sb.push('domId: ',this._domId,'\n');sb.push('fileLocation: ',this._fileLocation,'\n');sb.push('fileName: ',this._fileName,'\n');sb.push('hasIdea: ',this._hasIdea,'\n');sb.push('homepage: ',this._homePage,'\n');sb.push('id: ',this._serverId,'\n');sb.push('ideaNotes: ',this._ideaNotes,'n');sb.push('ideaTags: ',this._ideaTags,'\n');sb.push('ideatype: ',this._ideaType,'\n');sb.push('ownerId: ',this._ownerId,'\n');sb.push('ownerName: ',this._ownerName,'\n');sb.push('isPrivate:',this._isPrivate,'\n');sb.push('isProfessional: ',this._isProfessional,'\n');sb.push('tags: ',this._tags,'\n');sb.push('title: ',this._title,'\n');sb.push('url: ',this._url,'\n');sb.push('vendorId: ',this._vendorId,'\n');sb.push('vendors: ',this._vendors,'\n');sb.push('weddingId: ',this._weddingId,'\n}\n');return sb.join('');},toXML:function(){if(!this._xml){this._xml=xmlParse(this.toXMLString());}
return this._xml;},toXMLString:function(){var sb=[];sb.push('<photo>');sb.push('<canEdit>',this._cleanXML(this._canEdit),'</canEdit>');sb.push('<canEditIdea>',this._cleanXML(this._canEditIdea),'</canEditIdea>');sb.push('<createdString>',this._cleanXML(this._createdString),'</createdString>');sb.push('<description>',this._cleanXML(this._description),'</description>');sb.push('<domId>',this._cleanXML(this._domId),'</domId>');sb.push('<fileLocation>',this._cleanXML(this._fileLocation),'</fileLocation>');sb.push('<fileName>',this._cleanXML(this._fileName),'</fileName>');sb.push('<thumbnailImageURL>',this._cleanXML(this.getThumbnailImageURL()),'</thumbnailImageURL>');sb.push('<smallImageURL>',this._cleanXML(this.getSmallImageURL()),'</smallImageURL>');sb.push('<mediumImageURL>',this._cleanXML(this.getMediumImageURL()),'</mediumImageURL>');sb.push('<hasIdea>',this._cleanXML(this._hasIdea),'</hasIdea>');sb.push('<homePage>',this._cleanXML(this._homePage),'</homePage>');sb.push('<ideaNotes>',this._cleanXML(this._ideaNotes),'</ideaNotes>');sb.push('<ideaTags>');this._ideaTags.each(function(tag){sb.push('<tag>',this._cleanXML(tag),'</tag>');}.bind(this));sb.push('</ideaTags>');sb.push('<ideaType>',this._cleanXML(this._ideaType),'</ideaType>');sb.push('<serverId>',this._cleanXML(this._serverId),'</serverId>');sb.push('<ownerId>',this._cleanXML(this._ownerId),'</ownerId>');sb.push('<ownerName>',this._cleanXML(this._ownerName),'</ownerName>');sb.push('<isPrivate>',this._cleanXML(this._isPrivate),'</isPrivate>');sb.push('<isProfessional>',this._cleanXML(this._isProfessional),'</isProfessional>');sb.push('<tags>');this._tags.each(function(tag){sb.push('<tag>',this._cleanXML(tag),'</tag>')}.bind(this));sb.push('</tags>');sb.push('<title>',this._cleanXML(this._title),'</title>');sb.push('<url>',this._cleanXML(this._url),'</url>');sb.push('<vendorId>',this._cleanXML(this._vendorId),'</vendorId>');sb.push('<vendors>');this._vendors.each(function(vendor){sb.push(vendor.toXMLString());});sb.push('</vendors>');sb.push('<weddingId>',this._cleanXML(this._weddingId),'</weddingId>');sb.push('</photo>');return sb.join('');},clone:function(){return new blissbook.browser.domain.Photo(this.toTransferObject());},_cleanXML:function(o){var s=blissbook.util.LangUtils.toStringOrEmpty(o);return blissbook.util.StringEscapeUtils.escapeXML(s);},_markDirty:function(){this._xml=null;}};blissbook.namespace('blissbook.browser.domain');blissbook.browser.domain.Vendor=function(v,l){v=v||{};l=l||{};l.attributes=l.attributes||{};this._id=parseInt(v.id);this._rating=parseFloat(v.rating);this._total=parseInt(v.total);this._name=v.name;this._address=v.address;this._profile_url=v.profile_url;this._listingPosition=parseInt(l.attributes.position);this._listingName=l.attributes.name;};blissbook.browser.domain.Vendor.toVendors=function(vendors,listings){vendors=vendors||[];listings=listings||[];var result=new Array(vendors.length);for(var i=0,n=vendors.length;i<n;i++){result[i]=new blissbook.browser.domain.Vendor(vendors[i],listings[i]);}
return result;};blissbook.browser.domain.Vendor.prototype={getId:function(){return this._id;},getAddress:function(){return this._address;},getProfileUrl:function(){return this._profile_url;},getListingName:function(){return this._listingName;},getListingPosition:function(){return this._listingPosition;},getName:function(){return this._name;},getRating:function(){return this._rating;},getTotal:function(){return this._total;},toListingTO:function(){var o={};o.attributes={};o.attributes.position=this.getListingPosition();o.attributes.name=this.getListingName();return o;},toVendorTO:function(){var o={};o.id=this.getId();o.rating=this.getRating();o.total=this.getTotal();o.name=this.getName();o.address=this.getAddress();o.profile_url=this.getProfileUrl();return o;},toXMLString:function(){var sb=[];sb.push('<vendor>');sb.push('<id>',this._cleanXML(this.getId()),'</id>');sb.push('<rating>',this._cleanXML(this.getRating()),'</rating>');sb.push('<total>',this._cleanXML(this.getTotal()),'</total>');sb.push('<name>',this._cleanXML(this.getName()),'</name>');sb.push('<address>',this._cleanXML(this.getAddress()),'</address>');sb.push('<profile_url>',this._cleanXML(this.getProfileUrl()),'</profile_url>');sb.push('<listingPosition>',this._cleanXML(this.getListingName()),'</listingPosition>');sb.push('<listingName>',this._cleanXML(this.getListingName()),'</listingName>');sb.push('</vendor>');return sb.join('');},toString:function(){var sb=[];sb.push('blissbook.browser.domain.Vendor {');sb.push('id: ',this.getId(),'\n');sb.push('rating: ',this.getRating(),'\n');sb.push('total: ',this.getTotal(),'\n');sb.push('name: ',this.getName(),'\n');sb.push('address: ',this.getAddress(),'\n');sb.push('profile_url: ',this.getProfileUrl(),'\n');sb.push('listingPosition: ',this.getListingPosition(),'\n');sb.push('listingName: ',this.getListingName(),'\n');sb.push('}');return sb.join('');},_cleanXML:function(o){var s=blissbook.util.LangUtils.toStringOrEmpty(o);return blissbook.util.StringEscapeUtils.escapeXML(s);}};blissbook.namespace('blissbook.browser.domain');blissbook.browser.domain.PhotoCache=function(photos){this._photos=photos||[];this._serverIdToIndexMap={};this.reset(this._photos);};blissbook.browser.domain.PhotoCache.prototype={reset:function(photos){blissbook.util.Assert.isValue(photos,'PhotoCache.reset:');this._photos=photos;this._serverIdToIndexMap={};for(var i=0,n=photos.length;i<n;i++){this._serverIdToIndexMap[photos[i].getServerId()]=i;}},contains:function(p){p=this._toServerId(p);return null!==this._findByServerIdOrNull(p);},findByServerId:function(serverId){blissbook.util.Assert.isTrue(null!==this._findByServerIdOrNull(serverId),'PhotoCache.findByserverId: '+serverId);return this._findByServerIdOrNull(serverId);},findNeighbors:function(p){if(!this.contains(p)){return{prev:null,next:null};}
var i=this._toIndex(p);var photos=this._photos;return{prev:(i===0)?null:photos[i-1],next:(i===photos.length-1)?null:photos[i+1]}},put:function(p){blissbook.util.Assert.isInstanceOf(p,blissbook.browser.domain.Photo,'PhotoCahce.update: not photo');blissbook.util.Assert.isTrue(this.contains(p),'PhotoCache.update: not in cache');this._photos[this._toIndex(p)]=p;},findAll:function(){return this._photos;},findFirst:function(){return this._photos[0]||null;},_toServerId:function(p){if(p instanceof blissbook.browser.domain.Photo){return p.getServerId();}
return p;},_toIndex:function(p){p=this._toServerId(p);return this._serverIdToIndexMap[p];},_findByServerIdOrNull:function(serverId){var result=this._photos[this._serverIdToIndexMap[serverId]];return result||null;}};blissbook.namespace('blissbook.browser.domain');blissbook.browser.domain.PhotoManager=function(){this._currentPage=1;this._totalPages=1;this._photoDAO;this._photoCache=new blissbook.browser.domain.PhotoCache();this._focusPhoto=null;};blissbook.browser.domain.PhotoManager.prototype={setPhotoDAO:function(value){this._photoDAO=value;},getCurrentPage:function(){return this._currentPage;},getTotalPages:function(){return this._totalPages;},getFocusPhoto:function(){return this._focusPhoto||null;},setFocusPhoto:function(serverId){this._focusPhoto=this._photoCache.findByServerId(serverId);},getNeighbors:function(p){return this._photoCache.findNeighbors(p);},getPhotos:function(){return this._photoCache.findAll();},getPhotoByServerId:function(serverId){return this._photoCache.findByServerId(serverId);},rotatePhoto:function(serverId,degrees,o){var Assert=blissbook.util.Assert;Assert.isTrue(this._photoCache.contains(serverId),'PhotoManager.rotatePhoto: not found');Assert.isFunction(o.callback,' PhotoManager.rotatePhoto: no callback');var cache=this._photoCache;this._photoDAO.rotatePhoto(serverId,degrees,{callback:function(fileName){var p=cache.findByServerId(serverId);p.setFileName(fileName);cache.put(p);o.callback(p);},errback:function(msg){if(o.errback){o.errback(msg);}}});},deletePhoto:function(serverId,o){var Assert=blissbook.util.Assert;Assert.isTrue(this._photoCache.contains(serverId),'PhotoManager.deletePhoto: no found');Assert.isFunction(o.callback,'PhotoManager.deletePhoto: no callback');var n=this._photoCache.findNeighbors(serverId);var self=this;this._photoDAO.deletePhoto(serverId,this._currentPage,{callback:function(h){Assert.allValues([h.photos,h.totalPages],'PhotoManager.deletePhoto.callback: ');self._photoCache.reset(h.photos);self._totalPages=h.totalPages;self._focusPhoto=n.next||n.prev;o.callback();},errback:function(msg){if(o.errback){o.errback(msg);}}});},removeAllIdeas:function(serverId,o){var self=this;var n=this._photoCache.findNeighbors(serverId);this._photoDAO.removeAllIdeas(serverId,this._currentPage,{callback:function(h){if(h.pageNeedsUpdating){self._totalPages=h.totalPages;self._photoCache.reset(h.photos);self._focusPhoto=n.next||n.prev;o.callback(true,null);}else if(self._photoCache.contains(serverId)){var photo=self._photoCache.findByServerId(serverId);photo.removeAllIdeas();self._photoCache.put(photo);o.callback(false,photo);}},errback:function(msg){if(o.errback){o.errback(msg);}}});},loadPage:function(pageNum,o){var Assert=blissbook.util.Assert;Assert.isTrue(pageNum>=1,'PhotoManager.loadPage: '+pageNum);Assert.isFunction(o.callback,'PhotoManager.loadPage: no callback');var self=this;this._photoDAO.getPage(pageNum,{callback:function(h){Assert.allValues([h.photos,h.totalPages],'PhotoManager.loadPage.callback: ');self._photoCache.reset(h.photos);self._currentPage=pageNum;self._totalPages=h.totalPages;self._focusPhoto=self._photoCache.findFirst();o.callback();},errback:function(msg){if(o.errback){o.errback(msg);}}});},addTags:function(serverId,tags,o){var Assert=blissbook.util.Assert;Assert.isTrue(this._photoCache.contains(serverId),'PhotoManager.addTags: not found');Assert.notBlank(tags,'PhotoManager.addTags: blank tags');Assert.isFunction(o.callback,'PhotoManager.addTags: no callback');var cache=this._photoCache;this._photoDAO.addTags(serverId,tags,{callback:function(to){var p=cache.findByServerId(serverId);p.setTags(to.tags);p.setVendors(to.vendors);cache.put(p);o.callback(p);},errback:function(msg){if(o.errback){o.errback(msg);}}});},confirmTags:function(serverId,tags,o){var Assert=blissbook.util.Assert;Assert.isTrue(this._photoCache.contains(serverId),'PhotoManager.confirmTags: not found');Assert.notBlank(tags,'PhotoManager.confirmTags: blank tags');Assert.isFunction(o.callback,'PhotoManager.confirmTags: no callback');var cache=this._photoCache;this._photoDAO.confirmTags(serverId,tags,{callback:function(){o.callback(cache.findByServerId(serverId));},errback:function(msg){if(o.errback){o.errback(msg);}}});},removeTag:function(serverId,tag,o){var Assert=blissbook.util.Assert;Assert.isTrue(this._photoCache.contains(serverId),'PhotoManager.removeTag: not found');Assert.notBlank(tag,'PhotoManager.removeTag: blank tag');Assert.isFunction(o.callback,'PhotoManager.removeTag: no callback');var cache=this._photoCache;this._photoDAO.removeTag(serverId,tag,{callback:function(to){var p=cache.findByServerId(serverId);p.setTags(to.tags);p.setVendors(to.vendors);cache.put(p);o.callback(p);},errback:function(msg){if(o.errback){o.errback(msg);}}});},removeIdeaTag:function(serverId,tag,o){blissbook.util.Assert.isTrue(this._photoCache.contains(serverId),'PhotoManager.removeIdeaTag: not found');blissbook.util.Assert.notBlank(tag,'PhotoManager.removeIdeaTag: blank tag');blissbook.util.Assert.isFunction(o.callback,'PhotoManager.removeTag: no callback');var cache=this._photoCache;this._photoDAO.removeIdeaTag(serverId,tag,{callback:function(tags){var p=cache.findByServerId(serverId);p.setIdeaTags(tags);cache.put(p);o.callback(p);},errback:function(msg){if(o.errback){o.errback(msg);}}});},markPhotoAsBlurry:function(serverId,o){var Assert=blissbook.util.Assert;Assert.isTrue(this._photoCache.contains(serverId),'PhotoManager.markPhotoAsBlurry: not found');Assert.isFunction(o.callback,'PhotoManager.markPhotoAsBlurry: no callback');var cache=this._photoCache;this._photoDAO.markPhotoAsBlurry(serverId,{callback:function(){var p=cache.findByServerId(serverId);o.callback(p.getTitle());},errback:function(msg){if(o.errback){o.errback(msg);}}});},markPhotoAsExplicit:function(serverId,o){var Assert=blissbook.util.Assert;Assert.isTrue(this._photoCache.contains(serverId),'PhotoManager.markPhotoAsExplicit: not found');Assert.isFunction(o.callback,'PhotoManager.markPhotoAsExplicit: no callback');var cache=this._photoCache;this._photoDAO.markPhotoAsExplicit(serverId,{callback:function(){var p=cache.findByServerId(serverId);o.callback(p.getTitle());},errback:function(msg){if(o.errback){o.errback(msg);}}});},updatePhotoDescription:function(serverId,desc,o){var Assert=blissbook.util.Assert;Assert.isTrue(this._photoCache.contains(serverId),'PhotoManager.updatePhotoDescription: not found');Assert.isFunction(o.callback,'PhotoManager.updatePhotoDescription: no callback');var cache=this._photoCache;this._photoDAO.updatePhotoDescription(serverId,desc,{callback:function(serverDesc){var p=cache.findByServerId(serverId);p.setDescription(serverDesc);cache.put(p);o.callback(p);},errback:function(msg){if(o.errback){o.errback(msg);}}});},updatePhotoTitle:function(serverId,title,o){var Assert=blissbook.util.Assert;Assert.isTrue(this._photoCache.contains(serverId),'PhotoManager.updatePhotoTitle: not found');Assert.isFunction(o.callback,'PhotoManager.updatePhotoTitle: no callback');var cache=this._photoCache;this._photoDAO.updatePhotoTitle(serverId,title,{callback:function(serverTitle){var p=cache.findByServerId(serverId);p.setTitle(title);cache.put(p);o.callback(p);},errback:function(msg){if(o.errback){o.errback(msg);}}});},updatePhotoPrivacy:function(serverId,isPrivate,o){var Assert=blissbook.util.Assert;Assert.isTrue(this._photoCache.contains(serverId),'PhotoManager.updatePhotoPrivacy: not found');Assert.isFunction(o.callback,'PhotoManager.updatePhotoPrivacy: no callback');var cache=this._photoCache;this._photoDAO.updatePhotoPrivacy(serverId,isPrivate,{callback:function(serverIsPrivate){var p=cache.findByServerId(serverId);p.setPrivate(serverIsPrivate);cache.put(p);o.callback(p);},errback:function(msg){if(o.errback){o.errback(msg);}}});},updatePhotoProfessional:function(serverId,isProfessional,o){blissbook.util.Assert.isTrue(this._photoCache.contains(serverId,'Photomanager.updatePhotoProfessional: not found'));var cache=this._photoCache;this._photoDAO.updatePhotoProfessional(serverId,isProfessional,{callback:function(to){var p=cache.findByServerId(serverId);p.setProfessional(to.isPro);p.setVendors(to.vendors);cache.put(p);o.callback(p);},errback:function(msg){if(o.errback){o.errback(msg);}}});},updateIdea:function(serverId,ideaNotes,ideaTags,resourceType,o){var cache=this._photoCache;this._photoDAO.updateIdea(serverId,ideaNotes,ideaTags,resourceType,{callback:function(photo){cache.put(photo);o.callback(photo);},errback:function(msg){if(o.errback){o.errback(msg);}}});}}
blissbook.namespace('blissbook.browser.model');blissbook.browser.domain.PhotoModel=function(dao){blissbook.util.Assert.hasInterface(dao,blissbook.browser.dao.IPhotoDAO,'PhotoModel.constructor: IPhotoDAO - ');this._photoManager=new blissbook.browser.domain.PhotoManager();this._photoManager.setPhotoDAO(dao);this._errorChangeListeners=$A();};blissbook.browser.domain.PhotoModel.prototype={addErrorChangeListener:function(value){blissbook.util.Assert.isFunction(value,'PhotoModel.addErrorChangeListener');this._errorChangeListeners.push(value);},getPhotos:function(){return this._photoManager.getPhotos();},getFocusPhoto:function(){return this._photoManager.getFocusPhoto();},getNeighbors:function(p){return this._photoManager.getNeighbors(p);},getPhotoByServerId:function(serverId){return this._photoManager.getPhotoByServerId(serverId);},setFocus:function(serverId){this._photoManager.setFocusPhoto(serverId);this._fireFocusChange();},rotatePhoto:function(serverId,degrees){var self=this;this._photoManager.rotatePhoto(serverId,degrees,{callback:function(p){var event=new blissbook.browser.event.PhotoURLChange(p);blissbook.browser.event.EventBus.firePhotoURLChange(event);},errback:function(msg){self._fireErrorChangeListeners(msg);}});},deletePhoto:function(serverId){var self=this;this._photoManager.deletePhoto(serverId,{callback:function(){self._firePageChange();self._fireFocusChange();},errback:function(msg){self._fireErrorChangeListeners(msg);}});},loadPage:function(pageNum){var self=this;this._photoManager.loadPage(pageNum,{callback:function(){self._firePageChange();self._fireFocusChange();},errback:function(msg){self._fireErrorChangeListeners(msg);}});},addTags:function(serverId,tags){var self=this;this._photoManager.addTags(serverId,tags,{callback:function(p){var event=new blissbook.browser.event.PhotoTagsChange(p,true);blissbook.browser.event.EventBus.firePhotoTagsChange(event);},errback:function(msg){self._fireErrorChangeListeners(msg);}});},confirmTags:function(serverId,tags){var self=this;this._photoManager.confirmTags(serverId,tags,{callback:function(p){var event=new blissbook.browser.event.PhotoTagsChange(p,true);blissbook.browser.event.EventBus.firePhotoTagsChange(event);},errback:function(msg){self._fireErrorChangeListeners(msg);}});},removeTag:function(serverId,tag){var self=this;this._photoManager.removeTag(serverId,tag,{callback:function(p){var event=new blissbook.browser.event.PhotoTagsChange(p,false);blissbook.browser.event.EventBus.firePhotoTagsChange(event);},errback:function(msg){self._fireErrorChangeListeners(msg);}});},removeIdeaTag:function(serverId,tag){var self=this;this._photoManager.removeIdeaTag(serverId,tag,{callback:function(p){var event=new blissbook.browser.event.PhotoIdeaChange(p);blissbook.browser.event.EventBus.firePhotoIdeaChange(event);},errback:function(msg){self._fireErrorChangeListener(msg);}});},markPhotoAsBlurry:function(serverId){var self=this;this._photoManager.markPhotoAsBlurry(serverId,{callback:function(title){},errback:function(msg){self._fireErrorChangeListeners(msg);}});},markPhotoAsExplicit:function(serverId){var self=this;this._photoManager.markPhotoAsExplicit(serverId,{callback:function(title){},errback:function(msg){self._fireErrorChangeListeners(msg);}});},updatePhotoDescription:function(serverId,desc){var self=this;this._photoManager.updatePhotoDescription(serverId,desc,{callback:function(p){var event=new blissbook.browser.event.PhotoDescriptionChange(p)
blissbook.browser.event.EventBus.firePhotoDescriptionChange(event);},errback:function(msg){self._fireErrorChangeListeners(msg);}});},updatePhotoTitle:function(serverId,title){var self=this;this._photoManager.updatePhotoTitle(serverId,title,{callback:function(p){var event=new blissbook.browser.event.PhotoTitleChange(p)
blissbook.browser.event.EventBus.firePhotoTitleChange(event);},errback:function(msg){self._fireErrorChangeListeners(msg);}});},updatePhotoPrivacy:function(serverId,isPrivate){var self=this;this._photoManager.updatePhotoPrivacy(serverId,isPrivate,{callback:function(p){var event=new blissbook.browser.event.PhotoPrivacyChange(p)
blissbook.browser.event.EventBus.firePhotoPrivacyChange(event);},errback:function(msg){self._fireErrorChangeListeners(msg);}});},updatePhotoProfessional:function(serverId,isProfessional){var self=this;this._photoManager.updatePhotoProfessional(serverId,isProfessional,{callback:function(p){var event=new blissbook.browser.event.PhotoProfessionalChange(p);blissbook.browser.event.EventBus.firePhotoProfessionalChange(event);},errback:function(msg){self._fireErrorChangeListeners(msg);}});},updateIdea:function(serverId,ideaNotes,ideaTags,resourceType){var self=this;this._photoManager.updateIdea(serverId,ideaNotes,ideaTags,resourceType,{callback:function(p){var event=new blissbook.browser.event.PhotoIdeaChange(p);blissbook.browser.event.EventBus.firePhotoIdeaChange(event);},errback:function(msg){self._fireErrorChangeListeners(msg);}});},removeAllIdeas:function(serverId){var self=this;this._photoManager.removeAllIdeas(serverId,{callback:function(pageNeedsUpdating,p){if(pageNeedsUpdating){self._firePageChange();self._fireFocusChange();}else{var event=new blissbook.browser.event.PhotoIdeaChange(p);blissbook.browser.event.EventBus.firePhotoIdeaChange(event);}},errback:function(msg){self._fireErrorChangeListeners(msg);}});},_firePageChange:function(){var event=new blissbook.browser.event.PageChange(this._photoManager.getPhotos(),this._photoManager.getCurrentPage(),this._photoManager.getTotalPages());blissbook.browser.event.EventBus.firePageChange(event)},_fireFocusChange:function(){var p=this._photoManager.getFocusPhoto();var n=this._photoManager.getNeighbors(p);var event=new blissbook.browser.event.FocusChange(p,n.next,n.prev);blissbook.browser.event.EventBus.fireFocusChange(event);},_fireErrorChangeListeners:function(msg){this._errorChangeListeners.each(function(listener){listener(msg);});}}
blissbook.namespace('blissbook.browser.event');blissbook.browser.event.EventBus={_domReadyListeners:[],addDOMReadyListener:function(listener){blissbook.util.Assert.isFunction(listener,'EventBus.addBrowserStartListener: not function');blissbook.browser.event.EventBus._domReadyListeners.push(listener);},fireDOMReady:function(){var b=blissbook.browser.event.EventBus;b._domReadyListeners.each(function(listener){listener();});b.fireDOMReady=b.addDOMReadyListener=function(){};b._domReadyListeners=null;},_focusChangeListeners:[],addFocusChangeListener:function(listener){blissbook.util.Assert.isFunction(listener,'EventBus.addFocusChangeListner: not function');blissbook.browser.event.EventBus._focusChangeListeners.push(listener);},fireFocusChange:function(event){blissbook.util.Assert.isInstanceOf(event,blissbook.browser.event.FocusChange,'EventBus.fireFocusChange: not FocusChange');var b=blissbook.browser.event.EventBus;b._publish(b._focusChangeListeners,event);},_pageChangeListeners:[],addPageChangeListener:function(listener){blissbook.util.Assert.isFunction(listener,'EventBus.addPageChangeListener: not function');blissbook.browser.event.EventBus._pageChangeListeners.push(listener);},firePageChange:function(event){blissbook.util.Assert.isInstanceOf(event,blissbook.browser.event.PageChange,'EventBus.firePageChange: not PageChange');var b=blissbook.browser.event.EventBus;b._publish(b._pageChangeListeners,event);},_photoDescriptionChangeListeners:[],addPhotoDescriptionChangeListener:function(listener){blissbook.util.Assert.isFunction(listener,'EventBus.addPhotoDescriptionChangeListener: not function');blissbook.browser.event.EventBus._photoDescriptionChangeListeners.push(listener);},firePhotoDescriptionChange:function(event){blissbook.util.Assert.isInstanceOf(event,blissbook.browser.event.PhotoDescriptionChange,'EventBus.firePhotoDescriptionChange: not PhotoDescriptionChange');var b=blissbook.browser.event.EventBus;b._publish(b._photoDescriptionChangeListeners,event);},_photoPrivacyChangeListeners:[],addPhotoPrivacyChangeListener:function(listener){blissbook.util.Assert.isFunction(listener,'EventBus.addPhotoPrivacyChangeListener: not function');blissbook.browser.event.EventBus._photoPrivacyChangeListeners.push(listener);},firePhotoPrivacyChange:function(event){blissbook.util.Assert.isInstanceOf(event,blissbook.browser.event.PhotoPrivacyChange,'EventBus.firePhotoPrivacyChange: not PhotoPrivacyChange');var b=blissbook.browser.event.EventBus;b._publish(b._photoPrivacyChangeListeners,event);},_photoProfessionalChangeListeners:[],addPhotoProfessionalChangeListener:function(listener){blissbook.util.Assert.isFunction(listener,'EventBus.addPhotoProfessionalChangeListener: not function');blissbook.browser.event.EventBus._photoProfessionalChangeListeners.push(listener);},firePhotoProfessionalChange:function(event){blissbook.util.Assert.isInstanceOf(event,blissbook.browser.event.PhotoProfessionalChange,'EventBus.firePhotoProfessionalChange: not PhotoProfessionalChange');var b=blissbook.browser.event.EventBus;b._publish(b._photoProfessionalChangeListeners,event);},_photoTagsChangeListeners:[],addPhotoTagsChangeListener:function(listener){blissbook.util.Assert.isFunction(listener,'EventBus.addPhotoTagsChangeListener: not function');blissbook.browser.event.EventBus._photoTagsChangeListeners.push(listener);},firePhotoTagsChange:function(event){blissbook.util.Assert.isInstanceOf(event,blissbook.browser.event.PhotoTagsChange,'EventBus.firePhotoTagsChange: not PhotoTagsChange');var b=blissbook.browser.event.EventBus;b._publish(b._photoTagsChangeListeners,event);},_photoIdeaChangeListeners:[],addPhotoIdeaChangeListener:function(listener){blissbook.util.Assert.isFunction(listener,'EventBus.addPhotoIdeaChangeListener: not function');blissbook.browser.event.EventBus._photoIdeaChangeListeners.push(listener);},firePhotoIdeaChange:function(event){blissbook.util.Assert.isInstanceOf(event,blissbook.browser.event.PhotoIdeaChange,'EventBus.firePhotoIdeaChange: not PhotoIdeaChange');var b=blissbook.browser.event.EventBus;b._publish(b._photoIdeaChangeListeners,event);},_photoTitleChangeListeners:[],addPhotoTitleChangeListener:function(listener){blissbook.util.Assert.isFunction(listener,'EventBus.addPhotoTitleChangeListener: not  function');blissbook.browser.event.EventBus._photoTitleChangeListeners.push(listener);},firePhotoTitleChange:function(event){blissbook.util.Assert.isInstanceOf(event,blissbook.browser.event.PhotoTitleChange,'EventBus.firePhotoTitleChange: not PhotoTitleChange');var b=blissbook.browser.event.EventBus;b._publish(b._photoTitleChangeListeners,event);},_photoURLChangeListeners:[],addPhotoURLChangeListener:function(listener){blissbook.util.Assert.isFunction(listener,'EventBus.addPhotoURLChangeListener: not function');blissbook.browser.event.EventBus._photoURLChangeListeners.push(listener);},firePhotoURLChange:function(event){blissbook.util.Assert.isInstanceOf(event,blissbook.browser.event.PhotoURLChange,'EventBus.firePhotoURLChange: not PhotoURLChange');var b=blissbook.browser.event.EventBus;b._publish(b._photoURLChangeListeners,event);},_progressListeners:[],addProgressListener:function(listener){blissbook.util.Assert.isFunction(listener,'EventBus.addProgressListener: not function');blissbook.browser.event.EventBus._progressListeners.push(listener);},fireProgressChange:function(inProgress){var b=blissbook.browser.event.EventBus;b._publish(b._progressListeners,inProgress);},_publish:function(listeners,event){listeners.each(function(listener){listener.call(null,event);});}};blissbook.namespace('blissbook.browser.event');blissbook.browser.event.FocusChange=function(p,pNext,pPrev){this._focusPhoto=p||null;this._photoNext=pNext||null;this._photoPrev=pPrev||null;};Object.extend(blissbook.browser.event.FocusChange.prototype,{getFocusPhoto:function(){return this._focusPhoto;},getNextPhoto:function(){return this._photoNext;},getPreviousPhoto:function(){return this._photoPrev;}});blissbook.namespace('blissbook.browser.event');blissbook.browser.event.PageChange=function(photos,currentPage,totalPages){blissbook.util.Assert.isValue(photos,'PageChange.constructor: no photos');blissbook.util.Assert.isNumber(currentPage,'PageChange.constructor: currentPage '+currentPage);blissbook.util.Assert.isNumber(totalPages,'PageChange.constructor: totalPages: '+totalPages);this._photos=photos;this._currentPage=currentPage;this._totalPages=totalPages;};Object.extend(blissbook.browser.event.PageChange.prototype,{getPhotos:function(){return this._photos;},getCurrentPage:function(){return this._currentPage;},getTotalPages:function(){return this._totalPages;}});blissbook.namespace('blissbook.browser.event');blissbook.browser.event.PhotoDescriptionChange=function(p){blissbook.util.Assert.isValue(p,'PhotoDescriptionChanged.constructor: no p');this._photo=p;};Object.extend(blissbook.browser.event.PhotoDescriptionChange.prototype,{getPhoto:function(){return this._photo;}});blissbook.namespace('blissbook.browser.event');blissbook.browser.event.PhotoIdeaChange=function(p){blissbook.util.Assert.isValue(p,'PhotoIdeaChange.constructor: no p');this._photo=p;};Object.extend(blissbook.browser.event.PhotoIdeaChange.prototype,{getPhoto:function(){return this._photo;}});blissbook.namespace('blissbook.browser.event');blissbook.browser.event.PhotoPrivacyChange=function(p){blissbook.util.Assert.isValue(p,'PhotoPrivacyChange.constructor: no p');this._photo=p;};Object.extend(blissbook.browser.event.PhotoPrivacyChange.prototype,{getPhoto:function(){return this._photo;}});blissbook.namespace('blissbook.browser.event');blissbook.browser.event.PhotoProfessionalChange=function(p){blissbook.util.Assert.isValue(p,'PhotoProfessionalChange.constructor: no p');this._photo=p;};Object.extend(blissbook.browser.event.PhotoProfessionalChange.prototype,{getPhoto:function(){return this._photo;}});blissbook.namespace('blissbook.browser.event');blissbook.browser.event.PhotoTitleChange=function(p){blissbook.util.Assert.isValue(p,'PhotoTitleChange.constructor: no p');this._photo=p;};Object.extend(blissbook.browser.event.PhotoTitleChange.prototype,{getPhoto:function(){return this._photo;}});blissbook.namespace('blissbook.browser.event');blissbook.browser.event.PhotoURLChange=function(p){blissbook.util.Assert.isValue(p,'PhotoURLChange.constructor: no p');this._photo=p;};Object.extend(blissbook.browser.event.PhotoURLChange.prototype,{getPhoto:function(){return this._photo;}});blissbook.namespace('blissbook.browser.event');blissbook.browser.event.PhotoTagsChange=function(p,added){blissbook.util.Assert.isValue(p,'PhotoTagsChange.constructor: no p');this._photo=p;this._tagsAdded=added||false;};Object.extend(blissbook.browser.event.PhotoTagsChange.prototype,{getPhoto:function(){return this._photo;},tagsAdded:function(){return this._tagsAdded;}});blissbook.namespace('blissbook.browser.controller');blissbook.browser.controller.BrowserController=(function(){var _detailsView;var _singleView;var _slideShowView;var _thumbnailsView;var _magnifyView;var _navigationView;var _paginationView;var _progressView;var _deleteTagDialog;var _deleteIdeaDialog;var _deleteIdeaTagDialog;var _photoModel;var _currentView;return{setDetailsView:function(value){blissbook.util.Assert.hasInterface(value,blissbook.browser.view.IView,'BrowserController.setDetailsView:');_detailsView=value;},setSingleView:function(value){blissbook.util.Assert.hasInterface(value,blissbook.browser.view.IView,'BrowserController.setSingleView:');_singleView=value;},setSlideShowView:function(value){blissbook.util.Assert.hasInterface(value,blissbook.browser.view.IView,'BrowserController.setSlideShowView:');_slideShowView=value;},setThumbnailsView:function(value){blissbook.util.Assert.hasInterface(value,blissbook.browser.view.IView,'BrowserController.setThumbnailsView:');_thumbnailsView=value;},setNavigationView:function(value){_navigationView=value;},setPaginationView:function(value){_paginationView=value;},setProgressView:function(value){_progressView=value;},setMagnifyView:function(value){_magnifyView=value;},setConfirmTagDialog:function(value){_confirmTagDialog=value;},setDeleteIdeaTagDialog:function(value){_deleteIdeaTagDialog=value;},setDeleteIdeaDialog:function(value){_deleteIdeaDialog=value;},setDeletePhotoDialog:function(value){_deletePhotoDialog=value;},setDeleteTagDialog:function(value){_deleteTagDialog=value;},setReportPhotoDialog:function(value){_reportPhotoDialog=value;},setPhotoModel:function(value){_photoModel=value;_photoModel.addErrorChangeListener(function(msg){alert(msg);});},lazyGetPhotos:function(){return _photoModel.getPhotos();},lazyGetFocusPhoto:function(){return _photoModel.getFocusPhoto();},lazyGetNeighbors:function(p){return _photoModel.getNeighbors(p);},goStart:function(){blissbook.browser.event.EventBus.fireDOMReady();blissbook.browser.controller.BrowserController.goSlideShow();blissbook.browser.controller.BrowserController.goPageNumber(1);},goFocus:function(serverId){_photoModel.setFocus(serverId);},goMagnify:function(serverId,top,left){var p=_photoModel.getPhotoByServerId(serverId);_magnifyView.showMagnifyingGlass(p,top,left)},goDetails:function(){blissbook.browser.controller.BrowserController._switchCurrentView(_detailsView);_navigationView.onViewChanged(_navigationView.VIEW_DETAILS);},goSingle:function(serverId){if(blissbook.util.LangUtils.isValue(serverId)){_photoModel.setFocus(serverId);}
blissbook.browser.controller.BrowserController._switchCurrentView(_singleView);_navigationView.onViewChanged(_navigationView.VIEW_SINGLE);},goSlideShow:function(){blissbook.browser.controller.BrowserController._switchCurrentView(_slideShowView);_navigationView.onViewChanged(_navigationView.VIEW_SLIDESHOW);},goThumbnails:function(){blissbook.browser.controller.BrowserController._switchCurrentView(_thumbnailsView);_navigationView.onViewChanged(_navigationView.VIEW_THUMBNAILS);},_switchCurrentView:function(view){blissbook.util.Assert.isValue(view,'BrowserController._switchCurrentView');if(_currentView===view){return;}
if(_magnifyView.showing()){_magnifyView.hideView();}
if(_currentView){_currentView.hideView();}
_currentView=view;_currentView.showView();},goPageNumber:function(pageNum){blissbook.util.Assert.isTrue(pageNum>=1,'BrowserController.goPageNumber: pageNum '+pageNum);_photoModel.loadPage(pageNum);},doRotatePhoto:function(serverId,degrees){_photoModel.rotatePhoto(serverId,degrees);},doDeletePhoto:function(serverId){var p=_photoModel.getPhotoByServerId(serverId);_deletePhotoDialog.open({title:p.getTitle(),onConfirm:function(){_photoModel.deletePhoto(serverId);}});},doAddTags:function(serverId,tags){tags=blissbook.util.StringUtils.trimTokens(tags,',');if(tags.blank()){return'Please enter tags';}
var p=_photoModel.getPhotoByServerId(serverId);if(p.canEdit()){_photoModel.addTags(serverId,tags);}else{_confirmTagDialog.open({tags:tags,onConfirm:function(){_photoModel.confirmTags(serverId,tags);}});}
return null;},doRemoveTag:function(serverId,tag){_deleteTagDialog.open({tag:tag,onConfirm:function(){_photoModel.removeTag(serverId,tag);}});},doRemoveIdeaTag:function(serverId,ideaTag){_deleteIdeaTagDialog.open({tag:ideaTag,onConfirm:function(){_photoModel.removeIdeaTag(serverId,ideaTag);}});},doReportBlurryPhoto:function(serverId){var p=_photoModel.getPhotoByServerId(serverId);_reportPhotoDialog.confirmBlurry({photo:p,onConfirm:function(){_photoModel.markPhotoAsBlurry(serverId);}});},doReportExplicitPhoto:function(serverId){var p=_photoModel.getPhotoByServerId(serverId);_reportPhotoDialog.confirmExplicit({photo:p,onConfirm:function(){_photoModel.markPhotoAsExplicit(serverId);}});},doUpdatePhotoDescription:function(serverId,desc){desc=blissbook.util.StringUtils.trimToEmpty(desc);_photoModel.updatePhotoDescription(serverId,desc);},doUpdatePhotoTitle:function(serverId,title){title=blissbook.util.StringUtils.trimToEmpty(title);_photoModel.updatePhotoTitle(serverId,title);},doUpdatePhotoPrivacy:function(serverId,isPrivate){_photoModel.updatePhotoPrivacy(serverId,isPrivate);},doUpdateIdea:function(serverId,ideaNotes,ideaTags,resourceType){_photoModel.updateIdea(serverId,ideaNotes,ideaTags,resourceType);},doRemoveAllIdeas:function(serverId){var p=_photoModel.getPhotoByServerId(serverId);_deleteIdeaDialog.open({title:p.getTitle(),onConfirm:function(){_photoModel.removeAllIdeas(serverId);}});},doUpdatePhotoProfessional:function(serverId,isPro){_photoModel.updatePhotoProfessional(serverId,isPro);}}})();blissbook.namespace('blissbook.browser.view.common');blissbook.browser.view.common.AbstractTemplate=function(){};blissbook.browser.view.common.AbstractTemplate.prototype={getElementById:function(prefix,value){prefix=prefix+'';value=value+'';blissbook.util.Assert.notEmpty(prefix,'AbstractTemplate.getElementById: prefix '+prefix);blissbook.util.Assert.notEmpty(value,'AbstractTemplate.getElementById: value '+value);return $(prefix+value);},domIdStartsWith:function(prefix,el){blissbook.util.Assert.notEmpty(prefix,'AbstractTemplate.domIdStartsWith: prefix '+prefix);if(!el){return false;}
var domId=el.id||'';return domId.startsWith(prefix);},sliceServerId:function(prefix,el){blissbook.util.Assert.notEmpty(prefix,'AbstractTemplate.sliceValue: prefix '+prefix);blissbook.util.Assert.isValue(el,'AbstractTemplate.sliceValue: el '+el);var domId=el.id||'';var result=parseInt(domId.substring(prefix.length));blissbook.util.Assert.isNumber(result,'AbstractTemplate.sliceValue: serverId '+result);return result;},swapXSLWithParam:function(xslText,paramName,paramValue){var rx=new RegExp('<xsl:with-param[\\s]*name[\\s]*=[\\s]*[\\\'"]'+
paramName+'[\\\'"][\\s]*>.*<\\/xsl:with-param[\\s]*>','mi');return xslText.replace(rx,'<xsl:with-param name="'+paramName+'">'+paramValue+'</xsl:with-param>');}};blissbook.namespace('blissbook.browser.view.common');blissbook.browser.view.common.BlurryExplicitLinkTemplate=function(listenerScope){this._listenerScope=listenerScope||document.body;this.NAMESPACE='browser_blurry_explicit_link_template_'+
blissbook.browser.view.common.BlurryExplicitLinkTemplate.instances++;this.BLURRY_LINK_PREFIX=this.NAMESPACE+'_blurry_';this.EXPLICIT_LINK_PREFIX=this.NAMESPACE+'_explicit_';this.XSL='browser_blurry_explicit_link_template_xsl';this._controller=blissbook.browser.controller.BrowserController;};blissbook.browser.view.common.BlurryExplicitLinkTemplate.instances=0;blissbook.browser.view.common.BlurryExplicitLinkTemplate.prototype=Object.extend(new blissbook.browser.view.common.AbstractTemplate(),{newComponent:function(container,p){var Assert=blissbook.util.Assert;Assert.isValue($(container),'BlurryExplicitLinkTempalte.newComponent: container '+container);Assert.isValue(p,'BlurryExplicitLinkTemplate.newComponent: no p');this._ensureDOMEventHandlers();$(container).innerHTML=this._linksHTML(p);},_linksHTML:function(p){return xsltProcess(p.toXML(),this._getXSL());},_ensureDOMEventHandlers:function(){blissbook.util.Assert.isValue($(this._listenerScope),'BlurryExplicitLinkTempalte._ensureDOMEventHandlers: listenerScope: '+this._listenerScope);this._addClickListenerToScope();this._ensureDOMEventHandlers=function(){};},_addClickListenerToScope:function(){var self=this;blissbook.util.Event.onClickDelegateUntil(this._listenerScope,function(el){if(self._isBlurryLink(el)){self._onBlurryLinkClicked(el);return true;}else if(self._isExplicitLink(el)){self._onExplicitLinkClicked(el);return true;}
return false;});},_onBlurryLinkClicked:function(el){var serverId=this.sliceServerId(this.BLURRY_LINK_PREFIX,el);this._controller.doReportBlurryPhoto(serverId);},_onExplicitLinkClicked:function(el){var serverId=this.sliceServerId(this.EXPLICIT_LINK_PREFIX,el);this._controller.doReportExplicitPhoto(serverId);},_isBlurryLink:function(el){return this.domIdStartsWith(this.BLURRY_LINK_PREFIX,el);},_isExplicitLink:function(el){return this.domIdStartsWith(this.EXPLICIT_LINK_PREFIX,el);},_getXSL:function(){var s=$(this.XSL).value;s=this.swapXSLWithParam(s,'namespace',this.NAMESPACE);var xsl=xmlParse(s);this._getXSL=function(){return xsl};return xsl;}});blissbook.namespace('blissbook.browser.view.common');blissbook.browser.view.common.DescriptionTemplate=function(listenerScope){this._listenerScope=listenerScope||document.body;this.NAMESPACE='browser_description_template_'+
blissbook.browser.view.common.DescriptionTemplate.instances++;this.DESC_CONTAINER_PREFIX=this.NAMESPACE+'_desc_container_';this.DESC_EDITABLE_CONTAINER_PREFIX=this.NAMESPACE+'_desc_edit_container_';this.DESC_FORM_CONTAINER_PREFIX=this.NAMESPACE+'_desc_form_container_';this.DESC_FORM_TEXT_AREA_PREFIX=this.NAMESPACE+'_desc_text_';this.DESC_FORM_SAVE_BUTTON_PREFIX=this.NAMESPACE+'_desc_save_';this.DESC_FORM_CANCEL_BUTTON_PREFIX=this.NAMESPACE+'_desc_cancel_';this.XSL='browser_description_template_xsl';this._controller=blissbook.browser.controller.BrowserController;this._initSubscribers();};blissbook.browser.view.common.DescriptionTemplate.instances=0;blissbook.browser.view.common.DescriptionTemplate.prototype=Object.extend(new blissbook.browser.view.common.AbstractTemplate(),{newComponent:function(container,p){var Assert=blissbook.util.Assert;Assert.isValue($(container),'DescriptionTemplate.newComponent: container '+container);Assert.isValue(p,'DescriptionTemplate.newComponent: no p');this._ensureDOMEventHandlers();$(container).innerHTML=this._descriptionHTML(p);},_initSubscribers:function(){blissbook.browser.event.EventBus.addPhotoDescriptionChangeListener(this._onPhotoDescriptionChange.bind(this));},_onPhotoDescriptionChange:function(event){this._refreshDescription(event.getPhoto());},_refreshDescription:function(p){if(!this._getDescriptionRefreshContainer(p)){return;}
var container=this._getDescriptionRefreshContainer(p);container.innerHTML=this._descriptionHTML(p);blissbook.util.EffectUtils.highlightIfNotHighlighted(container);},_descriptionHTML:function(p){return xsltProcess(p.toXML(),this._getXSL());},_ensureDOMEventHandlers:function(){blissbook.util.Assert.isValue($(this._listenerScope),'DescriptionTemplate._ensureDOMEventHandlers: listenerScope: '+this._listenerScope);this._addClickListenerToScope();this._addMouseoverListenerToScope();this._ensureDOMEventHandlers=function(){};},_addClickListenerToScope:function(){var self=this;blissbook.util.Event.onClickDelegateUntil(this._listenerScope,function(el){if(self._isEditableDescriptionContainer(el)){self._onEditableDescriptionContainerClicked(el);return true;}else if(self._isDescriptionFormSaveButton(el)){self._onDescriptionFormSaveButtonClicked(el);return true;}else if(self._isDescriptionFormCancelButton(el)){self._onDescriptionFormCancelButtonClicked(el);return true;}
return false;});},_addMouseoverListenerToScope:function(){var self=this;blissbook.util.Event.onMouseoverDelegateUntil(this._listenerScope,function(el){if(self._isEditableDescriptionContainer(el)){self._onEditableDescriptionContainerMouseover(el);return true;}
return false;});},_onEditableDescriptionContainerClicked:function(el){el.hide();var serverId=this._getServerIdByEditableDescriptionContainer(el);this._getDescriptionFormContainerByServerId(serverId).show();},_onDescriptionFormSaveButtonClicked:function(el){var serverId=this._getServerIdByDescriptionFormSaveButton(el);var desc=this._getDescriptionFormTextAreaByServerId(serverId).value;this._hideDescriptionForm(serverId);this._controller.doUpdatePhotoDescription(serverId,desc);},_onDescriptionFormCancelButtonClicked:function(el){var serverId=this._getServerIdByDescriptionFormCancelButton(el);this._hideDescriptionForm(serverId);},_onEditableDescriptionContainerMouseover:function(el){blissbook.util.EffectUtils.highlightIfNotHighlighted(el);},_hideDescriptionForm:function(serverId){this._getDescriptionFormContainerByServerId(serverId).hide();this._getEditableDescriptionContainerByServerId(serverId).show();},_getDescriptionRefreshContainer:function(p){if(!$(this.DESC_CONTAINER_PREFIX+p.getServerId())){return null;}
return $(this.DESC_CONTAINER_PREFIX+p.getServerId()).parentNode;},_isEditableDescriptionContainer:function(el){return this.domIdStartsWith(this.DESC_EDITABLE_CONTAINER_PREFIX,el);},_getEditableDescriptionContainerByServerId:function(serverId){return this.getElementById(this.DESC_EDITABLE_CONTAINER_PREFIX,serverId);},_getServerIdByEditableDescriptionContainer:function(el){return this.sliceServerId(this.DESC_EDITABLE_CONTAINER_PREFIX,el);},_getDescriptionFormContainerByServerId:function(serverId){return this.getElementById(this.DESC_FORM_CONTAINER_PREFIX,serverId);},_getDescriptionFormTextAreaByServerId:function(serverId){return this.getElementById(this.DESC_FORM_TEXT_AREA_PREFIX,serverId);},_isDescriptionFormSaveButton:function(el){return this.domIdStartsWith(this.DESC_FORM_SAVE_BUTTON_PREFIX,el);},_getServerIdByDescriptionFormSaveButton:function(el){return this.sliceServerId(this.DESC_FORM_SAVE_BUTTON_PREFIX,el);},_isDescriptionFormCancelButton:function(el){return this.domIdStartsWith(this.DESC_FORM_CANCEL_BUTTON_PREFIX,el);},_getServerIdByDescriptionFormCancelButton:function(el){return this.sliceServerId(this.DESC_FORM_CANCEL_BUTTON_PREFIX,el);},_getXSL:function(){var s=$(this.XSL).value;s=this.swapXSLWithParam(s,'namespace',this.NAMESPACE);var xsl=xmlParse(s);this._getXSL=function(){return xsl;};return xsl;}});blissbook.namespace('blissbook.browser.view.common');blissbook.browser.view.common.IdeaNotesTemplate=function(listenerScope){this._listenerScope=listenerScope||document.body;this.NAMESPACE='browser_idea_notes_template_'+
blissbook.browser.view.common.IdeaNotesTemplate.instances++;this.CONTAINER_PREFIX=this.NAMESPACE+'_container_';this.XSL='browser_idea_notes_template_xsl';this._initSubscribers();};blissbook.browser.view.common.IdeaNotesTemplate.instances=0;blissbook.browser.view.common.IdeaNotesTemplate.prototype=Object.extend(new blissbook.browser.view.common.AbstractTemplate(),{newComponent:function(container,p){blissbook.util.Assert.isValue($(container),'IdeaNotesTemplate.newComponent: contaienr '+container);blissbook.util.Assert.isValue(p,'IdeaNotesTemplate.newComponent: no p');$(container).innerHTML=this._notesHTML(p);},_initSubscribers:function(){var EventBus=blissbook.browser.event.EventBus;EventBus.addPhotoIdeaChangeListener(this._onPhotoIdeaChange.bind(this));},_onPhotoIdeaChange:function(event){this._refreshNotes(event.getPhoto());},_refreshNotes:function(p){if(!this._getRefreshContainer(p)){return;}
this._getRefreshContainer(p).innerHTML=this._notesHTML(p);},_notesHTML:function(p){return xsltProcess(p.toXML(),this._getXSL());},_getRefreshContainer:function(p){if(!$(this.CONTAINER_PREFIX+p.getServerId())){return null;}
return $(this.CONTAINER_PREFIX+p.getServerId()).parentNode;},_getXSL:function(){var s=$(this.XSL).value;s=this.swapXSLWithParam(s,'namespace',this.NAMESPACE);var xsl=xmlParse(s);this._getXSL=function(){return xsl};return xsl;}});blissbook.namespace('blissbook.browser.view.common');blissbook.browser.view.common.IdeaTagsTemplate=function(listenerScope){this._listenerScope=listenerScope||document.body;this.NAMESPACE='browser_idea_tags_template_'+
blissbook.browser.view.common.IdeaTagsTemplate.instances++;this.TAG_CONTAINER_PREFIX=this.NAMESPACE+'_tag_container_';this.TAG_REMOVE_PREFIX=this.NAMESPACE+'_remove_tag_';this.TAG_NAME_REGEX=new RegExp('^'+this.TAG_REMOVE_PREFIX+'[\\d]+_(.*)$');this.SERVER_ID_REGEX=new RegExp('^'+this.TAG_REMOVE_PREFIX+'([\\d]+)_.*$')
this.XSL='browser_idea_tags_template_xsl';this._initSubscribers();};blissbook.browser.view.common.IdeaTagsTemplate.instances=0;blissbook.browser.view.common.IdeaTagsTemplate.prototype=Object.extend(new blissbook.browser.view.common.AbstractTemplate(),{newComponent:function(container,p){blissbook.util.Assert.isValue($(container),'IdeaTagsTemplate.newComponent: container '+container);blissbook.util.Assert.isValue(p,'IdeaTagsTemplate.newComponent: no p');$(container).innerHTML=this._tagsHTML(p);},_initSubscribers:function(){var EventBus=blissbook.browser.event.EventBus;EventBus.addDOMReadyListener(this._onDOMReady.bind(this));EventBus.addPhotoIdeaChangeListener(this._onPhotoIdeaChange.bind(this));},_onDOMReady:function(){blissbook.util.Assert.isValue($(this._listenerScope),'IdeaTagsTemplate._onDOMReady: listenerScope '+this._listenerScope);this._addClickListenerToScope();},_onPhotoIdeaChange:function(event){this._refreshTags(event.getPhoto());},_addClickListenerToScope:function(){var self=this;blissbook.util.Event.onClickDelegateUntil(this._listenerScope,function(el){if(self._isTagRemoveLink(el)){self._onTagRemoveLinkClicked(el);return true;}
return false;});},_refreshTags:function(p){if(!this._getRefreshContainer(p)){return;}
this._getRefreshContainer(p).innerHTML=this._tagsHTML(p);},_tagsHTML:function(p){return xsltProcess(p.toXML(),this._getXSL());},_onTagRemoveLinkClicked:function(el){var serverId=this._getServerIdByTagRemoveLink(el);var tag=this._getTagByTagRemoveLink(el);blissbook.browser.controller.BrowserController.doRemoveIdeaTag(serverId,tag);},_getRefreshContainer:function(p){if(!$(this.TAG_CONTAINER_PREFIX+p.getServerId())){return null;}
return $(this.TAG_CONTAINER_PREFIX+p.getServerId()).parentNode;},_isTagRemoveLink:function(el){return this.domIdStartsWith(this.TAG_REMOVE_PREFIX,el);},_getTagByTagRemoveLink:function(el){return el.id.match(this.TAG_NAME_REGEX)[1];},_getServerIdByTagRemoveLink:function(el){return parseInt(el.id.match(this.SERVER_ID_REGEX)[1]);},_getXSL:function(){var s=$(this.XSL).value;s=this.swapXSLWithParam(s,'namespace',this.NAMESPACE);var xsl=xmlParse(s);this._getXSL=function(){return xsl};return xsl;}})
blissbook.namespace('blissbook.browser.view.common');blissbook.browser.view.common.IdeasButtonTemplate=function(listenerScope){this._listenerScope=listenerScope||document.body;this.NAMESPACE='browser_ideas_button_template_'+
blissbook.browser.view.common.IdeasButtonTemplate.instances++;this.IDEAS_BUTTON_PREFIX=this.NAMESPACE+'_idea_';this.TEMPLATE_CONTAINER_PREFIX=this.NAMESPACE+'_container_';this.XSL='browser_ideas_button_template_xsl';this._initSubscribers();};Object.extend(blissbook.browser.view.common.IdeasButtonTemplate,{instances:0,onClick:function(href,hasIdea){blissbook.browser.view.common.IdeasButtonTemplate._openModal(href,hasIdea);return false;},_openModal:function(href,hasIdea){var self=blissbook.browser.view.common.IdeasButtonTemplate;new Ajax.Request(href,{asynchronous:false,onComplete:function(http){Control.Modal.open(http.responseText,{afterOpen:function(){if(hasIdea){self._addDeleteLinkToModal();}
self._overrideModalSubmit();}});},onException:function(req,e){throw e}});},_addDeleteLinkToModal:function(){new Insertion.Before('idea_entry_save','<img id="idea_delete_link" style="cursor:pointer" src="/images/buttons/delete.png"/>');$('idea_delete_link').onclick=function(){var id=$('idea_resource_id').value;Control.Modal.close();blissbook.browser.controller.BrowserController.doRemoveAllIdeas(id)};},_overrideModalSubmit:function(){$$('#idea_entry_div_container form')[0].onsubmit=function(){var resourceId=$('idea_resource_id').value;var ideaNotes=$('idea_notes').value;var ideaTagNames=$('idea_tag_names').value;var resourceType=$('idea_resource_type').value
Control.Modal.close();blissbook.browser.controller.BrowserController.doUpdateIdea(resourceId,ideaNotes,ideaTagNames,resourceType);return false;}}});blissbook.browser.view.common.IdeasButtonTemplate.prototype=Object.extend(new blissbook.browser.view.common.AbstractTemplate(),{newComponent:function(container,p){var html=xsltProcess(p.toXML(),this._getXSL());$(container).innerHTML=html;},_initSubscribers:function(){var EventBus=blissbook.browser.event.EventBus;EventBus.addDOMReadyListener(this._onDOMReady.bind(this));EventBus.addPhotoIdeaChangeListener(this._onPhotoIdeaChange.bind(this));},_onDOMReady:function(){blissbook.util.Assert.isValue($(this._listenerScope),'IdeasButtonTemplate._onDOMReady: lsitenerScope '+this._listenerScope);},_onPhotoIdeaChange:function(event){var p=event.getPhoto();var el=$(this.TEMPLATE_CONTAINER_PREFIX+p.getServerId());if(el){var html=xsltProcess(p.toXML(),this._getXSL());el.parentNode.innerHTML=html;}},_addClickListenerToScope:function(){var self=this;blissbook.util.Event.onClickDelegateUntil(this._listenerScope,function(el){if(self._isIdeasButton(el)){self._onIdeasButtonClicked(el);return true;}
return false;})},_isIdeasButton:function(el){return this.domIdStartsWith(this.IDEAS_BUTTON_PREFIX,el);},_onIdeasButtonClicked:function(el){var serverId=this.sliceServerId(this.IDEAS_BUTTON_PREFIX,el);},_getXSL:function(){var s=$(this.XSL).value;s=this.swapXSLWithParam(s,'namespace',this.NAMESPACE);var xsl=xmlParse(s);this._getXSL=function(){return xsl;};return xsl;}})
blissbook.namespace('blissbook.browser.view.common');blissbook.browser.view.common.MediumImageTemplate=function(){this.NAMESPACE='browser_medium_image_template_'+
blissbook.browser.view.common.MediumImageTemplate.instances++;this.IMAGE_PREFIX=this.NAMESPACE+'_medium_image_';this.XSL='browser_medium_image_template_xsl';this._initSubscribers();};blissbook.browser.view.common.MediumImageTemplate.instances=0;blissbook.browser.view.common.MediumImageTemplate.prototype=Object.extend(new blissbook.browser.view.common.AbstractTemplate(),{newComponent:function(container,p){var html=xsltProcess(p.toXML(),this._getXSL());$(container).innerHTML=html;},_initSubscribers:function(){blissbook.browser.event.EventBus.addPhotoURLChangeListener(this._onPhotoURLChange.bind(this));},_onPhotoURLChange:function(event){this._refreshMediumImage(event.getPhoto());},_refreshMediumImage:function(p){if(!$(this.IMAGE_PREFIX+p.getServerId())){return;}
$(this.IMAGE_PREFIX+p.getServerId()).src=p.getMediumImageURL();},_getXSL:function(){var s=$(this.XSL).value;s=this.swapXSLWithParam(s,'namespace',this.NAMESPACE);var xsl=xmlParse(s);this._getXSL=function(){return xsl;};return xsl;}});blissbook.namespace('blissbook.browser.view.common');blissbook.browser.view.common.PhotographerTemplate=function(listenerScope){this._listenerScope=listenerScope||document.body;this.NAMESPACE='browser_photographer_template_'+
blissbook.browser.view.common.PhotographerTemplate.instances++;this.CONTAINER_PREFIX=this.NAMESPACE+'_container_';this.EDIT_CONTAINER_PREFIX=this.NAMESPACE+'_edit_container_';this.FORM_CONTAINER_PREFIX=this.NAMESPACE+'_form_container_';this.PRO_RADIO_BUTTON_PREFIX=this.NAMESPACE+'_professional_radio_';this.FORM_SAVE_BUTTON_PREFIX=this.NAMESPACE+'_form_save_';this.FORM_CANCEL_BUTTON_PREFIX=this.NAMESPACE+'_form_cancel_';this.XSL='browser_photographer_template_xsl';this._initSubscribers();};blissbook.browser.view.common.PhotographerTemplate.instances=0;blissbook.browser.view.common.PhotographerTemplate.prototype=Object.extend(new blissbook.browser.view.common.AbstractTemplate(),{newComponent:function(container,p){var Assert=blissbook.util.Assert;Assert.isValue($(container),'PhotographerTemplate.newComponent: container '+container);Assert.isValue(p,'PhotographerTemplate.newComponent: no p');this._ensureDOMEventHandlers();$(container).innerHTML=this._privacyHTML(p);},_initSubscribers:function(){var EventBus=blissbook.browser.event.EventBus;EventBus.addPhotoProfessionalChangeListener(this._onPhotoProfessionalChange.bind(this));},_onPhotoProfessionalChange:function(event){this._refreshPhotographer(event.getPhoto());},_refreshPhotographer:function(p){if(!this._getRefreshContainer(p)){return;}
var container=this._getRefreshContainer(p);container.innerHTML=this._privacyHTML(p);blissbook.util.EffectUtils.highlightIfNotHighlighted(container);},_privacyHTML:function(p){return xsltProcess(p.toXML(),this._getXSL());},_ensureDOMEventHandlers:function(){blissbook.util.Assert.isValue($(this._listenerScope),'PhotographerTemplate._ensureDOMEventHandlers: listenerScope '+this._listenerScope);this._addClickListenerToScope();this._addMouseoverListenerToScope();this._ensureDOMEventHandlers=function(){};},_addClickListenerToScope:function(){var self=this;blissbook.util.Event.onClickDelegateUntil(this._listenerScope,function(el){if(self._isEditContainer(el)){self._onEditableContainerClicked(el);return true;}else if(self._isCancelButton(el)){self._onCancelButtonClicked(el);return true;}else if(self._isSaveButton(el)){self._onSaveButtonClicked(el);return true;}
return false;});},_addMouseoverListenerToScope:function(){var self=this;blissbook.util.Event.onMouseoverDelegateUntil(this._listenerScope,function(el){if(self._isEditContainer(el)){self._onEditContainerMouseover(el);return true;}
return false;});},_onEditableContainerClicked:function(el){var serverId=this._getServerIdByEditContainer(el);el.hide();this._getFormContainerByServerId(serverId).show();},_onCancelButtonClicked:function(el){var serverId=this._getServerIdByCancelButton(el);this._hideForm(serverId);},_onSaveButtonClicked:function(el){var serverId=this._getServerIdBySaveButton(el);var isPro=this._getProRadioButtonByServerId(serverId).checked;blissbook.browser.controller.BrowserController.doUpdatePhotoProfessional(serverId,isPro);this._hideForm(serverId);},_onEditContainerMouseover:function(el){blissbook.util.EffectUtils.highlightIfNotHighlighted(el);},_hideForm:function(serverId){this._getFormContainerByServerId(serverId).hide();this._getEditContainerByServerId(serverId).show();},_getRefreshContainer:function(p){if(!$(this.CONTAINER_PREFIX+p.getServerId())){return null;}
return $(this.CONTAINER_PREFIX+p.getServerId()).parentNode;},_isEditContainer:function(el){return this.domIdStartsWith(this.EDIT_CONTAINER_PREFIX,el);},_getServerIdByEditContainer:function(el){return this.sliceServerId(this.EDIT_CONTAINER_PREFIX,el);},_getEditContainerByServerId:function(serverId){return this.getElementById(this.EDIT_CONTAINER_PREFIX,serverId);},_getFormContainerByServerId:function(serverId){return this.getElementById(this.FORM_CONTAINER_PREFIX,serverId);},_getProRadioButtonByServerId:function(serverId){return this.getElementById(this.PRO_RADIO_BUTTON_PREFIX,serverId);},_isCancelButton:function(el){return this.domIdStartsWith(this.FORM_CANCEL_BUTTON_PREFIX,el);},_getServerIdByCancelButton:function(el){return this.sliceServerId(this.FORM_CANCEL_BUTTON_PREFIX,el);},_isSaveButton:function(el){return this.domIdStartsWith(this.FORM_SAVE_BUTTON_PREFIX,el);},_getServerIdBySaveButton:function(el){return this.sliceServerId(this.FORM_SAVE_BUTTON_PREFIX,el);},_getXSL:function(){var s=$(this.XSL).value;s=this.swapXSLWithParam(s,'namespace',this.NAMESPACE);var xsl=xmlParse(s);this._getXSL=function(){return xsl;};return xsl;}});blissbook.namespace('blissbook.browser.view.common');blissbook.browser.view.common.PrivacyTemplate=function(listenerScope){this._listenerScope=listenerScope||document.body;this.NAMESPACE='browser_privacy_template_'+
blissbook.browser.view.common.PrivacyTemplate.instances++;this.PRIVACY_CONTAINER_PREFIX=this.NAMESPACE+'_privacy_container_';this.PRIVACY_EDITABLE_CONTAINER_PREFIX=this.NAMESPACE+'_privacy_edit_container_';this.PRIVACY_FORM_CONTAINER_PREFIX=this.NAMESPACE+'_privacy_form_container_';this.PRIVACY_FORM_PRIVATE_RADIO_BUTTON_PREFIX=this.NAMESPACE+'_private_radio_';this.PRIVACY_FORM_SAVE_BUTTON_PREFIX=this.NAMESPACE+'_privacy_form_save_';this.PRIVACY_FORM_CANCEL_BUTTON_PREFIX=this.NAMESPACE+'_privacy_form_cancel_';this.XSL='browser_privacy_template_xsl';this._controller=blissbook.browser.controller.BrowserController;this._initSubscribers();};blissbook.browser.view.common.PrivacyTemplate.instances=0;blissbook.browser.view.common.PrivacyTemplate.prototype=Object.extend(new blissbook.browser.view.common.AbstractTemplate(),{newComponent:function(container,p){var Assert=blissbook.util.Assert;Assert.isValue($(container),'PrivacyTemplate.newComponent: container '+container);Assert.isValue(p,'PrivacyTemplate.newComponent: no p');this._ensureDOMEventHandlers();$(container).innerHTML=this._privacyHTML(p);},_initSubscribers:function(){blissbook.browser.event.EventBus.addPhotoPrivacyChangeListener(this._onPhotoPrivacyChange.bind(this));},_onPhotoPrivacyChange:function(event){this._refreshPrivacy(event.getPhoto());},_refreshPrivacy:function(p){if(!this._getPrivacyRefreshContainer(p)){return;}
var container=this._getPrivacyRefreshContainer(p);container.innerHTML=this._privacyHTML(p);blissbook.util.EffectUtils.highlightIfNotHighlighted(container);},_privacyHTML:function(p){return xsltProcess(p.toXML(),this._getXSL());},_ensureDOMEventHandlers:function(){blissbook.util.Assert.isValue($(this._listenerScope),'PrivacyTemplate._ensureDOMEventHandlers: listenerScope '+this._listenerScope);this._addClickListenerToScope();this._addMouseoverListenerToScope();this._ensureDOMEventHandlers=function(){};},_addClickListenerToScope:function(){var self=this;blissbook.util.Event.onClickDelegateUntil(this._listenerScope,function(el){if(self._isEditablePrivacyContainer(el)){self._onEditablePrivacyContainerClicked(el);return true;}else if(self._isPrivacyFormCancelButton(el)){self._onPrivacyFormCancelButtonClicked(el);return true;}else if(self._isPrivacyFormSaveButton(el)){self._onPrivacyFormSaveButtonClicked(el);return true;}
return false;});},_addMouseoverListenerToScope:function(){var self=this;blissbook.util.Event.onMouseoverDelegateUntil(this._listenerScope,function(el){if(self._isEditablePrivacyContainer(el)){self._onEditablePrivacyContainerMouseover(el);return true;}
return false;});},_onEditablePrivacyContainerClicked:function(el){var serverId=this._getServerIdByEditablePrivacyContainer(el);el.hide();this._getPrivacyFormContainerByServerId(serverId).show();},_onPrivacyFormCancelButtonClicked:function(el){var serverId=this._getServerIdByPrivacyFormCancelButton(el);this._hidePrivacyForm(serverId);},_onPrivacyFormSaveButtonClicked:function(el){var serverId=this._getServerIdByPrivacyFormSaveButton(el);var isPrivate=this._getPrivacyFormPrivateRadioButtonByServerId(serverId).checked;this._controller.doUpdatePhotoPrivacy(serverId,isPrivate);this._hidePrivacyForm(serverId);},_onEditablePrivacyContainerMouseover:function(el){blissbook.util.EffectUtils.highlightIfNotHighlighted(el);},_hidePrivacyForm:function(serverId){this._getPrivacyFormContainerByServerId(serverId).hide();this._getEditablePrivacyContainerByServerId(serverId).show();},_getPrivacyRefreshContainer:function(p){if(!$(this.PRIVACY_CONTAINER_PREFIX+p.getServerId())){return null;}
return $(this.PRIVACY_CONTAINER_PREFIX+p.getServerId()).parentNode;},_isEditablePrivacyContainer:function(el){return this.domIdStartsWith(this.PRIVACY_EDITABLE_CONTAINER_PREFIX,el);},_getServerIdByEditablePrivacyContainer:function(el){return this.sliceServerId(this.PRIVACY_EDITABLE_CONTAINER_PREFIX,el);},_getEditablePrivacyContainerByServerId:function(serverId){return this.getElementById(this.PRIVACY_EDITABLE_CONTAINER_PREFIX,serverId);},_getPrivacyFormContainerByServerId:function(serverId){return this.getElementById(this.PRIVACY_FORM_CONTAINER_PREFIX,serverId);},_getPrivacyFormPrivateRadioButtonByServerId:function(serverId){return this.getElementById(this.PRIVACY_FORM_PRIVATE_RADIO_BUTTON_PREFIX,serverId);},_isPrivacyFormCancelButton:function(el){return this.domIdStartsWith(this.PRIVACY_FORM_CANCEL_BUTTON_PREFIX,el);},_getServerIdByPrivacyFormCancelButton:function(el){return this.sliceServerId(this.PRIVACY_FORM_CANCEL_BUTTON_PREFIX,el);},_isPrivacyFormSaveButton:function(el){return this.domIdStartsWith(this.PRIVACY_FORM_SAVE_BUTTON_PREFIX,el);},_getServerIdByPrivacyFormSaveButton:function(el){return this.sliceServerId(this.PRIVACY_FORM_SAVE_BUTTON_PREFIX,el);},_getXSL:function(){var s=$(this.XSL).value;s=this.swapXSLWithParam(s,'namespace',this.NAMESPACE);var xsl=xmlParse(s);this._getXSL=function(){return xsl;};return xsl;}});blissbook.namespace('blissbook.browser.view.common');blissbook.browser.view.common.RotateLinksTemplate=function(listenerScope){this._listenerScope=listenerScope||document.body;this.NAMESPACE='browser_rotate_links_template_'+
blissbook.browser.view.common.RotateLinksTemplate.instances++;this.ROTATE_LEFT_PREFIX=this.NAMESPACE+'_rotate_left_photo_';this.ROTATE_RIGHT_PREFIX=this.NAMESPACE+'_rotate_right_photo_';this.XSL='browser_rotate_links_template_xsl';this._initSubscribers();};blissbook.browser.view.common.RotateLinksTemplate.instances=0;blissbook.browser.view.common.RotateLinksTemplate.prototype=Object.extend(new blissbook.browser.view.common.AbstractTemplate(),{newComponent:function(container,p){blissbook.util.Assert.isValue($(container),'RotateLinksTemplate.newComponent: container '+container);blissbook.util.Assert.isValue(p,'RotateLinksTemplate.newComponent: no p');$(container).innerHTML=this._linksHTML(p);},_initSubscribers:function(){blissbook.browser.event.EventBus.addDOMReadyListener(this._onDOMReady.bind(this));},_onDOMReady:function(){blissbook.util.Assert.isValue($(this._listenerScope),'RotateLinksTemplate._onDOMReady: listenerScope '+this._listenerScope);this._addClickListenerToScope();},_addClickListenerToScope:function(){var self=this;blissbook.util.Event.onClickDelegateUntil(this._listenerScope,function(el){if(self._isRotateLeftLink(el)){self._onRotateLeftLinkClicked(el);return true;}else if(self._isRotateRightLink(el)){self._onRotateRightLinkClicked(el);return true;}
return false;});},_onRotateLeftLinkClicked:function(el){var serverId=this._getServerIdByRotateLeftLink(el);blissbook.browser.controller.BrowserController.doRotatePhoto(serverId,-90);},_onRotateRightLinkClicked:function(el){var serverId=this._getServerIdByRotateRightLink(el);blissbook.browser.controller.BrowserController.doRotatePhoto(serverId,90);},_isRotateLeftLink:function(el){return this.domIdStartsWith(this.ROTATE_LEFT_PREFIX,el);},_getServerIdByRotateLeftLink:function(el){return this.sliceServerId(this.ROTATE_LEFT_PREFIX,el);},_isRotateRightLink:function(el){return this.domIdStartsWith(this.ROTATE_RIGHT_PREFIX,el);},_getServerIdByRotateRightLink:function(el){return this.sliceServerId(this.ROTATE_RIGHT_PREFIX,el);},_linksHTML:function(p){return xsltProcess(p.toXML(),this._getXSL());},_getXSL:function(){var s=$(this.XSL).value;s=this.swapXSLWithParam(s,'namespace',this.NAMESPACE);var xsl=xmlParse(s);this._getXSL=function(){return xsl;};return xsl;}});blissbook.namespace('blissbook.browser.view.common');blissbook.browser.view.common.DeleteLinkTemplate=function(listenerScope){this._listenerScope=listenerScope||document.body;this.NAMESPACE='browser_delete_template_'+
blissbook.browser.view.common.DeleteLinkTemplate.instances++;this.DELETE_PREFIX=this.NAMESPACE+'_delete_photo_';this.XSL='browser_delete_link_template_xsl';this._initSubscribers();};blissbook.browser.view.common.DeleteLinkTemplate.instances=0;blissbook.browser.view.common.DeleteLinkTemplate.prototype=Object.extend(new blissbook.browser.view.common.AbstractTemplate(),{newComponent:function(container,p){blissbook.util.Assert.isValue($(container),'DeleteLinkTemplate.newComponent: container '+container);blissbook.util.Assert.isValue(p,'DeleteLinkTemplate.newComponent: no p');$(container).innerHTML=this._linkHTML(p);},_initSubscribers:function(){blissbook.browser.event.EventBus.addDOMReadyListener(this._onDOMReady.bind(this));},_onDOMReady:function(){blissbook.util.Assert.isValue($(this._listenerScope),'DeleteLinkTemplate._onDOMReady: listenerScope '+this._listenerScope);this._addClickListenerToScope();},_addClickListenerToScope:function(){var self=this;blissbook.util.Event.onClickDelegateUntil(this._listenerScope,function(el){if(self._isDeleteLink(el)){self._onDeleteLinkClicked(el);return true;}});},_onDeleteLinkClicked:function(el){var serverId=this._getServerIdByDeleteLink(el);blissbook.browser.controller.BrowserController.doDeletePhoto(serverId);},_isDeleteLink:function(el){return this.domIdStartsWith(this.DELETE_PREFIX,el);},_getServerIdByDeleteLink:function(el){return this.sliceServerId(this.DELETE_PREFIX,el);},_linkHTML:function(p){return xsltProcess(p.toXML(),this._getXSL());},_getXSL:function(){var s=$(this.XSL).value;s=this.swapXSLWithParam(s,'namespace',this.NAMESPACE);var xsl=xmlParse(s);this._getXSL=function(){return xsl;};return xsl;}});blissbook.namespace('blissbook.browser.view.common');blissbook.browser.view.common.ScrollerTemplate=function(listenerScope){this.NAMESPACE='browser_scroller_template_'+
blissbook.browser.view.common.ScrollerTemplate.instances++;this.PREV_LINK_PREFIX=this.NAMESPACE+'_scroller_prev_';this.NEXT_LINK_PREFIX=this.NAMESPACE+'_scroller_next_';this.XSL='browser_single_scroller_xsl';this._listenerScope=listenerScope||document.body;this._controller=blissbook.browser.controller.BrowserController;};blissbook.browser.view.common.ScrollerTemplate.instances=0;blissbook.browser.view.common.ScrollerTemplate.prototype=Object.extend(new blissbook.browser.view.common.AbstractTemplate(),{newComponent:function(container,pNext,pPrev){blissbook.util.Assert.isValue($(container),'ScrollerTemplate.newComponent: container '+container);this._ensureDOMEventHandlers();$(container).innerHTML=this._scrollerHTML(pNext,pPrev);},_scrollerHTML:function(pNext,pPrev){return xsltProcess(this._getXML(pNext,pPrev),this._getXSL());},_ensureDOMEventHandlers:function(){blissbook.util.Assert.isValue($(this._listenerScope),'ScrollerTemplate._ensureDOMEventHandlers: listenerScope '+this._listenerScope);this._addClickListenerToScope();this._ensureDOMEventHandlers=function(){};},_addClickListenerToScope:function(){var self=this;blissbook.util.Event.onClickDelegateUntil(this._listenerScope,function(el){if(self._isPrevPhotoLink(el)){self._onPrevPhotoLinkClicked(el);return true;}else if(self._isNextPhotoLink(el)){self._onNextPhotoLinkClicked(el);return true;}
return false;});},_onPrevPhotoLinkClicked:function(el){var serverId=this.sliceServerId(this.PREV_LINK_PREFIX,el);this._controller.goFocus(serverId);},_onNextPhotoLinkClicked:function(el){var serverId=this.sliceServerId(this.NEXT_LINK_PREFIX,el);this._controller.goFocus(serverId);},_isPrevPhotoLink:function(el){return this.domIdStartsWith(this.PREV_LINK_PREFIX,el);},_isNextPhotoLink:function(el){return this.domIdStartsWith(this.NEXT_LINK_PREFIX,el);},_getXML:function(pNext,pPrev){var nextServerId=pNext?pNext.getServerId():'';var prevServerId=pPrev?pPrev.getServerId():'';var sb=[];sb.push('<neighbors>');sb.push('<prevServerId>',prevServerId,'</prevServerId>');sb.push('<nextServerId>',nextServerId,'</nextServerId>');sb.push('</neighbors>');return xmlParse(sb.join(''));},_getXSL:function(){var s=$(this.XSL).value;s=this.swapXSLWithParam(s,'namespace',this.NAMESPACE);var xsl=xmlParse(s);this._getXSL=function(){return xsl;};return xsl;}})
blissbook.namespace('blissbook.browser.view.common');blissbook.browser.view.common.SmallImageTemplate=function(listenerScope){this._listenerScope=listenerScope||document.body;this.NAMESPACE='browser_small_image_template_'+
blissbook.browser.view.common.SmallImageTemplate.instances++;this.IMAGE_PREFIX=this.NAMESPACE+'_small_image_';this.XSL='browser_small_image_template_xsl';this._controller=blissbook.browser.controller.BrowserController;this._initSubscribers();};blissbook.browser.view.common.SmallImageTemplate.instances=0;blissbook.browser.view.common.SmallImageTemplate.prototype=Object.extend(new blissbook.browser.view.common.AbstractTemplate(),{newComponent:function(container,p){blissbook.util.Assert.isValue($(container),'SmallImageTemplate.newComponent: container '+container);blissbook.util.Assert.isValue(p,'SmallImageTemplate.newComponent: no p');this._ensureDOMEventHandlers();$(container).innerHTML=this._imageHTML(p);},_initSubscribers:function(){blissbook.browser.event.EventBus.addPhotoURLChangeListener(this._onPhotoURLChange.bind(this));},_onPhotoURLChange:function(event){this._refreshSmallImage(event.getPhoto());},_refreshSmallImage:function(p){if(!$(this.IMAGE_PREFIX+p.getServerId())){return;}
$(this.IMAGE_PREFIX+p.getServerId()).src=p.getSmallImageURL();},_imageHTML:function(p){return xsltProcess(p.toXML(),this._getXSL());},_ensureDOMEventHandlers:function(){blissbook.util.Assert.isValue($(this._listenerScope),'SmallImageTemplate._ensureDOMEventHandlers: listenerScope: '+this._listenerScope);this._addClickListenerToScope();this._ensureDOMEventHandlers=function(){};},_addClickListenerToScope:function(){var self=this;blissbook.util.Event.onClickDelegateUntil(this._listenerScope,function(el){if(self._isPhotoImage(el)){self._onPhotoImageClicked(el);return true;}
return false;});},_isPhotoImage:function(el){return this.domIdStartsWith(this.IMAGE_PREFIX,el);},_onPhotoImageClicked:function(el){var serverId=this.sliceServerId(this.IMAGE_PREFIX,el);this._controller.goSingle(serverId);},_getXSL:function(){var s=$(this.XSL).value;s=this.swapXSLWithParam(s,'namespace',this.NAMESPACE);var xsl=xmlParse(s);this._getXSL=function(){return xsl;};return xsl;}});blissbook.namespace('blissbook.browser.view.common');blissbook.browser.view.common.TagFormTemplate=function(listenerScope){this._listenerScope=listenerScope||document.body;this.NAMESPACE='browser_tag_form_template_'+
blissbook.browser.view.common.TagFormTemplate.instances++;this.TAG_LABEL_PREFIX=this.NAMESPACE+'_tagging_label_';this.TAG_HINT_PREFIX=this.NAMESPACE+'_tagging_hint_';this.FORM_ERROR_PREFIX=this.NAMESPACE+'_form_error_';this.FORM_TEXT_PREFIX=this.NAMESPACE+'_form_text_';this.FORM_SUBMIT_BUTTON_PREFIX=this.NAMESPACE+'_form_submit_';this.XSL='browser_tag_form_template_xsl';this._controller=blissbook.browser.controller.BrowserController;this._initSubscribers();};blissbook.browser.view.common.TagFormTemplate.instances=0;blissbook.browser.view.common.TagFormTemplate.prototype=Object.extend(new blissbook.browser.view.common.AbstractTemplate(),{newComponent:function(container,p,tabindex){blissbook.util.Assert.isValue($(container),'TagFormTemplate.newComponent: container '+container);blissbook.util.Assert.isValue(p,'TagFormTemplate.newComponent: no p');this._ensureDOMEventHandlers();$(container).innerHTML=this._formHTML(p,tabindex);},focusTextField:function(serverId){if(this._getFormTextFieldByServerId(serverId)){try{this._getFormTextFieldByServerId(serverId).focus();}catch(e){}}},_initSubscribers:function(){blissbook.browser.event.EventBus.addPhotoTagsChangeListener(this._onPhotoTagsChange.bind(this));},_onPhotoTagsChange:function(event){if(event.tagsAdded()){this._clearTagInputField(event.getPhoto().getServerId());}},_clearTagInputField:function(serverId){if(!this._getFormTextFieldByServerId(serverId)){return;}
this._getFormTextFieldByServerId(serverId).value='';},_formHTML:function(p,tabindex){return xsltProcess(p.toXML(),this._getXSL(tabindex));},_ensureDOMEventHandlers:function(){blissbook.util.Assert.isValue($(this._listenerScope),'TagFormTemplate._ensureDOMEventHandlers: listenerScope '+this._listenerScope);this._addClickListenerToScope();this._addMouseoverListenerToScope();this._addMouseoutListenerToScope();this._addKeydownListenerToScope();this._ensureDOMEventHandlers=function(){};},_addClickListenerToScope:function(){var self=this;blissbook.util.Event.onClickDelegateUntil(this._listenerScope,function(el){if(self._isFormSubmitButton(el)){self._onTagFormSubmitButtonClicked(el);return true;}
return false;});},_addMouseoverListenerToScope:function(){var self=this;blissbook.util.Event.onMouseoverDelegateUntil(this._listenerScope,function(el){if(self._isTagsLabel(el)){self._onTagsLabelMouseover(el);return true;}
return false;});},_addMouseoutListenerToScope:function(){var self=this;blissbook.util.Event.onMouseoutDelegateUntil(this._listenerScope,function(el){if(self._isTagsLabel(el)){self._onTagsLabelMouseout(el);return true;}
return false;});},_addKeydownListenerToScope:function(){var self=this;Event.observe(this._listenerScope,'keydown',function(event){var el=Event.element(event);if(event.keyCode===Event.KEY_RETURN&&self._isTagFormTextField(el)){self._onTagFormTextFieldEnterKeydown(el);}});},_onTagFormSubmitButtonClicked:function(el){var serverId=this._getServerIdByFormSubmitButton(el);this._doTagFormSubmit(serverId);},_onTagFormTextFieldEnterKeydown:function(el){var serverId=this._getServerIdByTagFormTextField(el);this._doTagFormSubmit(serverId);},_doTagFormSubmit:function(serverId){var tags=this._getFormTextFieldByServerId(serverId).value;var errMsg=this._controller.doAddTags(serverId,tags);if(errMsg){this._getFormTextFieldErrorContainerByServerId(serverId).update(errMsg).show();}else{this._getFormTextFieldErrorContainerByServerId(serverId).update('&nbsp;').hide();}},_onTagsLabelMouseover:function(el){var serverId=this._getServerIdByTagsLabel(el);this._getTagsHintByServerId(serverId).show();},_onTagsLabelMouseout:function(el){var serverId=this._getServerIdByTagsLabel(el);this._getTagsHintByServerId(serverId).hide();},_isTagsLabel:function(el){return this.domIdStartsWith(this.TAG_LABEL_PREFIX,el);},_getServerIdByTagsLabel:function(el){return this.sliceServerId(this.TAG_LABEL_PREFIX,el);},_getTagsHintByServerId:function(serverId){return this.getElementById(this.TAG_HINT_PREFIX,serverId);},_isFormSubmitButton:function(el){return this.domIdStartsWith(this.FORM_SUBMIT_BUTTON_PREFIX,el);},_getServerIdByFormSubmitButton:function(el){return this.sliceServerId(this.FORM_SUBMIT_BUTTON_PREFIX,el);},_isTagFormTextField:function(el){return this.domIdStartsWith(this.FORM_TEXT_PREFIX,el);},_getServerIdByTagFormTextField:function(el){return this.sliceServerId(this.FORM_TEXT_PREFIX,el);},_getFormTextFieldByServerId:function(serverId){return this.getElementById(this.FORM_TEXT_PREFIX,serverId);},_getFormTextFieldErrorContainerByServerId:function(serverId){return this.getElementById(this.FORM_ERROR_PREFIX,serverId);},_getXSL:function(tabindex){if(blissbook.util.LangUtils.isNotNumber(tabindex)){tabindex='';}else if(tabindex<=0){tabindex=1;}
var s=$(this.XSL).value;s=this.swapXSLWithParam(s,'namespace',this.NAMESPACE);s=this.swapXSLWithParam(s,'tabindex_text',tabindex);return xmlParse(s);}});blissbook.namespace('blissbook.browser.view.common');blissbook.browser.view.common.TagsTemplate=function(listenerScope){this._listenerScope=listenerScope||document.body;this.NAMESPACE='browser_tags_template_'+
blissbook.browser.view.common.TagsTemplate.instances++;this.TAG_CONTAINER_PREFIX=this.NAMESPACE+'_tag_container_';this.TAG_REMOVE_PREFIX=this.NAMESPACE+'_remove_tag_';this.TAG_NAME_REGEX=new RegExp('^'+this.TAG_REMOVE_PREFIX+'[\\d]+_(.*)$');this.SERVER_ID_REGEX=new RegExp('^'+this.TAG_REMOVE_PREFIX+'([\\d]+)_.*$')
this.XSL='browser_tags_template_xsl';this._controller=blissbook.browser.controller.BrowserController;this._initSubscribers();};blissbook.browser.view.common.TagsTemplate.instances=0;blissbook.browser.view.common.TagsTemplate.prototype=Object.extend(new blissbook.browser.view.common.AbstractTemplate(),{newComponent:function(container,p){blissbook.util.Assert.isValue($(container),'TagsTemplate.newComponent: container '+container);blissbook.util.Assert.isValue(p,'TagsTemplate.newComponent: no p');this._ensureDOMEventHandlers();$(container).innerHTML=this._tagsHTML(p);},_initSubscribers:function(){blissbook.browser.event.EventBus.addPhotoTagsChangeListener(this._onPhotoTagsChange.bind(this));},_onPhotoTagsChange:function(event){this._refreshTags(event.getPhoto());},_refreshTags:function(p){if(!this._getRefreshContainer(p)){return;}
this._getRefreshContainer(p).innerHTML=this._tagsHTML(p);},_tagsHTML:function(p){return xsltProcess(p.toXML(),this._getXSL());},_ensureDOMEventHandlers:function(){blissbook.util.Assert.isValue($(this._listenerScope),'TagsTemplate._ensureDOMEventHandlers: listenerScope '+this._listenerScope);this._addClickListenerToScope();this._ensureDOMEventHandlers=function(){};},_addClickListenerToScope:function(){var self=this;blissbook.util.Event.onClickDelegateUntil(this._listenerScope,function(el){if(self._isTagRemoveLink(el)){self._onTagRemoveLinkClicked(el);return true;}
return false;});},_onTagRemoveLinkClicked:function(el){var serverId=this._getServerIdByTagRemoveLink(el);var tag=this._getTagByTagRemoveLink(el);this._controller.doRemoveTag(serverId,tag);},_getRefreshContainer:function(p){if(!$(this.TAG_CONTAINER_PREFIX+p.getServerId())){return null;}
return $(this.TAG_CONTAINER_PREFIX+p.getServerId()).parentNode;},_isTagRemoveLink:function(el){return this.domIdStartsWith(this.TAG_REMOVE_PREFIX,el);},_getTagByTagRemoveLink:function(el){return el.id.match(this.TAG_NAME_REGEX)[1];},_getServerIdByTagRemoveLink:function(el){return parseInt(el.id.match(this.SERVER_ID_REGEX)[1]);},_getXSL:function(){var s=$(this.XSL).value;s=this.swapXSLWithParam(s,'namespace',this.NAMESPACE);var xsl=xmlParse(s);this._getXSL=function(){return xsl};return xsl;}});blissbook.namespace('blissbook.browser.view.common');blissbook.browser.view.common.ThumbImageTemplate=function(listenerScope){this.NAMESPACE='browser_thumb_image_template_'+
blissbook.browser.view.common.ThumbImageTemplate.instances++;this.IMAGE_PREFIX=this.NAMESPACE+'_thumb_image_';this.MAGNIFY_OFFSET_TOP=5;this.MAGNIFY_OFFSET_LEFT=5;this.CSS_FOCUS_THUMBNAIL='browser_thumbnail_panel_focus_thumbnail';this.XSL='browser_thumb_image_template_xsl';this._listenerScope=listenerScope||document.body;this._focusImg;this._controller=blissbook.browser.controller.BrowserController;this._initSubscribers();};blissbook.browser.view.common.ThumbImageTemplate.instances=0;blissbook.browser.view.common.ThumbImageTemplate.prototype=Object.extend(new blissbook.browser.view.common.AbstractTemplate(),{newComponent:function(container,p){blissbook.util.Assert.isValue($(container),'ThumbImageTemplate.newComponent: container '+container);blissbook.util.Assert.isValue(p,'ThumbImageTemplate.newComponent: no p');this._ensureDOMEventHandlers();$(container).innerHTML=this._thumbHTML(p);},_initSubscribers:function(){var EventBus=blissbook.browser.event.EventBus;EventBus.addPhotoURLChangeListener(this._onPhotoURLChange.bind(this));EventBus.addFocusChangeListener(this._onFocusChange.bind(this));},_onPhotoURLChange:function(event){this._refreshThumbImage(event.getPhoto());},_refreshThumbImage:function(p){if(!this._getThumbImageByServerId(p.getServerId())){return;}
var img=this._getThumbImageByServerId(p.getServerId());img.src=p.getThumbnailImageURL();},_onFocusChange:function(event){if(!event.getFocusPhoto()){return;}
this._moveFocusHighlight(event.getFocusPhoto());},_moveFocusHighlight:function(p){if(this._focusImg){this._focusImg.removeClassName(this.CSS_FOCUS_THUMBNAIL);}
if(this._getThumbImageByServerId(p.getServerId())){this._focusImg=this._getThumbImageByServerId(p.getServerId());this._focusImg.addClassName(this.CSS_FOCUS_THUMBNAIL);}},_thumbHTML:function(p){return xsltProcess(p.toXML(),this._getXSL());},_ensureDOMEventHandlers:function(){blissbook.util.Assert.isValue($(this._listenerScope),'ThumbImageTemplate._ensureDOMEventHandlers: listenerScope '+this._listenerScope);this._addClickListenerToScope();this._addMouseoverListenerToScope();this._ensureDOMEventHandlers=function(){};},_addClickListenerToScope:function(){var self=this;blissbook.util.Event.onClickDelegateUntil(this._listenerScope,function(el){if(self._isThumbImage(el)){self._onThumbImageClicked(el);return true;}
return false;});},_addMouseoverListenerToScope:function(){var self=this;blissbook.util.Event.onMouseoverDelegateUntil(this._listenerScope,function(el){if(self._isThumbImage(el)){self._onThumbImageMouseover(el);return true;}
return false;});},_onThumbImageClicked:function(el){var serverId=this.sliceServerId(this.IMAGE_PREFIX,el);this._controller.goFocus(serverId);},_onThumbImageMouseover:function(el){var serverId=this.sliceServerId(this.IMAGE_PREFIX,el);var coors=Position.cumulativeOffset(el);var top=coors[1]+this.MAGNIFY_OFFSET_TOP;var left=coors[0]+this.MAGNIFY_OFFSET_LEFT;this._controller.goMagnify(serverId,top,left);},_isThumbImage:function(el){return this.domIdStartsWith(this.IMAGE_PREFIX,el);},_getThumbImageByServerId:function(serverId){return $(this.IMAGE_PREFIX+serverId);},_getXSL:function(){var s=$(this.XSL).value;s=this.swapXSLWithParam(s,'namespace',this.NAMESPACE);var xsl=xmlParse(s);this._getXSL=function(){return xsl;};return xsl;}});blissbook.namespace('blissbook.browser.view.common');blissbook.browser.view.common.TitleTemplate=function(listenerScope){this._listenerScope=listenerScope||document.body;this.NAMESPACE='browser_title_template_'+
blissbook.browser.view.common.TitleTemplate.instances++;this.TITLE_CONTAINER_PREFIX=this.NAMESPACE+'_title_container_';this.TITLE_EDITABLE_CONTAINER_PREFIX=this.NAMESPACE+'_title_current_';this.TITLE_FORM_CONTAINER_PREFIX=this.NAMESPACE+'_title_edit_';this.TITLE_FORM_TEXT_FIELD_PREFIX=this.NAMESPACE+'_title_edit_text_';this.TITLE_FORM_SAVE_BUTTON_PREFIX=this.NAMESPACE+'_title_edit_save_';this.TITLE_FORM_CANCEL_BUTTON_PREFIX=this.NAMESPACE+'_title_edit_cancel_';this.XSL='browser_title_template_xsl';this._controller=blissbook.browser.controller.BrowserController;this._initSubscribers();};blissbook.browser.view.common.TitleTemplate.instances=0;blissbook.browser.view.common.TitleTemplate.prototype=Object.extend(new blissbook.browser.view.common.AbstractTemplate(),{newComponent:function(container,p){blissbook.util.Assert.isValue($(container),'TitleTemplate.newComponent: container '+container);blissbook.util.Assert.isValue(p,'TitleTemplate.newComponent: no p');this._ensureDOMEventHandlers();$(container).innerHTML=this._titleHTML(p);},_initSubscribers:function(){blissbook.browser.event.EventBus.addPhotoTitleChangeListener(this._onPhotoTitleChange.bind(this));},_onPhotoTitleChange:function(event){this._refreshTitle(event.getPhoto());},_refreshTitle:function(p){if(!this._getTitleRefreshContainer(p)){return;}
var container=this._getTitleRefreshContainer(p);container.innerHTML=this._titleHTML(p);blissbook.util.EffectUtils.highlightIfNotHighlighted(container);},_titleHTML:function(p){return xsltProcess(p.toXML(),this._getXSL());},_ensureDOMEventHandlers:function(){blissbook.util.Assert.isValue($(this._listenerScope),'TitleTemplate._ensureDOMEventHandlers: listenerScope '+this._listenerScope);this._addClickListenerToScope();this._addMouseoverListenerToScope();this._ensureDOMEventHandlers=function(){};},_addClickListenerToScope:function(){var self=this;blissbook.util.Event.onClickDelegateUntil(this._listenerScope,function(el){if(self._isEditableTitleContainer(el)){self._onEditableTitleContainerClicked(el);return true;}else if(self._isTitleFormCancelButton(el)){self._onTitleFormCancelButtonClicked(el);return true;}else if(self._isTitleFormSaveButton(el)){self._onTitleFormSaveButtonClicked(el);return true;}
return false;});},_addMouseoverListenerToScope:function(){var self=this;blissbook.util.Event.onMouseoverDelegateUntil(this._listenerScope,function(el){if(self._isEditableTitleContainer(el)){self._onEditableTitleContainerMouseover(el);return true;}
return false;});},_onEditableTitleContainerMouseover:function(el){blissbook.util.EffectUtils.highlightIfNotHighlighted(el);},_onEditableTitleContainerClicked:function(el){el.hide();var serverId=this._getServerIdByEditableTitleContainer(el);this._getTitleFormContainerByServerId(serverId).show();},_onTitleFormCancelButtonClicked:function(el){var serverId=this._getServerIdByTitleFormCancelButton(el);this._hideTitleForm(serverId);},_onTitleFormSaveButtonClicked:function(el){var serverId=this._getServerIdByTitleFormSaveButton(el);var title=this._getTitleFormTextFieldByServerId(serverId).value;this._hideTitleForm(serverId);this._controller.doUpdatePhotoTitle(serverId,title);},_hideTitleForm:function(serverId){this._getTitleFormContainerByServerId(serverId).hide();this._getEditableTitleContainerByServerId(serverId).show();},_getTitleRefreshContainer:function(p){if(!$(this.TITLE_CONTAINER_PREFIX+p.getServerId())){return null;}
return $(this.TITLE_CONTAINER_PREFIX+p.getServerId()).parentNode;},_isEditableTitleContainer:function(el){return this.domIdStartsWith(this.TITLE_EDITABLE_CONTAINER_PREFIX,el);},_getEditableTitleContainerByServerId:function(serverId){return this.getElementById(this.TITLE_EDITABLE_CONTAINER_PREFIX,serverId);},_getServerIdByEditableTitleContainer:function(el){return this.sliceServerId(this.TITLE_EDITABLE_CONTAINER_PREFIX,el);},_getTitleFormContainerByServerId:function(serverId){return this.getElementById(this.TITLE_FORM_CONTAINER_PREFIX,serverId);},_getTitleFormTextFieldByServerId:function(serverId){return this.getElementById(this.TITLE_FORM_TEXT_FIELD_PREFIX,serverId);},_isTitleFormSaveButton:function(el){return this.domIdStartsWith(this.TITLE_FORM_SAVE_BUTTON_PREFIX,el);},_getServerIdByTitleFormSaveButton:function(el){return this.sliceServerId(this.TITLE_FORM_SAVE_BUTTON_PREFIX,el);},_isTitleFormCancelButton:function(el){return this.domIdStartsWith(this.TITLE_FORM_CANCEL_BUTTON_PREFIX,el);},_getServerIdByTitleFormCancelButton:function(el){return this.sliceServerId(this.TITLE_FORM_CANCEL_BUTTON_PREFIX,el);},_getXSL:function(){var s=$(this.XSL).value;s=this.swapXSLWithParam(s,'namespace',this.NAMESPACE);var xsl=xmlParse(s);this._getXSL=function(){return xsl};return xsl;}});blissbook.namespace('blissbook.browser.common');blissbook.browser.view.common.UploadedByTemplate=function(){this.NAMESPACE='browser_uploaded_by_template_'+
blissbook.browser.view.common.UploadedByTemplate.instances++;this.XSL='browser_uploaded_by_template_xsl';};blissbook.browser.view.common.UploadedByTemplate.instances=0;blissbook.browser.view.common.UploadedByTemplate.prototype=Object.extend(new blissbook.browser.view.common.AbstractTemplate(),{newComponent:function(container,p){var html=xsltProcess(p.toXML(),this._getXSL());$(container).innerHTML=html;},_getXSL:function(){var s=$(this.XSL).value;s=this.swapXSLWithParam(s,'namespace',this.NAMESPACE);var xsl=xmlParse(s);this._getXSL=function(){return xsl;};return xsl;}})
blissbook.namespace('blissbook.browser.view.common');blissbook.browser.view.common.VendorsTemplate=function(){this.NAMESPACE='browser_vendors_template_'+
blissbook.browser.view.common.VendorsTemplate.instances++;this.CONTAINER_PREFIX=this.NAMESPACE+'_container_';this.XSL='browser_vendors_template_xsl';this._initSubscribers();};blissbook.browser.view.common.VendorsTemplate.instances=0;blissbook.browser.view.common.VendorsTemplate.prototype=Object.extend(new blissbook.browser.view.common.AbstractTemplate(),{newComponent:function(container,p){$(container).innerHTML=this._vendorsHTML(p);},_initSubscribers:function(){var EventBus=blissbook.browser.event.EventBus;EventBus.addPhotoTagsChangeListener(this._onPhotoTagsChange.bind(this));EventBus.addPhotoProfessionalChangeListener(this._onPhotoProfessionalChange.bind(this));},_onPhotoTagsChange:function(event){this._refreshVendors(event.getPhoto());},_onPhotoProfessionalChange:function(event){this._refreshVendors(event.getPhoto());},_refreshVendors:function(p){if(!this._getRefreshContainer(p)){return;}
this._getRefreshContainer(p).innerHTML=this._vendorsHTML(p);},_vendorsHTML:function(p){return xsltProcess(p.toXML(),this._getXSL());},_getRefreshContainer:function(p){if(!$(this.CONTAINER_PREFIX+p.getServerId())){return null;}
return $(this.CONTAINER_PREFIX+p.getServerId()).parentNode;},_getXSL:function(){var s=$(this.XSL).value;s=this.swapXSLWithParam(s,'namespace',this.NAMESPACE);var xsl=xmlParse(s);this._getXSL=function(){return xsl;};return xsl;}})
blissbook.namespace('blissbook.browser.view.common');blissbook.browser.view.common.VendorWeddingButtonTemplate=function(){this.NAMESPACE='browser_vendor_wedding_button_template_'+
blissbook.browser.view.common.VendorWeddingButtonTemplate.instances++;this.XSL='browser_vendor_wedding_button_template_xsl';};blissbook.browser.view.common.VendorWeddingButtonTemplate.instances=0;blissbook.browser.view.common.VendorWeddingButtonTemplate.prototype=Object.extend(new blissbook.browser.view.common.AbstractTemplate(),{newComponent:function(container,p){var html=xsltProcess(p.toXML(),this._getXSL());$(container).innerHTML=html;},_getXSL:function(){var s=$(this.XSL).value;s=this.swapXSLWithParam(s,'namespace',this.NAMESPACE);var xsl=xmlParse(s);this._getXSL=function(){return xsl;};return xsl;}});blissbook.namespace('blissbook.browser.view.dialog');blissbook.browser.view.dialog.ConfirmTagDialog=function(){this.HTML='browser_confirm_tag_dialog_html';this.OK_BUTTON='browser_confirm_tag_dialog_ok';};blissbook.browser.view.dialog.ConfirmTagDialog.prototype={open:function(o){var Assert=blissbook.util.Assert;Assert.notBlank(o.tags,'ConfirmTagDialog.open: no tags');Assert.isFunction(o.onConfirm,'ConfirmTagDialog.open: no callback');Assert.id(this.HTML,'ConfirmTagDialog.open: textarea not in dom');var self=this;Control.Modal.open($(this.HTML).value,{afterOpen:function(){$(self.OK_BUTTON).onclick=function(){Control.Modal.close();o.onConfirm();}}});}};blissbook.namespace('blissbook.browser.view.dialog');blissbook.browser.view.dialog.DeleteIdeaDialog=function(){this.XSL='browser_delete_idea_dialog_xsl';this.OK_BUTTON='browser_delete_idea_dialog_ok';};blissbook.browser.view.dialog.DeleteIdeaDialog.prototype={open:function(o){blissbook.util.Assert.isFunction(o.onConfirm,'DeleteIdeaDialog.open: no callback');var xml=xmlParse(['<root><title>',o.title,'</title></root>'].join(''));var self=this;Control.Modal.open(xsltProcess(xml,this._getXSL()),{afterOpen:function(){$(self.OK_BUTTON).onclick=function(){Control.Modal.close();o.onConfirm();};}});},_getXSL:function(){blissbook.util.Assert.id(this.XSL,'DeleteIdeaDialog._getXSL: textarea not in dom');var xsl=xmlParse($(this.XSL).value);this._getXSL=function(){return xsl;};return xsl;}}
blissbook.namespace('blissbook.browser.view.dialog');blissbook.browser.view.dialog.DeleteIdeaTagDialog=function(){this.XSL='browser_delete_idea_tag_dialog_xsl';this.OK_BUTTON='browser_delete_idea_tag_dialog_ok';};blissbook.browser.view.dialog.DeleteIdeaTagDialog.prototype={open:function(o){blissbook.util.Assert.isFunction(o.onConfirm,'DeleteIdeaTagDialog.open: no callback');var xml=xmlParse(['<root><tag>',o.tag,'</tag></root>'].join(''));var self=this;Control.Modal.open(xsltProcess(xml,this._getXSL()),{afterOpen:function(){$(self.OK_BUTTON).onclick=function(){Control.Modal.close();o.onConfirm();};}});},_getXSL:function(){blissbook.util.Assert.id(this.XSL,'DeleteIdeaTagDialog._getXSL: textarea not in dom');var xsl=xmlParse($(this.XSL).value);this._getXSL=function(){return xsl;};return xsl;}}
blissbook.namespace('blissbook.browser.view.dialog');blissbook.browser.view.dialog.DeletePhotoDialog=function(){this.DELETE_OK='browser_delete_photo_dialog_ok';this.DELETE_MODAL_XSL='browser_delete_photo_dialog_xsl';};blissbook.browser.view.dialog.DeletePhotoDialog.prototype={open:function(o){blissbook.util.Assert.isFunction(o.onConfirm,'DeletePhotoDialog.open: no callback');o.title=o.title||'';var sb=['<title>',o.title,'<title>'];var html=xsltProcess(xmlParse(sb.join('')),this._getDialogXSL());var self=this;Control.Modal.open(html,{afterOpen:function(){$(self.DELETE_OK).onclick=function(){Control.Modal.close();o.onConfirm();};}});},_getDialogXSL:function(){blissbook.util.Assert.id(this.DELETE_MODAL_XSL,'DeletePhotoDialog._getDialogXSL:')
var xsl=xmlParse($(this.DELETE_MODAL_XSL).value)
this._getDialogXSL=function(){return xsl;};return xsl;}}
blissbook.namespace('blissbook.browser.view.dialog');blissbook.browser.view.dialog.DeleteTagDialog=function(){this.XSL='browser_delete_tag_dialog_xsl';this.OK_BUTTON='browser_delete_tag_dialog_ok';};blissbook.browser.view.dialog.DeleteTagDialog.prototype={open:function(o){blissbook.util.Assert.isFunction(o.onConfirm,'DeleteTagDialog.open: no callback');var xml=xmlParse(['<root><tag>',o.tag,'</tag></root>'].join(''));var self=this;Control.Modal.open(xsltProcess(xml,this._getXSL()),{afterOpen:function(){$(self.OK_BUTTON).onclick=function(){Control.Modal.close();o.onConfirm();};}});},_getXSL:function(){blissbook.util.Assert.id(this.XSL,'DeleteTagDialog._getXSL: textarea not in dom');var xsl=xmlParse($(this.XSL).value);this._getXSL=function(){return xsl;};return xsl;}}
blissbook.namespace('blissbook.browser.view.dialog');blissbook.browser.view.dialog.ReportPhotoDialog=function(){this.BLURRY_OK='browser_report_photo_dialog_blurry_ok';this.BLURRY_XSL='browser_report_photo_dialog_blurry_xsl';this.EXPLICIT_OK='browser_report_photo_dialog_explicit_ok';this.EXPLICIT_XSL='browser_report_photo_dialog_explicit_xsl';};blissbook.browser.view.dialog.ReportPhotoDialog.prototype={confirmBlurry:function(o){var Assert=blissbook.util.Assert;Assert.isValue(o.photo,'ReportPhotoDialog.confirmBlurry: no photo');Assert.isFunction(o.onConfirm,'ReportPhotoDialog.confirmBlurry: no callback');var html=xsltProcess(o.photo.toXML(),this._getBlurryXSL());var self=this;Control.Modal.open(html,{afterOpen:function(){$(self.BLURRY_OK).onclick=function(){Control.Modal.close();o.onConfirm();}}});},confirmExplicit:function(o){var Assert=blissbook.util.Assert;Assert.isValue(o.photo,'ReportPhotoDialog.confirmExplicit: no photo');Assert.isFunction(o.onConfirm,'ReportPhotoDialog.confirmExplicit: no callback');var html=xsltProcess(o.photo.toXML(),this._getExplicitXSL());var self=this;Control.Modal.open(html,{afterOpen:function(){$(self.EXPLICIT_OK).onclick=function(){Control.Modal.close();o.onConfirm();}}});},_getBlurryXSL:function(){blissbook.util.Assert.id(this.BLURRY_XSL,'ReportPhotoDialog._getBlurryXSL');var xsl=xmlParse($(this.BLURRY_XSL).value);this._getBlurryXSL=function(){return xsl;};return xsl;},_getExplicitXSL:function(){blissbook.util.Assert.id(this.EXPLICIT_XSL,'ReportPhotoDialog._getExplicitXSL:');var xsl=xmlParse($(this.EXPLICIT_XSL).value);this._getExplicitXSL=function(){return xsl;};return xsl;}}
blissbook.namespace('blissbook.browser.view');blissbook.browser.view.DetailsView=function(containerDomId,renderer){blissbook.util.Assert.hasInterface(renderer,blissbook.browser.view.IPhotoCollectionRenderer,'DetailsView.constructor: ');this.CONTAINER=containerDomId;this._renderer=renderer;this._needsRendering=false;this._initSubscribers();};Object.extend(blissbook.browser.view.DetailsView,{CONTAINER_DOM_ID:'browser_details_view_conainer',createBasicView:function(){var id=blissbook.browser.view.DetailsView.CONTAINER_DOM_ID;var strategy=new blissbook.browser.view.DetailsViewBasic(id);return new blissbook.browser.view.DetailsView(id,strategy);},createIdeasBookView:function(){var id=blissbook.browser.view.DetailsView.CONTAINER_DOM_ID;var strategy=new blissbook.browser.view.DetailsViewIdeasBook(id);return new blissbook.browser.view.DetailsView(id,strategy);}});blissbook.browser.view.DetailsView.prototype={showView:function(){if(!$(this.CONTAINER)){return;}
if(this._needsRendering){this._lazyRender();}
$(this.CONTAINER).show();},hideView:function(){if(!$(this.CONTAINER)){return;}
$(this.CONTAINER).hide();},_initSubscribers:function(){blissbook.browser.event.EventBus.addPageChangeListener(this._onPageChange.bind(this));},_onPageChange:function(event){if(!$(this.CONTAINER)){return;}
if($(this.CONTAINER).visible()){this._renderView(event.getPhotos())}else{this._needsRendering=true;}},_lazyRender:function(){var photos=blissbook.browser.controller.BrowserController.lazyGetPhotos();this._renderView(photos);},_renderView:function(photos){this._renderer.renderPhotos(photos);this._needsRendering=false;}}
blissbook.namespace('blissbook.browser.view');blissbook.browser.view.DetailsViewBasic=function(containerId){this.CONTAINER=containerId;this.DETAILS_PANEL_XSL="browser_details_view_basic_xsl";this.ROTATE_LINKS_PREFIX='browser_details_view_basic_rotate_links_';this.DELETE_LINK_PREFIX='browser_details_view_basic_delete_link_';this.TAG_FORM_PREFIX='browser_details_view_basic_tag_form_';this.TAGS_PREFIX='browser_details_view_basic_tags_';this.TITLE_PREFIX='browser_details_view_basic_title_';this.DESC_PREFIX='browser_details_view_basic_description_';this.PRIVACY_PREFIX='browser_details_view_basic_privacy_';this.PHOTOGRAPHER_PREFIX='browser_details_view_basic_photographer_';this.BLURRY_EXPLICIT_PREFIX='browser_details_view_basic_blurry_explicit_links_';this.VENDORS_PREFIX='browser_details_view_basic_vendors_';this.UPLOADED_BY_PREFIX='browser_details_view_basic_uploaded_by_';this.VENDOR_WEDDING_BUTTON_PREFIX='browser_details_view_basic_vendor_wedding_button_';this.IDEAS_BUTTON_PREFIX='browser_details_view_basic_ideas_button_';this.SMALL_IMAGE_PREFIX='browser_details_view_basic_small_image_';this._blurryExplicitLinkTemplate=new blissbook.browser.view.common.BlurryExplicitLinkTemplate(this.CONTAINER);this._descriptionTemplate=new blissbook.browser.view.common.DescriptionTemplate(this.CONTAINER);this._privacyTemplate=new blissbook.browser.view.common.PrivacyTemplate(this.CONTAINER);this._photographerTemplate=new blissbook.browser.view.common.PhotographerTemplate(this.CONTAINER);this._rotateLinksTemplate=new blissbook.browser.view.common.RotateLinksTemplate(this.CONTAINER);this._deleteLinkTemplate=new blissbook.browser.view.common.DeleteLinkTemplate(this.CONTAINER);this._tagFormTemplate=new blissbook.browser.view.common.TagFormTemplate(this.CONTAINER);this._tagsTemplate=new blissbook.browser.view.common.TagsTemplate(this.CONTAINER);this._titleTemplate=new blissbook.browser.view.common.TitleTemplate(this.CONTAINER);this._vendorsTemplate=new blissbook.browser.view.common.VendorsTemplate();this._uploadedByTemplate=new blissbook.browser.view.common.UploadedByTemplate();this._vendorWeddingButtonTemplate=new blissbook.browser.view.common.VendorWeddingButtonTemplate();this._ideasButtonTemplate=new blissbook.browser.view.common.IdeasButtonTemplate();this._smallImageTemplate=new blissbook.browser.view.common.SmallImageTemplate(this.CONTAINER);};blissbook.browser.view.DetailsViewBasic.prototype={renderPhotos:function(photos){this._renderLayout(photos);for(var i=0,n=photos.length;i<n;i++){var p=photos[i];this._renderRotateLinks(i,p);this._renderDeleteLink(i,p);this._renderTagForm(i,p);this._renderTags(i,p);this._renderTitle(i,p);this._renderDescription(i,p);this._renderPrivacy(i,p);this._renderPhotographer(i,p);this._renderBlurryExplicitLinks(i,p);this._renderVendors(i,p);this._renderUploadedBy(i,p);this._renderVendorWeddingButton(i,p);this._renderIdeasButton(i,p);this._renderSmallImage(i,p);}},_renderLayout:function(photos){var html=xsltProcess(this._getXML(photos.length),this._getXSL());$(this.CONTAINER).update(html);},_renderRotateLinks:function(i,p){this._rotateLinksTemplate.newComponent(this.ROTATE_LINKS_PREFIX+i,p);},_renderDeleteLink:function(i,p){this._deleteLinkTemplate.newComponent(this.DELETE_LINK_PREFIX+i,p);},_renderTagForm:function(i,p){this._tagFormTemplate.newComponent(this.TAG_FORM_PREFIX+i,p);},_renderTags:function(i,p){this._tagsTemplate.newComponent(this.TAGS_PREFIX+i,p);},_renderTitle:function(i,p){this._titleTemplate.newComponent(this.TITLE_PREFIX+i,p);},_renderDescription:function(i,p){this._descriptionTemplate.newComponent(this.DESC_PREFIX+i,p);},_renderPrivacy:function(i,p){this._privacyTemplate.newComponent(this.PRIVACY_PREFIX+i,p);},_renderPhotographer:function(i,p){this._photographerTemplate.newComponent(this.PHOTOGRAPHER_PREFIX+i,p);},_renderBlurryExplicitLinks:function(i,p){this._blurryExplicitLinkTemplate.newComponent(this.BLURRY_EXPLICIT_PREFIX+i,p);},_renderVendors:function(i,p){this._vendorsTemplate.newComponent(this.VENDORS_PREFIX+i,p);},_renderUploadedBy:function(i,p){this._uploadedByTemplate.newComponent(this.UPLOADED_BY_PREFIX+i,p);},_renderVendorWeddingButton:function(i,p){this._vendorWeddingButtonTemplate.newComponent(this.VENDOR_WEDDING_BUTTON_PREFIX+i,p);},_renderIdeasButton:function(i,p){this._ideasButtonTemplate.newComponent(this.IDEAS_BUTTON_PREFIX+i,p);},_renderSmallImage:function(i,p){this._smallImageTemplate.newComponent(this.SMALL_IMAGE_PREFIX+i,p);},_getXML:function(numPhotos){var sb=['<photos><count>',numPhotos,'</count></photos>'];return xmlParse(sb.join(''));},_getXSL:function(){var xsl=xmlParse($(this.DETAILS_PANEL_XSL).value);this._getXSL=function(){return xsl;};return xsl;}}
blissbook.namespace('blissbook.browser.view');blissbook.browser.view.DetailsViewIdeasBook=function(containerId){this.CONTAINER=containerId;this.XSL="browser_details_view_ideas_book_xsl";this.IDEA_TAGS_PREFIX='browser_details_view_ideas_book_tags_';this.IDEA_NOTES_PREFIX='browser_details_view_ideas_book_notes_';this.TITLE_PREFIX='browser_details_view_ideas_book_title_';this.DESC_PREFIX='browser_details_view_ideas_book_description_';this.PRIVACY_PREFIX='browser_details_view_ideas_book_privacy_';this.PHOTOGRAPHER_PREFIX='browser_details_view_ideas_book_photographer_';this.VENDORS_PREFIX='browser_details_view_ideas_book_vendors_';this.UPLOADED_BY_PREFIX='browser_details_view_ideas_book_uploaded_by_';this.VENDOR_WEDDING_BUTTON_PREFIX='browser_details_view_ideas_book_vendor_wedding_button_';this.IDEAS_BUTTON_PREFIX='browser_details_view_ideas_book_ideas_button_';this.SMALL_IMAGE_PREFIX='browser_details_view_ideas_book_small_image_';this._descriptionTemplate=new blissbook.browser.view.common.DescriptionTemplate(this.CONTAINER);this._privacyTemplate=new blissbook.browser.view.common.PrivacyTemplate(this.CONTAINER);this._photographerTemplate=new blissbook.browser.view.common.PhotographerTemplate(this.CONTAINER);this._ideaTagsTemplate=new blissbook.browser.view.common.IdeaTagsTemplate(this.CONTAINER);this._ideaNotesTemplate=new blissbook.browser.view.common.IdeaNotesTemplate();this._titleTemplate=new blissbook.browser.view.common.TitleTemplate(this.CONTAINER);this._vendorsTemplate=new blissbook.browser.view.common.VendorsTemplate();this._uploadedByTemplate=new blissbook.browser.view.common.UploadedByTemplate();this._vendorWeddingButtonTemplate=new blissbook.browser.view.common.VendorWeddingButtonTemplate();this._ideasButtonTemplate=new blissbook.browser.view.common.IdeasButtonTemplate();this._smallImageTemplate=new blissbook.browser.view.common.SmallImageTemplate(this.CONTAINER);};blissbook.browser.view.DetailsViewIdeasBook.prototype={renderPhotos:function(photos){this._renderLayout(photos);for(var i=0,n=photos.length;i<n;i++){var p=photos[i];this._renderIdeaTags(i,p);this._renderNotes(i,p);this._renderTitle(i,p);this._renderDescription(i,p);this._renderPrivacy(i,p);this._renderPhotographer(i,p);this._renderVendors(i,p);this._renderUploadedBy(i,p);this._renderVendorWeddingButton(i,p);this._renderIdeasButton(i,p);this._renderSmallImage(i,p);}},_renderLayout:function(photos){var html=xsltProcess(this._getXML(photos.length),this._getXSL());$(this.CONTAINER).update(html);},_renderIdeaTags:function(i,p){this._ideaTagsTemplate.newComponent(this.IDEA_TAGS_PREFIX+i,p);},_renderNotes:function(i,p){this._ideaNotesTemplate.newComponent(this.IDEA_NOTES_PREFIX+i,p);},_renderTitle:function(i,p){this._titleTemplate.newComponent(this.TITLE_PREFIX+i,p);},_renderDescription:function(i,p){this._descriptionTemplate.newComponent(this.DESC_PREFIX+i,p);},_renderPrivacy:function(i,p){this._privacyTemplate.newComponent(this.PRIVACY_PREFIX+i,p);},_renderPhotographer:function(i,p){this._photographerTemplate.newComponent(this.PHOTOGRAPHER_PREFIX+i,p);},_renderVendors:function(i,p){this._vendorsTemplate.newComponent(this.VENDORS_PREFIX+i,p);},_renderUploadedBy:function(i,p){this._uploadedByTemplate.newComponent(this.UPLOADED_BY_PREFIX+i,p);},_renderVendorWeddingButton:function(i,p){this._vendorWeddingButtonTemplate.newComponent(this.VENDOR_WEDDING_BUTTON_PREFIX+i,p);},_renderIdeasButton:function(i,p){this._ideasButtonTemplate.newComponent(this.IDEAS_BUTTON_PREFIX+i,p);},_renderSmallImage:function(i,p){this._smallImageTemplate.newComponent(this.SMALL_IMAGE_PREFIX+i,p);},_getXML:function(numPhotos){var sb=['<photos><count>',numPhotos,'</count></photos>'];return xmlParse(sb.join(''));},_getXSL:function(){var xsl=xmlParse($(this.XSL).value);this._getXSL=function(){return xsl;};return xsl;}}
blissbook.namespace('blissbook.browser.view');blissbook.browser.view.IPhotoCollectionRenderer={renderPhotos:function(photos){throw'IPhotoCollectionRenderer.renderPhotos: abstract method';}}
blissbook.namespace('blissbook.browser.view');blissbook.browser.view.IPhotoRenderer={renderPhoto:function(p){throw'IPhotoRenderer.render: abstract method';}}
blissbook.namespace('blissbook.browser.view');blissbook.browser.view.IView={showView:function(){throw'IView.showView: abstract method';},hideView:function(){throw'IView.hideView: abstract method';}}
blissbook.namespace('blissbook.browser.view.MagnifyView');blissbook.browser.view.MagnifyView=function(){this.MAGNIFY_CONTAINER='browser_magnify_view_magnify_container';this.DETAIL_CONTAINER='browser_magnify_view_detail_container';this.DETAIL_CONTENT='browser_magnify_view_detail_middle';this.DETAIL_IMAGE='browser_magnify_view_detail_img';this.MAGNIFY_HTML='browser_magnify_view_magnify_html';this.DETAIL_XSL='browser_magnify_view_detail_xsl';this.TITLE_CONTAINER='browser_magnify_widget_title_container';this.DESC_CONTAINER='browser_magnify_widget_desc_container';this.PRIVACY_CONTAINER='browser_magnify_widget_privacy_container';this.PHOTOGRAPHER_CONTAINER='browsser_magnify_widget_photographer_container';this.BLURRY_EXPLICIT_CONTAINER='browser_magnify_widget_blurry_explicit_links';this.VENDORS_CONTAINER='browser_magnfiy_widget_vendors_container';this.UPLOADED_BY_CONTAINER='browser_magnify_widget_uploaded_by_container';this.VENDOR_WEDDING_BUTTON_CONTAINER='browser_magnify_widget_vendor_wedding_button_container';this.IDEAS_BUTTON_CONTAINER='browser_magnify_widget_ideas_button_container';this.SMALL_IMAGE_CONTAINER='browser_magnify_view_detail_photo';this._controller=blissbook.browser.controller.BrowserController;this._blurryExplicitLinkTemplate=new blissbook.browser.view.common.BlurryExplicitLinkTemplate();this._descriptionTemplate=new blissbook.browser.view.common.DescriptionTemplate();this._privacyTemplate=new blissbook.browser.view.common.PrivacyTemplate();this._photographerTemplate=new blissbook.browser.view.common.PhotographerTemplate();this._titleTemplate=new blissbook.browser.view.common.TitleTemplate();this._vendorsTemplate=new blissbook.browser.view.common.VendorsTemplate();this._uploadedByTemplate=new blissbook.browser.view.common.UploadedByTemplate();this._vendorWeddingButtonTemplate=new blissbook.browser.view.common.VendorWeddingButtonTemplate();this._ideasButtonTemplate=new blissbook.browser.view.common.IdeasButtonTemplate();this._smallImageTemplate=new blissbook.browser.view.common.SmallImageTemplate();this._photo;this._initSubscribers();};blissbook.browser.view.MagnifyView.prototype={showMagnifyingGlass:function(photo,top,left){if(this._doesNotHaveContainers()){return;}
this._photo=photo;var el=$(this.MAGNIFY_CONTAINER);el.style.top=top+'px';el.style.left=left+'px';el.show();},showing:function(){if(this._doesNotHaveContainers()){return false;}
return $(this.DETAIL_CONTAINER).visible()||$(this.MAGNIFY_CONTAINER).visible();},hideView:function(){if(this._doesNotHaveContainers()){return;}
this._hideMagnifyingGlass();this._hideDetailPane();},_doesNotHaveContainers:function(){!$(this.DETAIL_CONTAINER)||!$(this.MAGNIFY_CONTAINER);},_isMagnifiedPhoto:function(p){var l=blissbook.util.LangUtils;return l.isValue(p)&&l.isValue(this._photo)&&p.getServerId()===this._photo.getServerId();},_isNotMagnifiedPhoto:function(p){return!this._isMagnifiedPhoto(p);},_initSubscribers:function(){blissbook.browser.event.EventBus.addDOMReadyListener(this._onDOMReady.bind(this));},_onDOMReady:function(){if(this._doesNotHaveContainers()){return;}
this._addMouseoverListenerToMagnifyingGlassContainer();this._addClickListenerToDocument();},_addMouseoverListenerToMagnifyingGlassContainer:function(){var self=this;Event.observe(this.MAGNIFY_CONTAINER,'mouseover',function(event){self._onMagnifyingGlassContainerMouseover(event);});},_addClickListenerToDocument:function(){var self=this;blissbook.util.Event.onClickDelegateUntil(document,function(el){if(el.id===self.DETAIL_CONTAINER){return true;}else if(el===document.body){self._hideMagnifyingGlass();self._hideDetailPane();return true;}
return false;});},_onMagnifyingGlassContainerMouseover:function(event){this._renderDetailPane();},_renderDetailPane:function(){var html=xsltProcess(this._photo.toXML(),this._getDetailPaneXSL());$(this.DETAIL_CONTAINER).update(html).show();this._titleTemplate.newComponent(this.TITLE_CONTAINER,this._photo);this._descriptionTemplate.newComponent(this.DESC_CONTAINER,this._photo);this._privacyTemplate.newComponent(this.PRIVACY_CONTAINER,this._photo);this._photographerTemplate.newComponent(this.PHOTOGRAPHER_CONTAINER,this._photo);this._blurryExplicitLinkTemplate.newComponent(this.BLURRY_EXPLICIT_CONTAINER,this._photo);this._vendorsTemplate.newComponent(this.VENDORS_CONTAINER,this._photo);this._uploadedByTemplate.newComponent(this.UPLOADED_BY_CONTAINER,this._photo);this._vendorWeddingButtonTemplate.newComponent(this.VENDOR_WEDDING_BUTTON_CONTAINER,this._photo);this._ideasButtonTemplate.newComponent(this.IDEAS_BUTTON_CONTAINER,this._photo);this._smallImageTemplate.newComponent(this.SMALL_IMAGE_CONTAINER,this._photo);},_hideDetailPane:function(){$(this.DETAIL_CONTAINER).hide();},_hideMagnifyingGlass:function(){$(this.MAGNIFY_CONTAINER).hide();},_getMagnifyingGlassHTML:function(){return $(this.MAGNIFY_HTML).value;},_getDetailPaneXSL:function(){var xsl=xmlParse($(this.DETAIL_XSL).value);this._getDetailPaneXSL=function(){return xsl;};return xsl;}};blissbook.namespace('blissbook.browser.view');blissbook.browser.view.NavigationView=function(){this.VIEW_SLIDESHOW='browser_view_tab_slideshow';this.VIEW_THUMBNAILS='browser_view_tab_thumbnail';this.VIEW_DETAILS='browser_view_tab_detail';this.VIEW_SINGLE='browser_view_tab_single';this.TAB_CONTAINER='browser_navigation_view_container';this._tabImageNav=new ImageNav('.gif');this._controller=blissbook.browser.controller.BrowserController;this._initSubscribers();};blissbook.browser.view.NavigationView.prototype={onViewChanged:function(currentView){blissbook.util.Assert.isTrue(currentView===this.VIEW_DETAILS||currentView===this.VIEW_SINGLE||currentView===this.VIEW_SLIDESHOW||currentView===this.VIEW_THUMBNAILS,'NavigationView.onViewChanged: '+currentView);this._tabImageNav.set(currentView);},_initSubscribers:function(){blissbook.browser.event.EventBus.addDOMReadyListener(this._onDOMReady.bind(this));},_onDOMReady:function(){this._addClickListenerToTabs();this._addMouseoverListenerToTabs();this._addMouseoutListenerToTabs();},_addClickListenerToTabs:function(){var self=this;blissbook.util.Event.onClickDelegateUntil(this.TAB_CONTAINER,function(el){var id=el.id||'';switch(id){case self.VIEW_SLIDESHOW:self._controller.goSlideShow();return true;case self.VIEW_THUMBNAILS:self._controller.goThumbnails();return true;case self.VIEW_DETAILS:self._controller.goDetails();return true;case self.VIEW_SINGLE:self._controller.goSingle();return true;default:return false;}});},_addMouseoverListenerToTabs:function(){var self=this;blissbook.util.Event.onMouseoverDelegateUntil(this.TAB_CONTAINER,function(el){var id=el.id||'';switch(id){case self.VIEW_SLIDESHOW:case self.VIEW_THUMBNAILS:case self.VIEW_DETAILS:case self.VIEW_SINGLE:self._tabImageNav.hoverOn(id);return true;default:return false;}});},_addMouseoutListenerToTabs:function(){var self=this;blissbook.util.Event.onMouseoutDelegateUntil(this.TAB_CONTAINER,function(el){var id=el.id||'';switch(id){case self.VIEW_SLIDESHOW:case self.VIEW_THUMBNAILS:case self.VIEW_DETAILS:case self.VIEW_SINGLE:self._tabImageNav.hoverOff(id);return true;default:return false;}});}}
blissbook.namespace('blissbook.browser.view');blissbook.browser.view.NullMagnifyView=function(){};blissbook.browser.view.NullMagnifyView.prototype={showMagnifyingGlass:function(photo,top,left){},showing:function(){return false;},hideView:function(){}}
blissbook.namespace('blissbook.browser.view');blissbook.browser.view.PaginationView=function(){this.CONTAINER='browser_pagination_view_container';this.PAGINATION_LEFT_PREFIX='browser_paginator_left_';this.PAGINATION_NUMBER_PREFIX='browser_paginator_page_';this.PAGINATION_RIGHT_PREFIX='browser_paginator_right_';this.PAGINATION_XSL='browser_paginator_pagination_xsl';this.RANGE=10;this._controller=blissbook.browser.controller.BrowserController;this._initSubscribers();};blissbook.browser.view.PaginationView.prototype={_initSubscribers:function(){var EventBus=blissbook.browser.event.EventBus;EventBus.addPageChangeListener(this._onPageChange.bind(this));EventBus.addDOMReadyListener(this._onDOMReady.bind(this));},_onDOMReady:function(){if(!$(this.CONTAINER)){return;}
this._addClickListenerToContainer();},_addClickListenerToContainer:function(){var self=this;blissbook.util.Event.onClickDelegateUntil(this.CONTAINER,function(childEl){var id=childEl.id||'';if(id.startsWith(self.PAGINATION_LEFT_PREFIX)){var pageNum=parseInt(id.substring(self.PAGINATION_LEFT_PREFIX.length));self._controller.goPageNumber(pageNum);return true;}else if(id.startsWith(self.PAGINATION_NUMBER_PREFIX)){var pageNum=parseInt(id.substring(self.PAGINATION_NUMBER_PREFIX.length));self._controller.goPageNumber(pageNum);return true;}else if(id.startsWith(self.PAGINATION_RIGHT_PREFIX)){var pageNum=parseInt(id.substring(self.PAGINATION_RIGHT_PREFIX.length));self._controller.goPageNumber(pageNum);return true;}
return false;});},_onPageChange:function(e){$(this.CONTAINER).update(this._paginationHTML(e.getCurrentPage(),e.getTotalPages()))},_paginationHTML:function(currentPage,totalPages){return xsltProcess(this._getXML(currentPage,totalPages),this._getXSL());},_getXML:function(currentPage,totalPages){var sb=[];sb.push('<pages>');sb.push('<totalPages>',totalPages,'</totalPages>');sb.push('<currentPage>',currentPage,'</currentPage>');sb.push('<lower>',Math.max(currentPage-this.RANGE,1),'</lower>')
sb.push('<upper>',Math.min(currentPage+this.RANGE,totalPages),'</upper>');sb.push('</pages>');return xmlParse(sb.join(''));},_getXSL:function(){var xsl=xmlParse($(this.PAGINATION_XSL).value);this._getXSL=function(){return xsl;};return xsl;}};blissbook.namespace('blissbook.browser.view');blissbook.browser.view.ProgressView=function(){this._visible=false;var self=this;this._modal=new Control.Modal(false,{loading:'/images/progress.gif',afterOpen:function(){self._visible=true;},beforeClose:function(){self._visible=false;},opacity:0.0});this._initSubscribers();};blissbook.browser.view.ProgressView.prototype={_initSubscribers:function(){blissbook.browser.event.EventBus.addProgressListener(this._onProgressChange.bind(this));},_onProgressChange:function(inProgress){if(inProgress&&this._visible){return;}
if(inProgress){this._modal.open();return;}else if(this._visible){this._modal.close();}}}
blissbook.namespace('blissbook.browser.view');blissbook.browser.view.SingleView=function(containerDomId,photoDomId,scrollerDomId,renderer){blissbook.util.Assert.hasInterface(renderer,blissbook.browser.view.IPhotoRenderer,'SingleView.constructor: ');this.CONTAINER=containerDomId;this.PHOTO_CONTAINER=photoDomId;this.SCROLLER_CONTAINER=scrollerDomId;this._scrollerTemplate=new blissbook.browser.view.common.ScrollerTemplate(this.CONTAINER);this._needsRendering=false;this._renderer=renderer;this._initSubscribers();};Object.extend(blissbook.browser.view.SingleView,{CONTAINER_DOM_ID:'browser_single_view_container',SCROLLER_DOM_ID:'browser_single_scroller_container',PHOTO_DOM_ID:'browser_single_photo_container',createBasicView:function(){var self=blissbook.browser.view.SingleView;return self._doCreateView(new blissbook.browser.view.SingleViewBasic(self.PHOTO_DOM_ID));},createIdeasBookView:function(){var self=blissbook.browser.view.SingleView;return self._doCreateView(new blissbook.browser.view.SingleViewIdeasBook(self.PHOTO_DOM_ID));},_doCreateView:function(strategy){return new blissbook.browser.view.SingleView(blissbook.browser.view.SingleView.CONTAINER_DOM_ID,blissbook.browser.view.SingleView.PHOTO_DOM_ID,blissbook.browser.view.SingleView.SCROLLER_DOM_ID,strategy);}});blissbook.browser.view.SingleView.prototype={showView:function(){if(!$(this.CONTAINER)){return;}
if(this._needsRendering){this._lazyRender();}
$(this.CONTAINER).show();},hideView:function(){if(!$(this.CONTAINER)){return;}
$(this.CONTAINER).hide();},_initSubscribers:function(){var EventBus=blissbook.browser.event.EventBus;EventBus.addFocusChangeListener(this._onFocusChange.bind(this));EventBus.addPageChangeListener(this._onPageChange.bind(this));},_onFocusChange:function(e){if(!$(this.CONTAINER)){return;}
if($(this.CONTAINER).visible()){this._renderView(e.getFocusPhoto(),e.getNextPhoto(),e.getPreviousPhoto());}else{this._needsRendering=true;}},_onPageChange:function(event){if(!$(this.CONTAINER)){return;}
if(event.getPhotos().length===0){this._clearView();}},_lazyRender:function(){var p=blissbook.browser.controller.BrowserController.lazyGetFocusPhoto();var n=blissbook.browser.controller.BrowserController.lazyGetNeighbors(p);this._renderView(p,n.next,n.prev);},_renderView:function(p,pNext,pPrev){if(!p){this._clearView();return;}
this._renderer.renderPhoto(p);this._renderNextPrevPhotoLinks(pNext,pPrev);this._needsRendering=false;},_renderNextPrevPhotoLinks:function(pNext,pPrev){this._scrollerTemplate.newComponent(this.SCROLLER_CONTAINER,pNext,pPrev);},_clearView:function(){$(this.PHOTO_CONTAINER).update();$(this.SCROLLER_CONTAINER).update();}}
blissbook.namespace('blissbook.browser.view');blissbook.browser.view.SingleViewBasic=function(photoDomId){this.CONTAINER=photoDomId;this.SINGLE_PANEL_HTML="browser_single_view_basic_html";this.ROTATE_LINKS='browser_single_view_basic_rotate_links';this.DELETE_LINK='browser_single_view_basic_delete_link';this.TAG_FORM_CONTAINER='browser_single_view_basic_tag_form';this.TAGS_CONTAINER='browser_single_view_basic_tags';this.TITLE_CONTAINER='browser_single_view_basic_title';this.DESC_CONTAINER='browser_single_view_basic_description';this.PRIVACY_CONTAINER='browser_single_view_basic_privacy';this.PHOTOGRAPHER_CONTAINER='browser_single_view_basic_photographer';this.BLURRY_EXPLICIT_CONTAINER='browser_single_view_basic_blurry_explicit';this.VENDORS_CONTAINER='browser_single_view_basic_vendors';this.UPLOADED_BY_CONTAINER='browser_single_view_basic_uploaded_by';this.VENDOR_WEDDING_BUTTON_CONTAINER='browser_single_view_basic_vendor_wedding_button';this.IDEAS_BUTTON_CONTAINER='browser_single_view_basic_ideas_button';this.MEDIUM_IMAGE_CONTAINER='browser_single_view_basic_image';this._blurryExplicitLinkTemplate=new blissbook.browser.view.common.BlurryExplicitLinkTemplate(this.CONTAINER);this._descriptionTemplate=new blissbook.browser.view.common.DescriptionTemplate(this.CONTAINER);this._privacyTemplate=new blissbook.browser.view.common.PrivacyTemplate(this.CONTAINER);this._photographerTemplate=new blissbook.browser.view.common.PhotographerTemplate(this.CONTAINER);this._rotateLinksTemplate=new blissbook.browser.view.common.RotateLinksTemplate(this.CONTAINER);this._deleteLinkTemplate=new blissbook.browser.view.common.DeleteLinkTemplate(this.CONTAINER);this._tagFormTemplate=new blissbook.browser.view.common.TagFormTemplate(this.CONTAINER);this._tagsTemplate=new blissbook.browser.view.common.TagsTemplate(this.CONTAINER);this._titleTemplate=new blissbook.browser.view.common.TitleTemplate(this.CONTAINER);this._vendorsTemplate=new blissbook.browser.view.common.VendorsTemplate();this._uploadedByTemplate=new blissbook.browser.view.common.UploadedByTemplate();this._vendorWeddingButtonTemplate=new blissbook.browser.view.common.VendorWeddingButtonTemplate();this._ideasButtonTemplate=new blissbook.browser.view.common.IdeasButtonTemplate();this._mediumImageTemplate=new blissbook.browser.view.common.MediumImageTemplate();};blissbook.browser.view.SingleViewBasic.prototype={renderPhoto:function(p){this._renderLayout();this._renderRotateLinks(p);this._renderDeleteLink(p);this._renderTagForm(p);this._renderTags(p);this._renderTitle(p);this._renderDescription(p);this._renderPrivacy(p);this._renderPhotographer(p);this._renderBlurryExplicitLinks(p);this._renderVendors(p);this._renderUploadedBy(p);this._renderVendorWeddingButton(p);this._renderIdeasButton(p);this._renderMediumImage(p);},_renderLayout:function(){var html=$(this.SINGLE_PANEL_HTML).value;$(this.CONTAINER).update(html);Nifty('div#single_photo');},_renderRotateLinks:function(p){this._rotateLinksTemplate.newComponent(this.ROTATE_LINKS,p);},_renderDeleteLink:function(p){this._deleteLinkTemplate.newComponent(this.DELETE_LINK,p);},_renderTagForm:function(p){this._tagFormTemplate.newComponent(this.TAG_FORM_CONTAINER,p);},_renderTags:function(p){this._tagsTemplate.newComponent(this.TAGS_CONTAINER,p);},_renderTitle:function(p){this._titleTemplate.newComponent(this.TITLE_CONTAINER,p);},_renderDescription:function(p){this._descriptionTemplate.newComponent(this.DESC_CONTAINER,p);},_renderPrivacy:function(p){this._privacyTemplate.newComponent(this.PRIVACY_CONTAINER,p);},_renderPhotographer:function(p){this._photographerTemplate.newComponent(this.PHOTOGRAPHER_CONTAINER,p);},_renderBlurryExplicitLinks:function(p){this._blurryExplicitLinkTemplate.newComponent(this.BLURRY_EXPLICIT_CONTAINER,p);},_renderVendors:function(p){this._vendorsTemplate.newComponent(this.VENDORS_CONTAINER,p);},_renderUploadedBy:function(p){this._uploadedByTemplate.newComponent(this.UPLOADED_BY_CONTAINER,p);},_renderVendorWeddingButton:function(p){this._vendorWeddingButtonTemplate.newComponent(this.VENDOR_WEDDING_BUTTON_CONTAINER,p);},_renderIdeasButton:function(p){this._ideasButtonTemplate.newComponent(this.IDEAS_BUTTON_CONTAINER,p);},_renderMediumImage:function(p){this._mediumImageTemplate.newComponent(this.MEDIUM_IMAGE_CONTAINER,p);}}
blissbook.namespace('blissbook.browser.view');blissbook.browser.view.SingleViewIdeasBook=function(photoDomId){this.CONTAINER=photoDomId;this.HTML="browser_single_view_ideas_book_html";this.IDEA_TAGS_CONTAINER='browser_single_view_ideas_book_tags';this.IDEA_NOTES='browser_single_view_ideas_book_notes';this.TITLE_CONTAINER='browser_single_view_ideas_book_title';this.DESC_CONTAINER='browser_single_view_ideas_book_description';this.PRIVACY_CONTAINER='browser_single_view_ideas_book_privacy';this.PHOTOGRAPHER_CONTAINER='browser_single_view_ideas_book_photographer';this.BLURRY_EXPLICIT_CONTAINER='browser_single_view_ideas_book_blurry_explicit';this.VENDORS_CONTAINER='browser_single_view_ideas_book_vendors';this.UPLOADED_BY_CONTAINER='browser_single_view_ideas_book_uploaded_by';this.VENDOR_WEDDING_BUTTON_CONTAINER='browser_single_view_ideas_book_vendor_wedding_button';this.IDEAS_BUTTON_CONTAINER='browser_single_view_ideas_book_ideas_button';this.MEDIUM_IMAGE_CONTAINER='browser_single_view_ideas_book_image';this._descriptionTemplate=new blissbook.browser.view.common.DescriptionTemplate(this.CONTAINER);this._privacyTemplate=new blissbook.browser.view.common.PrivacyTemplate(this.CONTAINER);this._photographerTemplate=new blissbook.browser.view.common.PhotographerTemplate(this.CONTAINER);this._ideaTagsTemplate=new blissbook.browser.view.common.IdeaTagsTemplate(this.CONTAINER);this._ideaNotesTemplate=new blissbook.browser.view.common.IdeaNotesTemplate();this._titleTemplate=new blissbook.browser.view.common.TitleTemplate(this.CONTAINER);this._vendorsTemplate=new blissbook.browser.view.common.VendorsTemplate();this._uploadedByTemplate=new blissbook.browser.view.common.UploadedByTemplate();this._vendorWeddingButtonTemplate=new blissbook.browser.view.common.VendorWeddingButtonTemplate();this._ideasButtonTemplate=new blissbook.browser.view.common.IdeasButtonTemplate();this._mediumImageTemplate=new blissbook.browser.view.common.MediumImageTemplate();};blissbook.browser.view.SingleViewIdeasBook.prototype={renderPhoto:function(p){this._renderLayout();this._renderIdeaTags(p);this._renderIdeaNotes(p);this._renderTitle(p);this._renderDescription(p);this._renderPrivacy(p);this._renderPhotographer(p);this._renderVendors(p);this._renderUploadedBy(p);this._renderVendorWeddingButton(p);this._renderIdeasButton(p);this._renderMediumImage(p);},_renderLayout:function(){var html=$(this.HTML).value;$(this.CONTAINER).update(html);Nifty('div#single_photo');},_renderIdeaTags:function(p){this._ideaTagsTemplate.newComponent(this.IDEA_TAGS_CONTAINER,p);},_renderIdeaNotes:function(p){this._ideaNotesTemplate.newComponent(this.IDEA_NOTES,p);},_renderTitle:function(p){this._titleTemplate.newComponent(this.TITLE_CONTAINER,p);},_renderDescription:function(p){this._descriptionTemplate.newComponent(this.DESC_CONTAINER,p);},_renderPrivacy:function(p){this._privacyTemplate.newComponent(this.PRIVACY_CONTAINER,p);},_renderPhotographer:function(p){this._photographerTemplate.newComponent(this.PHOTOGRAPHER_CONTAINER,p);},_renderVendors:function(p){this._vendorsTemplate.newComponent(this.VENDORS_CONTAINER,p);},_renderUploadedBy:function(p){this._uploadedByTemplate.newComponent(this.UPLOADED_BY_CONTAINER,p);},_renderVendorWeddingButton:function(p){this._vendorWeddingButtonTemplate.newComponent(this.VENDOR_WEDDING_BUTTON_CONTAINER,p);},_renderIdeasButton:function(p){this._ideasButtonTemplate.newComponent(this.IDEAS_BUTTON_CONTAINER,p);},_renderMediumImage:function(p){this._mediumImageTemplate.newComponent(this.MEDIUM_IMAGE_CONTAINER,p);}}
blissbook.namespace('blissbook.browser.view');blissbook.browser.view.SlideShowView=function(containerDomId,flashDomId,detailPaneDomId,renderer){blissbook.util.Assert.hasInterface(renderer,blissbook.browser.view.IPhotoRenderer,'SlideShowView.constructor: ');this.CONTAINER=containerDomId;this.VENDORS_CONTAINER='browser_slideshow_view_vendors';this.FLASH_CONTENT=flashDomId;this.DETAIL_PANE=detailPaneDomId;this.SLIDE_SHOW_PATH='/swf/browser.swf';this._renderer=renderer;this._vendorsTemplate=new blissbook.browser.view.common.VendorsTemplate();this._initSubscribers();};Object.extend(blissbook.browser.view.SlideShowView,{CONTAINER_DOM_ID:'browser_slideshow_view_container',FLASH_DOM_ID:'flashcontent',DETAIL_PANE_DOM_ID:'browser_slideshow_detail_pane_container',createBasicView:function(){var self=blissbook.browser.view.SlideShowView;return self._doCreateView(new blissbook.browser.view.SlideShowViewBasic(self.DETAIL_PANE_DOM_ID));},createIdeasBookView:function(){var self=blissbook.browser.view.SlideShowView;return self._doCreateView(new blissbook.browser.view.SlideShowViewIdeasBook(self.DETAIL_PANE_DOM_ID));},_doCreateView:function(strategy){return new blissbook.browser.view.SlideShowView(blissbook.browser.view.SlideShowView.CONTAINER_DOM_ID,blissbook.browser.view.SlideShowView.FLASH_DOM_ID,blissbook.browser.view.SlideShowView.DETAIL_PANE_DOM_ID,strategy);}});blissbook.browser.view.SlideShowView.prototype={showView:function(){if(!$(this.CONTAINER)){return;}
$(this.CONTAINER).show();},hideView:function(){if(!$(this.CONTAINER)){return;}
$(this.CONTAINER).hide();},slideShowReady:function(){if(!$(this.CONTAINER)){return;}
var photos=blissbook.browser.controller.BrowserController.lazyGetPhotos();var tos=[];photos.each(function(photo){tos.push(photo.toTransferObject());});var slideShow=getMovie('browser_swf');slideShow.clearPhotos();slideShow.loadPhotos(tos);if(tos.length===0){this._clearDetailPane();}},flashSelectPhoto:function(e){if(blissbook.util.LangUtils.isString(e)){blissbook.browser.controller.BrowserController.goFocus(parseInt(e));}},doubleClickPhoto:function(serverId){blissbook.browser.controller.BrowserController.goSingle(parseInt(serverId));},_initSubscribers:function(){var EventBus=blissbook.browser.event.EventBus;EventBus.addFocusChangeListener(this._onFocusChange.bind(this));EventBus.addPageChangeListener(this._onPageChange.bind(this));EventBus.addPhotoURLChangeListener(this._onPhotoURLChange.bind(this));},_onFocusChange:function(e){if(!$(this.CONTAINER)){return;}
if(!e.getFocusPhoto()){this._clearDetailPane();return;}
if($(this.CONTAINER).visible()){this._renderDetailPane(e.getFocusPhoto());this._renderVendors(e.getFocusPhoto());}},_onPageChange:function(event){if(!$(this.CONTAINER)){return;}
this._rebuildFlashSlideShow();},_onPhotoURLChange:function(event){if(!$(this.CONTAINER)){return;}
this._rebuildFlashSlideShow();},_rebuildFlashSlideShow:function(){$(this.FLASH_CONTENT).update();flashplayer_missing();var so=new SWFObject(this.SLIDE_SHOW_PATH,'browser_swf','450','335','8','#ffffff');so.addParam('wmode','transparent');so.addParam('quality','best');so.addParam('allowScriptAccess','sameDomain');so.write($(this.FLASH_CONTENT));},_renderDetailPane:function(p){this._renderer.renderPhoto(p);},_renderVendors:function(p){this._vendorsTemplate.newComponent(this.VENDORS_CONTAINER,p);},_clearDetailPane:function(){$(this.DETAIL_PANE).update();}};blissbook.namespace('blissbook.browser.view');blissbook.browser.view.SlideShowViewBasic=function(detailPaneDomId){this.CONTAINER=detailPaneDomId;this.DETAIL_PANE_HTML='browser_slideshow_view_basic_html';this.TAG_FORM_CONTAINER='browser_slideshow_view_basic_tag_form';this.TAGS_CONTAINER='browser_slideshow_view_basic_tags';this.TITLE_CONTAINER='browser_slideshow_view_basic_title';this.DESC_CONTAINER='browser_slideshow_view_basic_description';this.PRIVACY_CONTAINER='browser_slideshow_view_basic_privacy';this.PHOTOGRAPHER_CONTAINER='browser_slideshow_view_basic_photographer';this.BLURRY_EXPLICIT_CONTAINER='browser_slideshow_view_basic_blurry_explicit';this.UPLOADED_BY_CONTAINER='browser_slideshow_view_basic_uploaded_by';this.VENDOR_WEDDING_BUTTON_CONTAINER='browser_slideshow_view_basic_vendor_wedding_button';this.IDEAS_BUTTON_CONTAINER='browser_slideshow_view_basic_ideas_button';this._titleTemplate=new blissbook.browser.view.common.TitleTemplate(this.CONTAINER);this._descriptionTemplate=new blissbook.browser.view.common.DescriptionTemplate(this.CONTAINER);this._privacyTemplate=new blissbook.browser.view.common.PrivacyTemplate(this.CONTAINER);this._photographerTemplate=new blissbook.browser.view.common.PhotographerTemplate(this.CONTAINER);this._blurryExplicitLinkTemplate=new blissbook.browser.view.common.BlurryExplicitLinkTemplate(this.CONTAINER);this._tagFormTemplate=new blissbook.browser.view.common.TagFormTemplate(this.CONTAINER);this._tagsTemplate=new blissbook.browser.view.common.TagsTemplate(this.CONTAINER);this._privacyTemplate=new blissbook.browser.view.common.PrivacyTemplate(this.CONTAINER);this._uploadedByTemplate=new blissbook.browser.view.common.UploadedByTemplate();this._vendorWeddingButtonTemplate=new blissbook.browser.view.common.VendorWeddingButtonTemplate();this._ideasButtonTemplate=new blissbook.browser.view.common.IdeasButtonTemplate();};blissbook.browser.view.SlideShowViewBasic.prototype={renderPhoto:function(p){this._renderDetailPaneLayout();this._renderTagForm(p);this._renderTags(p);this._renderTitle(p);this._renderDescription(p);this._renderPrivacy(p);this._renderPhotographer(p);this._renderBlurryExplicitLinks(p);this._renderUploadedBy(p);this._renderVendorWeddingButton(p);this._renderIdeasButton(p);this._tagFormTemplate.focusTextField(p.getServerId());},_renderDetailPaneLayout:function(){var html=$(this.DETAIL_PANE_HTML).value;$(this.CONTAINER).update(html);},_renderTagForm:function(p){this._tagFormTemplate.newComponent(this.TAG_FORM_CONTAINER,p);},_renderTags:function(p){this._tagsTemplate.newComponent(this.TAGS_CONTAINER,p);},_renderTitle:function(p){this._titleTemplate.newComponent(this.TITLE_CONTAINER,p);},_renderDescription:function(p){this._descriptionTemplate.newComponent(this.DESC_CONTAINER,p);},_renderPrivacy:function(p){this._privacyTemplate.newComponent(this.PRIVACY_CONTAINER,p);},_renderPhotographer:function(p){this._photographerTemplate.newComponent(this.PHOTOGRAPHER_CONTAINER,p);},_renderBlurryExplicitLinks:function(p){this._blurryExplicitLinkTemplate.newComponent(this.BLURRY_EXPLICIT_CONTAINER,p);},_renderUploadedBy:function(p){this._uploadedByTemplate.newComponent(this.UPLOADED_BY_CONTAINER,p);},_renderVendorWeddingButton:function(p){this._vendorWeddingButtonTemplate.newComponent(this.VENDOR_WEDDING_BUTTON_CONTAINER,p);},_renderIdeasButton:function(p){this._ideasButtonTemplate.newComponent(this.IDEAS_BUTTON_CONTAINER,p);},_clearDetailPane:function(){$(this.CONTAINER).update();}}
blissbook.namespace('blissbook.browser.view');blissbook.browser.view.SlideShowViewIdeasBook=function(detailPaneDomId){this.CONTAINER=detailPaneDomId;this.DETAIL_PANE_HTML='browser_slideshow_view_ideas_book_html';this.IDEA_TAGS_CONTAINER='browser_slideshow_view_ideas_book_tags';this.IDEA_NOTES='browser_slideshow_view_ideas_book_notes';this.TITLE_CONTAINER='browser_slideshow_view_ideas_book_title';this.DESC_CONTAINER='browser_slideshow_view_ideas_book_description';this.PRIVACY_CONTAINER='browser_slideshow_view_ideas_book_privacy';this.PHOTOGRAPHER_CONTAINER='browser_slideshow_view_ideas_book_photographer';this.UPLOADED_BY_CONTAINER='browser_slideshow_view_ideas_book_uploaded_by';this.VENDOR_WEDDING_BUTTON_CONTAINER='browser_slideshow_view_ideas_book_vendor_wedding_button';this.IDEAS_BUTTON_CONTAINER='browser_slideshow_view_ideas_book_ideas_button';this._titleTemplate=new blissbook.browser.view.common.TitleTemplate(this.CONTAINER);this._descriptionTemplate=new blissbook.browser.view.common.DescriptionTemplate(this.CONTAINER);this._privacyTemplate=new blissbook.browser.view.common.PrivacyTemplate(this.CONTAINER);this._photographerTemplate=new blissbook.browser.view.common.PhotographerTemplate(this.CONTAINER);this._ideaTagsTemplate=new blissbook.browser.view.common.IdeaTagsTemplate(this.CONTAINER);this._ideaNotesTemplate=new blissbook.browser.view.common.IdeaNotesTemplate();this._privacyTemplate=new blissbook.browser.view.common.PrivacyTemplate(this.CONTAINER);this._uploadedByTemplate=new blissbook.browser.view.common.UploadedByTemplate();this._vendorWeddingButtonTemplate=new blissbook.browser.view.common.VendorWeddingButtonTemplate();this._ideasButtonTemplate=new blissbook.browser.view.common.IdeasButtonTemplate();};blissbook.browser.view.SlideShowViewIdeasBook.prototype={renderPhoto:function(p){this._renderDetailPaneLayout();this._renderIdeaTags(p);this._renderIdeaNotes(p);this._renderTitle(p);this._renderDescription(p);this._renderPrivacy(p);this._renderPhotographer(p);this._renderUploadedBy(p);this._renderVendorWeddingButton(p);this._renderIdeasButton(p);},_renderDetailPaneLayout:function(){var html=$(this.DETAIL_PANE_HTML).value;$(this.CONTAINER).update(html);},_renderIdeaTags:function(p){this._ideaTagsTemplate.newComponent(this.IDEA_TAGS_CONTAINER,p);},_renderIdeaNotes:function(p){this._ideaNotesTemplate.newComponent(this.IDEA_NOTES,p);},_renderTitle:function(p){this._titleTemplate.newComponent(this.TITLE_CONTAINER,p);},_renderDescription:function(p){this._descriptionTemplate.newComponent(this.DESC_CONTAINER,p);},_renderPrivacy:function(p){this._privacyTemplate.newComponent(this.PRIVACY_CONTAINER,p);},_renderPhotographer:function(p){this._photographerTemplate.newComponent(this.PHOTOGRAPHER_CONTAINER,p);},_renderUploadedBy:function(p){this._uploadedByTemplate.newComponent(this.UPLOADED_BY_CONTAINER,p);},_renderVendorWeddingButton:function(p){this._vendorWeddingButtonTemplate.newComponent(this.VENDOR_WEDDING_BUTTON_CONTAINER,p);},_renderIdeasButton:function(p){this._ideasButtonTemplate.newComponent(this.IDEAS_BUTTON_CONTAINER,p);},_clearDetailPane:function(){$(this.CONTAINER).update();}}
blissbook.namespace('blissbook.browser.view');blissbook.browser.view.ThumbnailsView=function(containerDomId,renderer){blissbook.util.Assert.hasInterface(renderer,blissbook.browser.view.IPhotoCollectionRenderer,'ThumbnailsView.contsructor: ');this.CONTAINER=containerDomId;this._renderer=renderer;this._needsRendering=false;this._initSubscribers();};Object.extend(blissbook.browser.view.ThumbnailsView,{CONTAINER_DOM_ID:'browser_thumbnails_view_container',createBasicView:function(){var id=blissbook.browser.view.ThumbnailsView.CONTAINER_DOM_ID;var strategy=new blissbook.browser.view.ThumbnailsViewBasic(id);return new blissbook.browser.view.ThumbnailsView(id,strategy);},createIdeasBookView:function(){var id=blissbook.browser.view.ThumbnailsView.CONTAINER_DOM_ID;var strategy=new blissbook.browser.view.ThumbnailsViewIdeasBook(id);return new blissbook.browser.view.ThumbnailsView(id,strategy);}});blissbook.browser.view.ThumbnailsView.prototype={showView:function(){if(!$(this.CONTAINER)){return;}
if(this._needsRendering){this._lazyRender();}
$(this.CONTAINER).show();},hideView:function(){if(!$(this.CONTAINER)){return;}
$(this.CONTAINER).hide();},_initSubscribers:function(){blissbook.browser.event.EventBus.addPageChangeListener(this._onPageChange.bind(this));},_onPageChange:function(event){if(!$(this.CONTAINER)){return;}
if($(this.CONTAINER).visible()){this._renderView(event.getPhotos());}else{this._needsRendering=true;}},_lazyRender:function(){var photos=blissbook.browser.controller.BrowserController.lazyGetPhotos();this._renderView(photos);},_renderView:function(photos){this._renderer.renderPhotos(photos);this._needsRendering=false;}};blissbook.namespace('blissbook.browser.view');blissbook.browser.view.ThumbnailsViewBasic=function(containerDomId){this.CONTAINER=containerDomId;this.THUMBNAIL_XSL='browser_thumbnails_view_basic_xsl';this.ROTATE_LINKS_PREFIX='browser_thumbnails_view_basic_rotate_links_';this.DELETE_LINK_PREFIX='browser_thumbnails_view_basic_delete_link_';this.TAG_FORM_PREFIX='browser_thumbnails_view_basic_tag_form_';this.TAGS_PREFIX='browser_thumbnails_view_basic_tags_';this.THUMB_PREFIX='browser_thumbnails_view_basic_image_';this._rotateLinksTemplate=new blissbook.browser.view.common.RotateLinksTemplate(this.CONTAINER);this._deleteLinkTemplate=new blissbook.browser.view.common.DeleteLinkTemplate(this.CONTAINER);this._tagFormTemplate=new blissbook.browser.view.common.TagFormTemplate(this.CONTAINER);this._tagsTemplate=new blissbook.browser.view.common.TagsTemplate(this.CONTAINER);this._thumbImageTemplate=new blissbook.browser.view.common.ThumbImageTemplate(this.CONTAINER);};blissbook.browser.view.ThumbnailsViewBasic.prototype={renderPhotos:function(photos){this._renderLayout(photos);for(var i=0,n=photos.length;i<n;i++){var p=photos[i];this._renderRotateLinks(i,p);this._renderDeleteLink(i,p);this._renderTagForm(i,p);this._renderTags(i,p);this._renderThumb(i,p);}},_renderLayout:function(photos){var html=xsltProcess(this._getXML(photos.length),this._getXSL());$(this.CONTAINER).update(html)},_renderRotateLinks:function(i,p){this._rotateLinksTemplate.newComponent(this.ROTATE_LINKS_PREFIX+i,p);},_renderDeleteLink:function(i,p){this._deleteLinkTemplate.newComponent(this.DELETE_LINK_PREFIX+i,p);},_renderTagForm:function(i,p){this._tagFormTemplate.newComponent(this.TAG_FORM_PREFIX+i,p,i+1);},_renderTags:function(i,p){this._tagsTemplate.newComponent(this.TAGS_PREFIX+i,p);},_renderThumb:function(i,p){this._thumbImageTemplate.newComponent(this.THUMB_PREFIX+i,p);},_getXML:function(numPhotos){var sb=['<photos><count>',numPhotos,'</count></photos>'];return xmlParse(sb.join(''));},_getXSL:function(){var xsl=xmlParse($(this.THUMBNAIL_XSL).value);this._getXSL=function(){return xsl;};return xsl;}};blissbook.namespace('blissbook.browser.view');blissbook.browser.view.ThumbnailsViewIdeasBook=function(containerDomId){this.CONTAINER=containerDomId;this.THUMBNAIL_XSL='browser_thumbnails_view_ideas_book_xsl';this.TAGS_PREFIX='browser_thumbnails_view_ideas_book_tags_';this.THUMB_PREFIX='browser_thumbnails_view_ideas_book_image_';this._ideaTagsTemplate=new blissbook.browser.view.common.IdeaTagsTemplate(this.CONTAINER);this._thumbImageTemplate=new blissbook.browser.view.common.ThumbImageTemplate(this.CONTAINER);};blissbook.browser.view.ThumbnailsViewIdeasBook.prototype={renderPhotos:function(photos){this._renderLayout(photos);for(var i=0,n=photos.length;i<n;i++){var p=photos[i];this._renderIdeaTags(i,p);this._renderThumb(i,p);}},_renderLayout:function(photos){var html=xsltProcess(this._getXML(photos.length),this._getXSL());$(this.CONTAINER).update(html)},_renderIdeaTags:function(i,p){this._ideaTagsTemplate.newComponent(this.TAGS_PREFIX+i,p);},_renderThumb:function(i,p){this._thumbImageTemplate.newComponent(this.THUMB_PREFIX+i,p);},_getXML:function(numPhotos){var sb=['<photos><count>',numPhotos,'</count></photos>'];return xmlParse(sb.join(''));},_getXSL:function(){var xsl=xmlParse($(this.THUMBNAIL_XSL).value);this._getXSL=function(){return xsl;};return xsl;}};blissbook.namespace('blissbook.browser')
blissbook.browser.PhotoBrowser={loadPhotosByAlbum:function(albumId){blissbook.browser.PhotoBrowser._loadWithBasicView(new blissbook.browser.dao.impl.AlbumScopedPhotoDAO(albumId),new blissbook.browser.view.NullMagnifyView());},loadPhotosByUser:function(userId){blissbook.browser.PhotoBrowser._loadWithBasicView(new blissbook.browser.dao.impl.UserScopedPhotoDAO(userId),new blissbook.browser.view.NullMagnifyView());},loadPhotosByWedding:function(weddingId){blissbook.browser.PhotoBrowser._loadWithBasicView(new blissbook.browser.dao.impl.WeddingScopedPhotoDAO(weddingId),new blissbook.browser.view.NullMagnifyView());},loadPhotosByTextSearch:function(query,sortBy){blissbook.util.Assert.isTrue(['id','score','ideas_count'].include(sortBy.toLowerCase()),'PhotoBrowser.loadPhotosByTextSearch: sortBy: '+sortBy);blissbook.browser.PhotoBrowser._loadWithBasicView(new blissbook.browser.dao.impl.TextSearchScopedPhotoDAO(query,sortBy.toLowerCase()),new blissbook.browser.view.MagnifyView());},loadPhotosByTag:function(tag,sortBy){blissbook.util.Assert.isTrue(['id','score','ideas_count'].include(sortBy.toLowerCase()),'PhotoBrowser.loadPhotosByTag: sortBy: '+sortBy);blissbook.browser.PhotoBrowser._loadWithBasicView(new blissbook.browser.dao.impl.TagScopedPhotoDAO(tag,sortBy.toLowerCase()),new blissbook.browser.view.MagnifyView());},loadPhotosByIdeaTag:function(tag){blissbook.browser.PhotoBrowser._loadWithIdeasBookView(new blissbook.browser.dao.impl.TagScopedIdeasBookDAO(tag),new blissbook.browser.view.NullMagnifyView());},loadPhotosByIdeaSearch:function(query){blissbook.browser.PhotoBrowser._loadWithIdeasBookView(new blissbook.browser.dao.impl.TextSearchScopedIdeasBookDAO(query),new blissbook.browser.view.NullMagnifyView());},loadPhotosByIdeaUser:function(userId){blissbook.browser.PhotoBrowser._loadWithIdeasBookView(new blissbook.browser.dao.impl.UserScopedIdeasBookDAO(userId),new blissbook.browser.view.NullMagnifyView());},_loadWithBasicView:function(photoDAO,magnifyView){blissbook.browser.PhotoBrowser._loadWith({magnifyView:magnifyView,photoDAO:photoDAO,detailsView:blissbook.browser.view.DetailsView.createBasicView(),singleView:blissbook.browser.view.SingleView.createBasicView(),slideShowView:blissbook.browser.view.SlideShowView.createBasicView(),thumbnailsView:blissbook.browser.view.ThumbnailsView.createBasicView()});},_loadWithIdeasBookView:function(photoDAO,magnifyView){blissbook.browser.PhotoBrowser._loadWith({magnifyView:magnifyView,photoDAO:photoDAO,detailsView:blissbook.browser.view.DetailsView.createIdeasBookView(),singleView:blissbook.browser.view.SingleView.createIdeasBookView(),slideShowView:blissbook.browser.view.SlideShowView.createIdeasBookView(),thumbnailsView:blissbook.browser.view.ThumbnailsView.createIdeasBookView()});},_loadWith:function(o){if(blissbook.browser.PhotoBrowser._isLoaded()){alert('PhotoBrowser._loadWith: only one Browser global object may be loaded per page');return;}
var ctrl=blissbook.browser.controller.BrowserController;ctrl.setPhotoModel(new blissbook.browser.domain.PhotoModel(o.photoDAO));ctrl.setDetailsView(o.detailsView);ctrl.setSingleView(o.singleView);ctrl.setSlideShowView(o.slideShowView);ctrl.setThumbnailsView(o.thumbnailsView);ctrl.setMagnifyView(o.magnifyView);ctrl.setNavigationView(new blissbook.browser.view.NavigationView());ctrl.setPaginationView(new blissbook.browser.view.PaginationView());ctrl.setProgressView(new blissbook.browser.view.ProgressView());ctrl.setConfirmTagDialog(new blissbook.browser.view.dialog.ConfirmTagDialog());ctrl.setDeleteIdeaDialog(new blissbook.browser.view.dialog.DeleteIdeaDialog());ctrl.setDeleteIdeaTagDialog(new blissbook.browser.view.dialog.DeleteIdeaTagDialog());ctrl.setDeletePhotoDialog(new blissbook.browser.view.dialog.DeletePhotoDialog());ctrl.setDeleteTagDialog(new blissbook.browser.view.dialog.DeleteTagDialog());ctrl.setReportPhotoDialog(new blissbook.browser.view.dialog.ReportPhotoDialog());Browser={slideShowReady:o.slideShowView.slideShowReady.bind(o.slideShowView),flashSelectPhoto:o.slideShowView.flashSelectPhoto.bind(o.slideShowView),doubleClickPhoto:o.slideShowView.doubleClickPhoto.bind(o.slideShowView)};Event.observe(window,'load',ctrl.goStart.bind(ctrl));},_isLoaded:function(){return typeof Browser!=='undefined'}};blissbook.namespace('blissbook.swfu');blissbook.swfu.PhotoUploadWidget=function(o){this._assertOptions(o);this.CSS_TRANSLUCENT='photo_upload_widget_translucent_spinner';this.PROGRESS_PREFIX='photo_upload_widget_progress_';this.READY_POLL=200;this._progressContainer=$(o['progressContainer']);this._statusContainer=$(o['statusContainer']);this._albumId=parseInt(o['albumId']);this._afterUploadHandler=o['afterUpload']||null;this._onUploadHandler=o['onUpload']||null;this._beforeUploadHandler=o['beforeUpload']||null;this._isSWFUReady=false;var self=this;this._swfu=new SWFUpload({upload_url:o['uploadURL'],file_types:'*.jpg;*.jpeg;*.gif;*.png;*.tiff;*.bmp;*.pict;*.tga',file_types_description:'*.jpg;*.jpeg;*.gif;*.png;*.tiff;*.bmp;*.pict;*.tga',file_size_limit:30720,flash_url:'/javascripts/lib/swfupload/swfupload_f9.swf',debug:false,swfupload_loaded_handler:self._swfUploadLoaded.bind(self),file_queued_handler:self._fileQueued.bind(self),file_dialog_complete_handler:self._fileDialogComplete.bind(self),upload_start_handler:self._uploadStart.bind(self),upload_success_handler:self._uploadSuccess.bind(self),upload_complete_handler:self._uploadComplete.bind(self)});};blissbook.swfu.PhotoUploadWidget.prototype={selectFiles:function(){if(!this._isSWFUReady){setTimeout(this.selectFiles.bind(this),this.READY_POLL);return;}
if(this._hasFilesToUpload()){return;}
this._swfu.selectFiles();},selectFile:function(){if(!this._isSWFUReady){setTimeout(this.selectFile.bind(this),this.READY_POLL);return;}
if(this._hasFilesToUpload()){return;}
this._swfu.selectFile();},_swfUploadLoaded:function(){this._isSWFUReady=true;},_fileQueued:function(file){var html='<img src="/images/upload_thumb.gif" id="'+
this.PROGRESS_PREFIX+file.id+'" class="thumbnail_upload"/>';new Insertion.Bottom(this._progressContainer,html);},_fileDialogComplete:function(numberSelected,numberQueued){if(this._beforeUploadHandler){this._beforeUploadHandler.call(null);}
this._swfu.startUpload();},_uploadStart:function(file){var msg=['Uploading file ',file.name].join('');$(this._statusContainer).update(msg);return true;},_uploadSuccess:function(file,serverData){$(this.PROGRESS_PREFIX+file.id).addClassName(this.CSS_TRANSLUCENT);if(this._onUploadHandler){this._onUploadHandler.call(null,serverData);}},_uploadComplete:function(file){if(this._hasFilesToUpload()){this._swfu.startUpload();}else{this._statusContainer.update();this._progressContainer.update();if(this._afterUploadHandler){this._afterUploadHandler.call(null);}}},_assertOptions:function(o){var Assert=blissbook.util.Assert;Assert.isValue(o,'PhotoUploadWidget._assertOptions: no options');Assert.isString(o['uploadURL'],'PhotoUploadWidget._assertOptions: no uploadURL');Assert.isValue($(o['progressContainer']),'PhotoUploadWidget._assertOptions: no progressCotnaienr');Assert.isValue($(o['statusContainer']),'PhotoUploadWidget._assertOptions: no statusContainer');Assert.isTrue(parseInt(o['albumId'])>0,'PhotoUploadWidget._assertOptions: albumId '+o['albumId']);if(o['beforeUpload']){Assert.isFunction(o['beforeUpload'],'PhotoUploadWidget._assertOptions: beforeUpload must be a function');}
if(o['onUpload']){Assert.isFunction(o['onUpload'],'PhotoUploadWidget._assertOptions: onUpload must be a function');}
if(o['afterUpload']){Assert.isFunction(o['afterUpload'],'PhotoUploadWidget._assertOptions: afterUpload must be a function');}},_hasFilesToUpload:function(){blissbook.util.Assert.isTrue(this._isSWFUReady,'PhotoUploadWidget._hasFilesToUpload: swfu not ready');return this._swfu.getStats().files_queued>0;}};
