/*
*
* Copyright (c) 2007 Andrew Tetlaw
* 
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* 
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
* 
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
* * 
*
*
* FastInit
* http://tetlaw.id.au/view/javascript/fastinit
* Andrew Tetlaw
* Version 1.4.1 (2007-03-15)
* Based on:
* http://dean.edwards.name/weblog/2006/03/faster
* http://dean.edwards.name/weblog/2006/06/again/
* Help from:
* http://www.cherny.com/webdev/26/domloaded-object-literal-updated
* 
*/
var FastInit = {
	onload : function() {
		if (FastInit.done) { return; }
		FastInit.done = true;
		for(var x = 0, al = FastInit.f.length; x < al; x++) {
			FastInit.f[x]();
		}
	},
	addOnLoad : function() {
		var a = arguments;
		for(var x = 0, al = a.length; x < al; x++) {
			if(typeof a[x] === 'function') {
				if (FastInit.done ) {
					a[x]();
				} else {
					FastInit.f.push(a[x]);
				}
			}
		}
	},
	listen : function() {
		if (/WebKit|khtml/i.test(navigator.userAgent)) {
			FastInit.timer = setInterval(function() {
				if (/loaded|complete/.test(document.readyState)) {
					clearInterval(FastInit.timer);
					delete FastInit.timer;
					FastInit.onload();
				}}, 10);
		} else if (document.addEventListener) {
			document.addEventListener('DOMContentLoaded', FastInit.onload, false);
		} else if(!FastInit.iew32) {
			if(window.addEventListener) {
				window.addEventListener('load', FastInit.onload, false);
			} else if (window.attachEvent) {
				return window.attachEvent('onload', FastInit.onload);
			}
		}
	},
	f:[],done:false,timer:null,iew32:false
};
/*@cc_on @*/
/*@if (@_win32)
FastInit.iew32 = true;
document.write('<script id="__ie_onload" defer src="' + ((location.protocol == 'https:') ? '//0' : 'javascript:void(0)') + '"><\/script>');
document.getElementById('__ie_onload').onreadystatechange = function(){if (this.readyState == 'complete') { FastInit.onload(); }};
/*@end @*/
FastInit.listen();
//v1.7
// Flash Player Version Detection
// Detect Client Browser type
// Copyright 2005-2007 Adobe Systems Incorporated.  All rights reserved.
var isIE  = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;
var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false;
var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false;

function ControlVersion()
{
	var version;
	var axo;
	var e;

	// NOTE : new ActiveXObject(strFoo) throws an exception if strFoo isn't in the registry

	try {
		// version will be set for 7.X or greater players
		axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");
		version = axo.GetVariable("$version");
	} catch (e) {
	}

	if (!version)
	{
		try {
			// version will be set for 6.X players only
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");
			
			// installed player is some revision of 6.0
			// GetVariable("$version") crashes for versions 6.0.22 through 6.0.29,
			// so we have to be careful. 
			
			// default to the first public version
			version = "WIN 6,0,21,0";

			// throws if AllowScripAccess does not exist (introduced in 6.0r47)		
			axo.AllowScriptAccess = "always";

			// safe to call for 6.0r47 or greater
			version = axo.GetVariable("$version");

		} catch (e) {
		}
	}

	if (!version)
	{
		try {
			// version will be set for 4.X or 5.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
			version = axo.GetVariable("$version");
		} catch (e) {
		}
	}

	if (!version)
	{
		try {
			// version will be set for 3.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
			version = "WIN 3,0,18,0";
		} catch (e) {
		}
	}

	if (!version)
	{
		try {
			// version will be set for 2.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
			version = "WIN 2,0,0,11";
		} catch (e) {
			version = -1;
		}
	}
	
	return version;
}

// JavaScript helper required to detect Flash Player PlugIn version information
function GetSwfVer(){
	// NS/Opera version >= 3 check for Flash plugin in plugin array
	var flashVer = -1;
	
	if (navigator.plugins != null && navigator.plugins.length > 0) {
		if (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]) {
			var swVer2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : "";
			var flashDescription = navigator.plugins["Shockwave Flash" + swVer2].description;
			var descArray = flashDescription.split(" ");
			var tempArrayMajor = descArray[2].split(".");			
			var versionMajor = tempArrayMajor[0];
			var versionMinor = tempArrayMajor[1];
			var versionRevision = descArray[3];
			if (versionRevision == "") {
				versionRevision = descArray[4];
			}
			if (versionRevision[0] == "d") {
				versionRevision = versionRevision.substring(1);
			} else if (versionRevision[0] == "r") {
				versionRevision = versionRevision.substring(1);
				if (versionRevision.indexOf("d") > 0) {
					versionRevision = versionRevision.substring(0, versionRevision.indexOf("d"));
				}
			}
			var flashVer = versionMajor + "." + versionMinor + "." + versionRevision;
		}
	}
	// MSN/WebTV 2.6 supports Flash 4
	else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.6") != -1) flashVer = 4;
	// WebTV 2.5 supports Flash 3
	else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.5") != -1) flashVer = 3;
	// older WebTV supports Flash 2
	else if (navigator.userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = 2;
	else if ( isIE && isWin && !isOpera ) {
		flashVer = ControlVersion();
	}	
	return flashVer;
}

// When called with reqMajorVer, reqMinorVer, reqRevision returns true if that version or greater is available
function DetectFlashVer(reqMajorVer, reqMinorVer, reqRevision)
{
	versionStr = GetSwfVer();
	if (versionStr == -1 ) {
		return false;
	} else if (versionStr != 0) {
		if(isIE && isWin && !isOpera) {
			// Given "WIN 2,0,0,11"
			tempArray         = versionStr.split(" "); 	// ["WIN", "2,0,0,11"]
			tempString        = tempArray[1];			// "2,0,0,11"
			versionArray      = tempString.split(",");	// ['2', '0', '0', '11']
		} else {
			versionArray      = versionStr.split(".");
		}
		var versionMajor      = versionArray[0];
		var versionMinor      = versionArray[1];
		var versionRevision   = versionArray[2];

        	// is the major.revision >= requested major.revision AND the minor version >= requested minor
		if (versionMajor > parseFloat(reqMajorVer)) {
			return true;
		} else if (versionMajor == parseFloat(reqMajorVer)) {
			if (versionMinor > parseFloat(reqMinorVer))
				return true;
			else if (versionMinor == parseFloat(reqMinorVer)) {
				if (versionRevision >= parseFloat(reqRevision))
					return true;
			}
		}
		return false;
	}
}

function AC_AddExtension(src, ext)
{
  if (src.indexOf('?') != -1)
    return src.replace(/\?/, ext+'?'); 
  else
    return src + ext;
}

function AC_Generateobj(objAttrs, params, embedAttrs) 
{ 
  var str = '';
  if (isIE && isWin && !isOpera)
  {
    str += '<object ';
    for (var i in objAttrs)
    {
      str += i + '="' + objAttrs[i] + '" ';
    }
    str += '>';
    for (var i in params)
    {
      str += '<param name="' + i + '" value="' + params[i] + '" /> ';
    }
    str += '</object>';
  }
  else
  {
    str += '<embed ';
    for (var i in embedAttrs)
    {
      str += i + '="' + embedAttrs[i] + '" ';
    }
    str += '> </embed>';
  }

  document.write(str);
}

function AC_FL_RunContent(){
  var ret = 
    AC_GetArgs
    (  arguments, ".swf", "movie", "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
     , "application/x-shockwave-flash"
    );
  AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
}

function AC_SW_RunContent(){
  var ret = 
    AC_GetArgs
    (  arguments, ".dcr", "src", "clsid:166B1BCA-3F9C-11CF-8075-444553540000"
     , null
    );
  AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
}

function AC_GetArgs(args, ext, srcParamName, classid, mimeType){
  var ret = new Object();
  ret.embedAttrs = new Object();
  ret.params = new Object();
  ret.objAttrs = new Object();
  for (var i=0; i < args.length; i=i+2){
    var currArg = args[i].toLowerCase();    

    switch (currArg){	
      case "classid":
        break;
      case "pluginspage":
        ret.embedAttrs[args[i]] = args[i+1];
        break;
      case "src":
      case "movie":	
        args[i+1] = AC_AddExtension(args[i+1], ext);
        ret.embedAttrs["src"] = args[i+1];
        ret.params[srcParamName] = args[i+1];
        break;
      case "onafterupdate":
      case "onbeforeupdate":
      case "onblur":
      case "oncellchange":
      case "onclick":
      case "ondblclick":
      case "ondrag":
      case "ondragend":
      case "ondragenter":
      case "ondragleave":
      case "ondragover":
      case "ondrop":
      case "onfinish":
      case "onfocus":
      case "onhelp":
      case "onmousedown":
      case "onmouseup":
      case "onmouseover":
      case "onmousemove":
      case "onmouseout":
      case "onkeypress":
      case "onkeydown":
      case "onkeyup":
      case "onload":
      case "onlosecapture":
      case "onpropertychange":
      case "onreadystatechange":
      case "onrowsdelete":
      case "onrowenter":
      case "onrowexit":
      case "onrowsinserted":
      case "onstart":
      case "onscroll":
      case "onbeforeeditfocus":
      case "onactivate":
      case "onbeforedeactivate":
      case "ondeactivate":
      case "type":
      case "codebase":
      case "id":
        ret.objAttrs[args[i]] = args[i+1];
        break;
      case "width":
      case "height":
      case "align":
      case "vspace": 
      case "hspace":
      case "class":
      case "title":
      case "accesskey":
      case "name":
      case "tabindex":
        ret.embedAttrs[args[i]] = ret.objAttrs[args[i]] = args[i+1];
        break;
      default:
        ret.embedAttrs[args[i]] = ret.params[args[i]] = args[i+1];
    }
  }
  ret.objAttrs["classid"] = classid;
  if (mimeType) ret.embedAttrs["type"] = mimeType;
  return ret;
}
//prototype.js
var Prototype={Version:'1.6.0.2',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,MobileSafari:!!navigator.userAgent.match(/Apple.*Mobile.*Safari/)},BrowserFeatures:{XPath:!!document.evaluate,ElementExtensions:!!window.HTMLElement,SpecificElementExtensions:document.createElement('div').__proto__&&document.createElement('div').__proto__!==document.createElement('form').__proto__},ScriptFragment:'<script[^>]*>([\\S\\s]*?)<\/script>',JSONFilter:/^\/\*-secure-([\s\S]*)\*\/\s*$/,emptyFunction:function(){},K:function(x){return x}};if(Prototype.Browser.MobileSafari)Prototype.BrowserFeatures.SpecificElementExtensions=false;var Class={create:function(){var a=null,properties=$A(arguments);if(Object.isFunction(properties[0]))a=properties.shift();function klass(){this.initialize.apply(this,arguments)}Object.extend(klass,Class.Methods);klass.superclass=a;klass.subclasses=[];if(a){var b=function(){};b.prototype=a.prototype;klass.prototype=new b;a.subclasses.push(klass)}for(var i=0;i<properties.length;i++)klass.addMethods(properties[i]);if(!klass.prototype.initialize)klass.prototype.initialize=Prototype.emptyFunction;klass.prototype.constructor=klass;return klass}};Class.Methods={addMethods:function(a){var b=this.superclass&&this.superclass.prototype;var c=Object.keys(a);if(!Object.keys({toString:true}).length)c.push("toString","valueOf");for(var i=0,length=c.length;i<length;i++){var d=c[i],value=a[d];if(b&&Object.isFunction(value)&&value.argumentNames().first()=="$super"){var e=value,value=Object.extend((function(m){return function(){return b[m].apply(this,arguments)}})(d).wrap(e),{valueOf:function(){return e},toString:function(){return e.toString()}})}this.prototype[d]=value}return this}};var Abstract={};Object.extend=function(a,b){for(var c in b)a[c]=b[c];return a};Object.extend(Object,{inspect:function(a){try{if(Object.isUndefined(a))return'undefined';if(a===null)return'null';return a.inspect?a.inspect():String(a)}catch(e){if(e instanceof RangeError)return'...';throw e;}},toJSON:function(a){var b=typeof a;switch(b){case'undefined':case'function':case'unknown':return;case'boolean':return a.toString()}if(a===null)return'null';if(a.toJSON)return a.toJSON();if(Object.isElement(a))return;var c=[];for(var d in a){var e=Object.toJSON(a[d]);if(!Object.isUndefined(e))c.push(d.toJSON()+': '+e)}return'{'+c.join(', ')+'}'},toQueryString:function(a){return $H(a).toQueryString()},toHTML:function(a){return a&&a.toHTML?a.toHTML():String.interpret(a)},keys:function(a){var b=[];for(var c in a)b.push(c);return b},values:function(a){var b=[];for(var c in a)b.push(a[c]);return b},clone:function(a){return Object.extend({},a)},isElement:function(a){return a&&a.nodeType==1},isArray:function(a){return a!=null&&typeof a=="object"&&'splice'in a&&'join'in a},isHash:function(a){return a instanceof Hash},isFunction:function(a){return typeof a=="function"},isString:function(a){return typeof a=="string"},isNumber:function(a){return typeof a=="number"},isUndefined:function(a){return typeof a=="undefined"}});Object.extend(Function.prototype,{argumentNames:function(){var a=this.toString().match(/^[\s\(]*function[^(]*\((.*?)\)/)[1].split(",").invoke("strip");return a.length==1&&!a[0]?[]:a},bind:function(){if(arguments.length<2&&Object.isUndefined(arguments[0]))return this;var a=this,args=$A(arguments),object=args.shift();return function(){return a.apply(object,args.concat($A(arguments)))}},bindAsEventListener:function(){var b=this,args=$A(arguments),object=args.shift();return function(a){return b.apply(object,[a||window.event].concat(args))}},curry:function(){if(!arguments.length)return this;var a=this,args=$A(arguments);return function(){return a.apply(this,args.concat($A(arguments)))}},delay:function(){var a=this,args=$A(arguments),timeout=args.shift()*1000;return window.setTimeout(function(){return a.apply(a,args)},timeout)},wrap:function(a){var b=this;return function(){return a.apply(this,[b.bind(this)].concat($A(arguments)))}},methodize:function(){if(this._methodized)return this._methodized;var a=this;return this._methodized=function(){return a.apply(null,[this].concat($A(arguments)))}}});Function.prototype.defer=Function.prototype.delay.curry(0.01);Date.prototype.toJSON=function(){return'"'+this.getUTCFullYear()+'-'+(this.getUTCMonth()+1).toPaddedString(2)+'-'+this.getUTCDate().toPaddedString(2)+'T'+this.getUTCHours().toPaddedString(2)+':'+this.getUTCMinutes().toPaddedString(2)+':'+this.getUTCSeconds().toPaddedString(2)+'Z"'};var Try={these:function(){var a;for(var i=0,length=arguments.length;i<length;i++){var b=arguments[i];try{a=b();break}catch(e){}}return a}};RegExp.prototype.match=RegExp.prototype.test;RegExp.escape=function(a){return String(a).replace(/([.*+?^=!:${}()|[\]\/\\])/g,'\\$1')};var PeriodicalExecuter=Class.create({initialize:function(a,b){this.callback=a;this.frequency=b;this.currentlyExecuting=false;this.registerCallback()},registerCallback:function(){this.timer=setInterval(this.onTimerEvent.bind(this),this.frequency*1000)},execute:function(){this.callback(this)},stop:function(){if(!this.timer)return;clearInterval(this.timer);this.timer=null},onTimerEvent:function(){if(!this.currentlyExecuting){try{this.currentlyExecuting=true;this.execute()}finally{this.currentlyExecuting=false}}}});Object.extend(String,{interpret:function(a){return a==null?'':String(a)},specialChar:{'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\f','\r':'\\r','\\':'\\\\'}});Object.extend(String.prototype,{gsub:function(a,b){var c='',source=this,match;b=arguments.callee.prepareReplacement(b);while(source.length>0){if(match=source.match(a)){c+=source.slice(0,match.index);c+=String.interpret(b(match));source=source.slice(match.index+match[0].length)}else{c+=source,source=''}}return c},sub:function(b,c,d){c=this.gsub.prepareReplacement(c);d=Object.isUndefined(d)?1:d;return this.gsub(b,function(a){if(--d<0)return a[0];return c(a)})},scan:function(a,b){this.gsub(a,b);return String(this)},truncate:function(a,b){a=a||30;b=Object.isUndefined(b)?'...':b;return this.length>a?this.slice(0,a-b.length)+b:String(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 b=new RegExp(Prototype.ScriptFragment,'img');var c=new RegExp(Prototype.ScriptFragment,'im');return(this.match(b)||[]).map(function(a){return(a.match(c)||['',''])[1]})},evalScripts:function(){return this.extractScripts().map(function(a){return eval(a)})},escapeHTML:function(){var a=arguments.callee;a.text.data=this;return a.div.innerHTML},unescapeHTML:function(){var c=new Element('div');c.innerHTML=this.stripTags();return c.childNodes[0]?(c.childNodes.length>1?$A(c.childNodes).inject('',function(a,b){return a+b.nodeValue}):c.childNodes[0].nodeValue):''},toQueryParams:function(e){var f=this.strip().match(/([^?#]*)(#.*)?$/);if(!f)return{};return f[1].split(e||'&').inject({},function(a,b){if((b=b.split('='))[0]){var c=decodeURIComponent(b.shift());var d=b.length>1?b.join('='):b[0];if(d!=undefined)d=decodeURIComponent(d);if(c in a){if(!Object.isArray(a[c]))a[c]=[a[c]];a[c].push(d)}else a[c]=d}return a})},toArray:function(){return this.split('')},succ:function(){return this.slice(0,this.length-1)+String.fromCharCode(this.charCodeAt(this.length-1)+1)},times:function(a){return a<1?'':new Array(a+1).join(this)},camelize:function(){var a=this.split('-'),len=a.length;if(len==1)return a[0];var b=this.charAt(0)=='-'?a[0].charAt(0).toUpperCase()+a[0].substring(1):a[0];for(var i=1;i<len;i++)b+=a[i].charAt(0).toUpperCase()+a[i].substring(1);return b},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(c){var d=this.gsub(/[\x00-\x1f\\]/,function(a){var b=String.specialChar[a[0]];return b?b:'\\u00'+a[0].charCodeAt().toPaddedString(2,16)});if(c)return'"'+d.replace(/"/g,'\\"')+'"';return"'"+d.replace(/'/g,'\\\'')+"'"},toJSON:function(){return this.inspect(true)},unfilterJSON:function(a){return this.sub(a||Prototype.JSONFilter,'#{1}')},isJSON:function(){var a=this;if(a.blank())return false;a=this.replace(/\\./g,'@').replace(/"[^"\\\n\r]*"/g,'');return(/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/).test(a)},evalJSON:function(a){var b=this.unfilterJSON();try{if(!a||b.isJSON())return eval('('+b+')')}catch(e){}throw new SyntaxError('Badly formed JSON string: '+this.inspect());},include:function(a){return this.indexOf(a)>-1},startsWith:function(a){return this.indexOf(a)===0},endsWith:function(a){var d=this.length-a.length;return d>=0&&this.lastIndexOf(a)===d},empty:function(){return this==''},blank:function(){return/^\s*$/.test(this)},interpolate:function(a,b){return new Template(this,b).evaluate(a)}});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(b){if(Object.isFunction(b))return b;var c=new Template(b);return function(a){return c.evaluate(a)}};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({initialize:function(a,b){this.template=a.toString();this.pattern=b||Template.Pattern},evaluate:function(f){if(Object.isFunction(f.toTemplateReplacements))f=f.toTemplateReplacements();return this.template.gsub(this.pattern,function(a){if(f==null)return'';var b=a[1]||'';if(b=='\\')return a[2];var c=f,expr=a[3];var d=/^([^.[]+|\[((?:.*?[^\\])?)\])(\.|\[|$)/;a=d.exec(expr);if(a==null)return b;while(a!=null){var e=a[1].startsWith('[')?a[2].gsub('\\\\]',']'):a[1];c=c[e];if(null==c||''==a[3])break;expr=expr.substring('['==a[3]?a[1].length:a[0].length);a=d.exec(expr)}return b+String.interpret(c)})}});Template.Pattern=/(^|.|\r|\n)(#\{(.*?)\})/;var $break={};var Enumerable={each:function(b,c){var d=0;b=b.bind(c);try{this._each(function(a){b(a,d++)})}catch(e){if(e!=$break)throw e;}return this},eachSlice:function(a,b,c){b=b?b.bind(c):Prototype.K;var d=-a,slices=[],array=this.toArray();while((d+=a)<array.length)slices.push(array.slice(d,d+a));return slices.collect(b,c)},all:function(c,d){c=c?c.bind(d):Prototype.K;var e=true;this.each(function(a,b){e=e&&!!c(a,b);if(!e)throw $break;});return e},any:function(c,d){c=c?c.bind(d):Prototype.K;var e=false;this.each(function(a,b){if(e=!!c(a,b))throw $break;});return e},collect:function(c,d){c=c?c.bind(d):Prototype.K;var e=[];this.each(function(a,b){e.push(c(a,b))});return e},detect:function(c,d){c=c.bind(d);var e;this.each(function(a,b){if(c(a,b)){e=a;throw $break;}});return e},findAll:function(c,d){c=c.bind(d);var e=[];this.each(function(a,b){if(c(a,b))e.push(a)});return e},grep:function(c,d,e){d=d?d.bind(e):Prototype.K;var f=[];if(Object.isString(c))c=new RegExp(c);this.each(function(a,b){if(c.match(a))f.push(d(a,b))});return f},include:function(b){if(Object.isFunction(this.indexOf))if(this.indexOf(b)!=-1)return true;var c=false;this.each(function(a){if(a==b){c=true;throw $break;}});return c},inGroupsOf:function(b,c){c=Object.isUndefined(c)?null:c;return this.eachSlice(b,function(a){while(a.length<b)a.push(c);return a})},inject:function(c,d,e){d=d.bind(e);this.each(function(a,b){c=d(c,a,b)});return c},invoke:function(b){var c=$A(arguments).slice(1);return this.map(function(a){return a[b].apply(a,c)})},max:function(c,d){c=c?c.bind(d):Prototype.K;var e;this.each(function(a,b){a=c(a,b);if(e==null||a>=e)e=a});return e},min:function(c,d){c=c?c.bind(d):Prototype.K;var e;this.each(function(a,b){a=c(a,b);if(e==null||a<e)e=a});return e},partition:function(c,d){c=c?c.bind(d):Prototype.K;var e=[],falses=[];this.each(function(a,b){(c(a,b)?e:falses).push(a)});return[e,falses]},pluck:function(b){var c=[];this.each(function(a){c.push(a[b])});return c},reject:function(c,d){c=c.bind(d);var e=[];this.each(function(a,b){if(!c(a,b))e.push(a)});return e},sortBy:function(e,f){e=e.bind(f);return this.map(function(a,b){return{value:a,criteria:e(a,b)}}).sort(function(c,d){var a=c.criteria,b=d.criteria;return a<b?-1:a>b?1:0}).pluck('value')},toArray:function(){return this.map()},zip:function(){var c=Prototype.K,args=$A(arguments);if(Object.isFunction(args.last()))c=args.pop();var d=[this].concat(args).map($A);return this.map(function(a,b){return c(d.pluck(b))})},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,filter:Enumerable.findAll,member:Enumerable.include,entries:Enumerable.toArray,every:Enumerable.all,some:Enumerable.any});function $A(a){if(!a)return[];if(a.toArray)return a.toArray();var b=a.length||0,results=new Array(b);while(b--)results[b]=a[b];return results}if(Prototype.Browser.WebKit){$A=function(a){if(!a)return[];if(!(Object.isFunction(a)&&a=='[object NodeList]')&&a.toArray)return a.toArray();var b=a.length||0,results=new Array(b);while(b--)results[b]=a[b];return results}}Array.from=$A;Object.extend(Array.prototype,Enumerable);if(!Array.prototype._reverse)Array.prototype._reverse=Array.prototype.reverse;Object.extend(Array.prototype,{_each:function(a){for(var i=0,length=this.length;i<length;i++)a(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(a){return a!=null})},flatten:function(){return this.inject([],function(a,b){return a.concat(Object.isArray(b)?b.flatten():[b])})},without:function(){var b=$A(arguments);return this.select(function(a){return!b.include(a)})},reverse:function(a){return(a!==false?this:this.toArray())._reverse()},reduce:function(){return this.length>1?this:this[0]},uniq:function(d){return this.inject([],function(a,b,c){if(0==c||(d?a.last()!=b:!a.include(b)))a.push(b);return a})},intersect:function(c){return this.uniq().findAll(function(b){return c.detect(function(a){return b===a})})},clone:function(){return[].concat(this)},size:function(){return this.length},inspect:function(){return'['+this.map(Object.inspect).join(', ')+']'},toJSON:function(){var c=[];this.each(function(a){var b=Object.toJSON(a);if(!Object.isUndefined(b))c.push(b)});return'['+c.join(', ')+']'}});if(Object.isFunction(Array.prototype.forEach))Array.prototype._each=Array.prototype.forEach;if(!Array.prototype.indexOf)Array.prototype.indexOf=function(a,i){i||(i=0);var b=this.length;if(i<0)i=b+i;for(;i<b;i++)if(this[i]===a)return i;return-1};if(!Array.prototype.lastIndexOf)Array.prototype.lastIndexOf=function(a,i){i=isNaN(i)?this.length:(i<0?this.length+i:i)+1;var n=this.slice(0,i).reverse().indexOf(a);return(n<0)?n:i-n-1};Array.prototype.toArray=Array.prototype.clone;function $w(a){if(!Object.isString(a))return[];a=a.strip();return a?a.split(/\s+/):[]}if(Prototype.Browser.Opera){Array.prototype.concat=function(){var a=[];for(var i=0,length=this.length;i<length;i++)a.push(this[i]);for(var i=0,length=arguments.length;i<length;i++){if(Object.isArray(arguments[i])){for(var j=0,arrayLength=arguments[i].length;j<arrayLength;j++)a.push(arguments[i][j])}else{a.push(arguments[i])}}return a}}Object.extend(Number.prototype,{toColorPart:function(){return this.toPaddedString(2,16)},succ:function(){return this+1},times:function(a){$R(0,this,true).each(a);return this},toPaddedString:function(a,b){var c=this.toString(b||10);return'0'.times(a-c.length)+c},toJSON:function(){return isFinite(this)?this.toString():'null'}});$w('abs round ceil floor').each(function(a){Number.prototype[a]=Math[a].methodize()});function $H(a){return new Hash(a)};var Hash=Class.create(Enumerable,(function(){function toQueryPair(a,b){if(Object.isUndefined(b))return a;return a+'='+encodeURIComponent(String.interpret(b))}return{initialize:function(a){this._object=Object.isHash(a)?a.toObject():Object.clone(a)},_each:function(a){for(var b in this._object){var c=this._object[b],pair=[b,c];pair.key=b;pair.value=c;a(pair)}},set:function(a,b){return this._object[a]=b},get:function(a){return this._object[a]},unset:function(a){var b=this._object[a];delete this._object[a];return b},toObject:function(){return Object.clone(this._object)},keys:function(){return this.pluck('key')},values:function(){return this.pluck('value')},index:function(b){var c=this.detect(function(a){return a.value===b});return c&&c.key},merge:function(a){return this.clone().update(a)},update:function(c){return new Hash(c).inject(this,function(a,b){a.set(b.key,b.value);return a})},toQueryString:function(){return this.map(function(a){var b=encodeURIComponent(a.key),values=a.value;if(values&&typeof values=='object'){if(Object.isArray(values))return values.map(toQueryPair.curry(b)).join('&')}return toQueryPair(b,values)}).join('&')},inspect:function(){return'#<Hash:{'+this.map(function(a){return a.map(Object.inspect).join(': ')}).join(', ')+'}>'},toJSON:function(){return Object.toJSON(this.toObject())},clone:function(){return new Hash(this)}}})());Hash.prototype.toTemplateReplacements=Hash.prototype.toObject;Hash.from=$H;var ObjectRange=Class.create(Enumerable,{initialize:function(a,b,c){this.start=a;this.end=b;this.exclusive=c},_each:function(a){var b=this.start;while(this.include(b)){a(b);b=b.succ()}},include:function(a){if(a<this.start)return false;if(this.exclusive)return a<this.end;return a<=this.end}});var $R=function(a,b,c){return new ObjectRange(a,b,c)};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(a){this.responders._each(a)},register:function(a){if(!this.include(a))this.responders.push(a)},unregister:function(a){this.responders=this.responders.without(a)},dispatch:function(b,c,d,f){this.each(function(a){if(Object.isFunction(a[b])){try{a[b].apply(a,[c,d,f])}catch(e){}}})}};Object.extend(Ajax.Responders,Enumerable);Ajax.Responders.register({onCreate:function(){Ajax.activeRequestCount++},onComplete:function(){Ajax.activeRequestCount--}});Ajax.Base=Class.create({initialize:function(a){this.options={method:'post',asynchronous:true,contentType:'application/x-www-form-urlencoded',encoding:'UTF-8',parameters:'',evalJSON:true,evalJS:true};Object.extend(this.options,a||{});this.options.method=this.options.method.toLowerCase();if(Object.isString(this.options.parameters))this.options.parameters=this.options.parameters.toQueryParams();else if(Object.isHash(this.options.parameters))this.options.parameters=this.options.parameters.toObject()}});Ajax.Request=Class.create(Ajax.Base,{_complete:false,initialize:function($super,b,c){$super(c);this.transport=Ajax.getTransport();this.request(b)},request:function(a){this.url=a;this.method=this.options.method;var b=Object.clone(this.options.parameters);if(!['get','post'].include(this.method)){b['_method']=this.method;this.method='post'}this.parameters=b;if(b=Object.toQueryString(b)){if(this.method=='get')this.url+=(this.url.include('?')?'&':'?')+b;else if(/Konqueror|Safari|KHTML/.test(navigator.userAgent))b+='&_='}try{var c=new Ajax.Response(this);if(this.options.onCreate)this.options.onCreate(c);Ajax.Responders.dispatch('onCreate',this,c);this.transport.open(this.method.toUpperCase(),this.url,this.options.asynchronous);if(this.options.asynchronous)this.respondToReadyState.bind(this).defer(1);this.transport.onreadystatechange=this.onStateChange.bind(this);this.setRequestHeaders();this.body=this.method=='post'?(this.options.postBody||b):null;this.transport.send(this.body);if(!this.options.asynchronous&&this.transport.overrideMimeType)this.onStateChange()}catch(e){this.dispatchException(e)}},onStateChange:function(){var a=this.transport.readyState;if(a>1&&!((a==4)&&this._complete))this.respondToReadyState(this.transport.readyState)},setRequestHeaders:function(){var b={'X-Requested-With':'XMLHttpRequest','X-Prototype-Version':Prototype.Version,'Accept':'text/javascript, text/html, application/xml, text/xml, */*'};if(this.method=='post'){b['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)b['Connection']='close'}if(typeof this.options.requestHeaders=='object'){var c=this.options.requestHeaders;if(Object.isFunction(c.push))for(var i=0,length=c.length;i<length;i+=2)b[c[i]]=c[i+1];else $H(c).each(function(a){b[a.key]=a.value})}for(var d in b)this.transport.setRequestHeader(d,b[d])},success:function(){var a=this.getStatus();return!a||(a>=200&&a<300)},getStatus:function(){try{return this.transport.status||0}catch(e){return 0}},respondToReadyState:function(a){var b=Ajax.Request.Events[a],response=new Ajax.Response(this);if(b=='Complete'){try{this._complete=true;(this.options['on'+response.status]||this.options['on'+(this.success()?'Success':'Failure')]||Prototype.emptyFunction)(response,response.headerJSON)}catch(e){this.dispatchException(e)}var c=response.getHeader('Content-type');if(this.options.evalJS=='force'||(this.options.evalJS&&this.isSameOrigin()&&c&&c.match(/^\s*(text|application)\/(x-)?(java|ecma)script(;.*)?\s*$/i)))this.evalResponse()}try{(this.options['on'+b]||Prototype.emptyFunction)(response,response.headerJSON);Ajax.Responders.dispatch('on'+b,this,response,response.headerJSON)}catch(e){this.dispatchException(e)}if(b=='Complete'){this.transport.onreadystatechange=Prototype.emptyFunction}},isSameOrigin:function(){var m=this.url.match(/^\s*https?:\/\/[^\/]*/);return!m||(m[0]=='#{protocol}//#{domain}#{port}'.interpolate({protocol:location.protocol,domain:document.domain,port:location.port?':'+location.port:''}))},getHeader:function(a){try{return this.transport.getResponseHeader(a)||null}catch(e){return null}},evalResponse:function(){try{return eval((this.transport.responseText||'').unfilterJSON())}catch(e){this.dispatchException(e)}},dispatchException:function(a){(this.options.onException||Prototype.emptyFunction)(this,a);Ajax.Responders.dispatch('onException',this,a)}});Ajax.Request.Events=['Uninitialized','Loading','Loaded','Interactive','Complete'];Ajax.Response=Class.create({initialize:function(a){this.request=a;var b=this.transport=a.transport,readyState=this.readyState=b.readyState;if((readyState>2&&!Prototype.Browser.IE)||readyState==4){this.status=this.getStatus();this.statusText=this.getStatusText();this.responseText=String.interpret(b.responseText);this.headerJSON=this._getHeaderJSON()}if(readyState==4){var c=b.responseXML;this.responseXML=Object.isUndefined(c)?null:c;this.responseJSON=this._getResponseJSON()}},status:0,statusText:'',getStatus:Ajax.Request.prototype.getStatus,getStatusText:function(){try{return this.transport.statusText||''}catch(e){return''}},getHeader:Ajax.Request.prototype.getHeader,getAllHeaders:function(){try{return this.getAllResponseHeaders()}catch(e){return null}},getResponseHeader:function(a){return this.transport.getResponseHeader(a)},getAllResponseHeaders:function(){return this.transport.getAllResponseHeaders()},_getHeaderJSON:function(){var a=this.getHeader('X-JSON');if(!a)return null;a=decodeURIComponent(escape(a));try{return a.evalJSON(this.request.options.sanitizeJSON||!this.request.isSameOrigin())}catch(e){this.request.dispatchException(e)}},_getResponseJSON:function(){var a=this.request.options;if(!a.evalJSON||(a.evalJSON!='force'&&!(this.getHeader('Content-type')||'').include('application/json'))||this.responseText.blank())return null;try{return this.responseText.evalJSON(a.sanitizeJSON||!this.request.isSameOrigin())}catch(e){this.request.dispatchException(e)}}});Ajax.Updater=Class.create(Ajax.Request,{initialize:function($super,d,e,f){this.container={success:(d.success||d),failure:(d.failure||(d.success?null:d))};f=Object.clone(f);var g=f.onComplete;f.onComplete=(function(a,b){this.updateContent(a.responseText);if(Object.isFunction(g))g(a,b)}).bind(this);$super(e,f)},updateContent:function(a){var b=this.container[this.success()?'success':'failure'],options=this.options;if(!options.evalScripts)a=a.stripScripts();if(b=$(b)){if(options.insertion){if(Object.isString(options.insertion)){var c={};c[options.insertion]=a;b.insert(c)}else options.insertion(b,a)}else b.update(a)}}});Ajax.PeriodicalUpdater=Class.create(Ajax.Base,{initialize:function($super,b,c,d){$super(d);this.onComplete=this.options.onComplete;this.frequency=(this.options.frequency||2);this.decay=(this.options.decay||1);this.updater={};this.container=b;this.url=c;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(a){if(this.options.decay){this.decay=(a.responseText==this.lastText?this.decay*this.options.decay:1);this.lastText=a.responseText}this.timer=this.onTimerEvent.bind(this).delay(this.decay*this.frequency)},onTimerEvent:function(){this.updater=new Ajax.Updater(this.container,this.url,this.options)}});function $(a){if(arguments.length>1){for(var i=0,elements=[],length=arguments.length;i<length;i++)elements.push($(arguments[i]));return elements}if(Object.isString(a))a=document.getElementById(a);return Element.extend(a)}if(Prototype.BrowserFeatures.XPath){document._getElementsByXPath=function(a,b){var c=[];var d=document.evaluate(a,$(b)||document,null,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,null);for(var i=0,length=d.snapshotLength;i<length;i++)c.push(Element.extend(d.snapshotItem(i)));return c}}if(!window.Node)var Node={};if(!Node.ELEMENT_NODE){Object.extend(Node,{ELEMENT_NODE:1,ATTRIBUTE_NODE:2,TEXT_NODE:3,CDATA_SECTION_NODE:4,ENTITY_REFERENCE_NODE:5,ENTITY_NODE:6,PROCESSING_INSTRUCTION_NODE:7,COMMENT_NODE:8,DOCUMENT_NODE:9,DOCUMENT_TYPE_NODE:10,DOCUMENT_FRAGMENT_NODE:11,NOTATION_NODE:12})}(function(){var d=this.Element;this.Element=function(a,b){b=b||{};a=a.toLowerCase();var c=Element.cache;if(Prototype.Browser.IE&&b.name){a='<'+a+' name="'+b.name+'">';delete b.name;return Element.writeAttribute(document.createElement(a),b)}if(!c[a])c[a]=Element.extend(document.createElement(a));return Element.writeAttribute(c[a].cloneNode(false),b)};Object.extend(this.Element,d||{})}).call(window);Element.cache={};Element.Methods={visible:function(a){return $(a).style.display!='none'},toggle:function(a){a=$(a);Element[Element.visible(a)?'hide':'show'](a);return a},hide:function(a){$(a).style.display='none';return a},show:function(a){$(a).style.display='';return a},remove:function(a){a=$(a);a.parentNode.removeChild(a);return a},update:function(a,b){a=$(a);if(b&&b.toElement)b=b.toElement();if(Object.isElement(b))return a.update().insert(b);b=Object.toHTML(b);a.innerHTML=b.stripScripts();b.evalScripts.bind(b).defer();return a},replace:function(a,b){a=$(a);if(b&&b.toElement)b=b.toElement();else if(!Object.isElement(b)){b=Object.toHTML(b);var c=a.ownerDocument.createRange();c.selectNode(a);b.evalScripts.bind(b).defer();b=c.createContextualFragment(b.stripScripts())}a.parentNode.replaceChild(b,a);return a},insert:function(a,b){a=$(a);if(Object.isString(b)||Object.isNumber(b)||Object.isElement(b)||(b&&(b.toElement||b.toHTML)))b={bottom:b};var c,insert,tagName,childNodes;for(var d in b){c=b[d];d=d.toLowerCase();insert=Element._insertionTranslations[d];if(c&&c.toElement)c=c.toElement();if(Object.isElement(c)){insert(a,c);continue}c=Object.toHTML(c);tagName=((d=='before'||d=='after')?a.parentNode:a).tagName.toUpperCase();childNodes=Element._getContentFromAnonymousElement(tagName,c.stripScripts());if(d=='top'||d=='after')childNodes.reverse();childNodes.each(insert.curry(a));c.evalScripts.bind(c).defer()}return a},wrap:function(a,b,c){a=$(a);if(Object.isElement(b))$(b).writeAttribute(c||{});else if(Object.isString(b))b=new Element(b,c);else b=new Element('div',b);if(a.parentNode)a.parentNode.replaceChild(b,a);b.appendChild(a);return b},inspect:function(d){d=$(d);var e='<'+d.tagName.toLowerCase();$H({'id':'id','className':'class'}).each(function(a){var b=a.first(),attribute=a.last();var c=(d[b]||'').toString();if(c)e+=' '+attribute+'='+c.inspect(true)});return e+'>'},recursivelyCollect:function(a,b){a=$(a);var c=[];while(a=a[b])if(a.nodeType==1)c.push(Element.extend(a));return c},ancestors:function(a){return $(a).recursivelyCollect('parentNode')},descendants:function(a){return $(a).select("*")},firstDescendant:function(a){a=$(a).firstChild;while(a&&a.nodeType!=1)a=a.nextSibling;return $(a)},immediateDescendants:function(a){if(!(a=$(a).firstChild))return[];while(a&&a.nodeType!=1)a=a.nextSibling;if(a)return[a].concat($(a).nextSiblings());return[]},previousSiblings:function(a){return $(a).recursivelyCollect('previousSibling')},nextSiblings:function(a){return $(a).recursivelyCollect('nextSibling')},siblings:function(a){a=$(a);return a.previousSiblings().reverse().concat(a.nextSiblings())},match:function(a,b){if(Object.isString(b))b=new Selector(b);return b.match($(a))},up:function(a,b,c){a=$(a);if(arguments.length==1)return $(a.parentNode);var d=a.ancestors();return Object.isNumber(b)?d[b]:Selector.findElement(d,b,c)},down:function(a,b,c){a=$(a);if(arguments.length==1)return a.firstDescendant();return Object.isNumber(b)?a.descendants()[b]:a.select(b)[c||0]},previous:function(a,b,c){a=$(a);if(arguments.length==1)return $(Selector.handlers.previousElementSibling(a));var d=a.previousSiblings();return Object.isNumber(b)?d[b]:Selector.findElement(d,b,c)},next:function(a,b,c){a=$(a);if(arguments.length==1)return $(Selector.handlers.nextElementSibling(a));var d=a.nextSiblings();return Object.isNumber(b)?d[b]:Selector.findElement(d,b,c)},select:function(){var a=$A(arguments),element=$(a.shift());return Selector.findChildElements(element,a)},adjacent:function(){var a=$A(arguments),element=$(a.shift());return Selector.findChildElements(element.parentNode,a).without(element)},identify:function(a){a=$(a);var b=a.readAttribute('id'),self=arguments.callee;if(b)return b;do{b='anonymous_element_'+self.counter++}while($(b));a.writeAttribute('id',b);return b},readAttribute:function(a,b){a=$(a);if(Prototype.Browser.IE){var t=Element._attributeTranslations.read;if(t.values[b])return t.values[b](a,b);if(t.names[b])b=t.names[b];if(b.include(':')){return(!a.attributes||!a.attributes[b])?null:a.attributes[b].value}}return a.getAttribute(b)},writeAttribute:function(a,b,c){a=$(a);var d={},t=Element._attributeTranslations.write;if(typeof b=='object')d=b;else d[b]=Object.isUndefined(c)?true:c;for(var e in d){b=t.names[e]||e;c=d[e];if(t.values[e])b=t.values[e](a,c);if(c===false||c===null)a.removeAttribute(b);else if(c===true)a.setAttribute(b,b);else a.setAttribute(b,c)}return a},getHeight:function(a){return $(a).getDimensions().height},getWidth:function(a){return $(a).getDimensions().width},classNames:function(a){return new Element.ClassNames(a)},hasClassName:function(a,b){if(!(a=$(a)))return;var c=a.className;return(c.length>0&&(c==b||new RegExp("(^|\\s)"+b+"(\\s|$)").test(c)))},addClassName:function(a,b){if(!(a=$(a)))return;if(!a.hasClassName(b))a.className+=(a.className?' ':'')+b;return a},removeClassName:function(a,b){if(!(a=$(a)))return;a.className=a.className.replace(new RegExp("(^|\\s+)"+b+"(\\s+|$)"),' ').strip();return a},toggleClassName:function(a,b){if(!(a=$(a)))return;return a[a.hasClassName(b)?'removeClassName':'addClassName'](b)},cleanWhitespace:function(a){a=$(a);var b=a.firstChild;while(b){var c=b.nextSibling;if(b.nodeType==3&&!/\S/.test(b.nodeValue))a.removeChild(b);b=c}return a},empty:function(a){return $(a).innerHTML.blank()},descendantOf:function(b,c){b=$(b),c=$(c);var d=c;if(b.compareDocumentPosition)return(b.compareDocumentPosition(c)&8)===8;if(b.sourceIndex&&!Prototype.Browser.Opera){var e=b.sourceIndex,a=c.sourceIndex,nextAncestor=c.nextSibling;if(!nextAncestor){do{c=c.parentNode}while(!(nextAncestor=c.nextSibling)&&c.parentNode)}if(nextAncestor&&nextAncestor.sourceIndex)return(e>a&&e<nextAncestor.sourceIndex)}while(b=b.parentNode)if(b==d)return true;return false},scrollTo:function(a){a=$(a);var b=a.cumulativeOffset();window.scrollTo(b[0],b[1]);return a},getStyle:function(a,b){a=$(a);b=b=='float'?'cssFloat':b.camelize();var c=a.style[b];if(!c){var d=document.defaultView.getComputedStyle(a,null);c=d?d[b]:null}if(b=='opacity')return c?parseFloat(c):1.0;return c=='auto'?null:c},getOpacity:function(a){return $(a).getStyle('opacity')},setStyle:function(a,b){a=$(a);var c=a.style,match;if(Object.isString(b)){a.style.cssText+=';'+b;return b.include('opacity')?a.setOpacity(b.match(/opacity:\s*(\d?\.?\d*)/)[1]):a}for(var d in b)if(d=='opacity')a.setOpacity(b[d]);else c[(d=='float'||d=='cssFloat')?(Object.isUndefined(c.styleFloat)?'cssFloat':'styleFloat'):d]=b[d];return a},setOpacity:function(a,b){a=$(a);a.style.opacity=(b==1||b==='')?'':(b<0.00001)?0:b;return a},getDimensions:function(a){a=$(a);var b=$(a).getStyle('display');if(b!='none'&&b!=null)return{width:a.offsetWidth,height:a.offsetHeight};var c=a.style;var d=c.visibility;var e=c.position;var f=c.display;c.visibility='hidden';c.position='absolute';c.display='block';var g=a.clientWidth;var h=a.clientHeight;c.display=f;c.position=e;c.visibility=d;return{width:g,height:h}},makePositioned:function(a){a=$(a);var b=Element.getStyle(a,'position');if(b=='static'||!b){a._madePositioned=true;a.style.position='relative';if(window.opera){a.style.top=0;a.style.left=0}}return a},undoPositioned:function(a){a=$(a);if(a._madePositioned){a._madePositioned=undefined;a.style.position=a.style.top=a.style.left=a.style.bottom=a.style.right=''}return a},makeClipping:function(a){a=$(a);if(a._overflow)return a;a._overflow=Element.getStyle(a,'overflow')||'auto';if(a._overflow!=='hidden')a.style.overflow='hidden';return a},undoClipping:function(a){a=$(a);if(!a._overflow)return a;a.style.overflow=a._overflow=='auto'?'':a._overflow;a._overflow=null;return a},cumulativeOffset:function(a){var b=0,valueL=0;do{b+=a.offsetTop||0;valueL+=a.offsetLeft||0;a=a.offsetParent}while(a);return Element._returnOffset(valueL,b)},positionedOffset:function(a){var b=0,valueL=0;do{b+=a.offsetTop||0;valueL+=a.offsetLeft||0;a=a.offsetParent;if(a){if(a.tagName=='BODY')break;var p=Element.getStyle(a,'position');if(p!=='static')break}}while(a);return Element._returnOffset(valueL,b)},absolutize:function(a){a=$(a);if(a.getStyle('position')=='absolute')return;var b=a.positionedOffset();var c=b[1];var d=b[0];var e=a.clientWidth;var f=a.clientHeight;a._originalLeft=d-parseFloat(a.style.left||0);a._originalTop=c-parseFloat(a.style.top||0);a._originalWidth=a.style.width;a._originalHeight=a.style.height;a.style.position='absolute';a.style.top=c+'px';a.style.left=d+'px';a.style.width=e+'px';a.style.height=f+'px';return a},relativize:function(a){a=$(a);if(a.getStyle('position')=='relative')return;a.style.position='relative';var b=parseFloat(a.style.top||0)-(a._originalTop||0);var c=parseFloat(a.style.left||0)-(a._originalLeft||0);a.style.top=b+'px';a.style.left=c+'px';a.style.height=a._originalHeight;a.style.width=a._originalWidth;return a},cumulativeScrollOffset:function(a){var b=0,valueL=0;do{b+=a.scrollTop||0;valueL+=a.scrollLeft||0;a=a.parentNode}while(a);return Element._returnOffset(valueL,b)},getOffsetParent:function(a){if(a.offsetParent)return $(a.offsetParent);if(a==document.body)return $(a);while((a=a.parentNode)&&a!=document.body)if(Element.getStyle(a,'position')!='static')return $(a);return $(document.body)},viewportOffset:function(a){var b=0,valueL=0;var c=a;do{b+=c.offsetTop||0;valueL+=c.offsetLeft||0;if(c.offsetParent==document.body&&Element.getStyle(c,'position')=='absolute')break}while(c=c.offsetParent);c=a;do{if(!Prototype.Browser.Opera||c.tagName=='BODY'){b-=c.scrollTop||0;valueL-=c.scrollLeft||0}}while(c=c.parentNode);return Element._returnOffset(valueL,b)},clonePosition:function(a,b){var c=Object.extend({setLeft:true,setTop:true,setWidth:true,setHeight:true,offsetTop:0,offsetLeft:0},arguments[2]||{});b=$(b);var p=b.viewportOffset();a=$(a);var d=[0,0];var e=null;if(Element.getStyle(a,'position')=='absolute'){e=a.getOffsetParent();d=e.viewportOffset()}if(e==document.body){d[0]-=document.body.offsetLeft;d[1]-=document.body.offsetTop}if(c.setLeft)a.style.left=(p[0]-d[0]+c.offsetLeft)+'px';if(c.setTop)a.style.top=(p[1]-d[1]+c.offsetTop)+'px';if(c.setWidth)a.style.width=b.offsetWidth+'px';if(c.setHeight)a.style.height=b.offsetHeight+'px';return a}};Element.Methods.identify.counter=1;Object.extend(Element.Methods,{getElementsBySelector:Element.Methods.select,childElements:Element.Methods.immediateDescendants});Element._attributeTranslations={write:{names:{className:'class',htmlFor:'for'},values:{}}};if(Prototype.Browser.Opera){Element.Methods.getStyle=Element.Methods.getStyle.wrap(function(d,e,f){switch(f){case'left':case'top':case'right':case'bottom':if(d(e,'position')==='static')return null;case'height':case'width':if(!Element.visible(e))return null;var g=parseInt(d(e,f),10);if(g!==e['offset'+f.capitalize()])return g+'px';var h;if(f==='height'){h=['border-top-width','padding-top','padding-bottom','border-bottom-width']}else{h=['border-left-width','padding-left','padding-right','border-right-width']}return h.inject(g,function(a,b){var c=d(e,b);return c===null?a:a-parseInt(c,10)})+'px';default:return d(e,f)}});Element.Methods.readAttribute=Element.Methods.readAttribute.wrap(function(a,b,c){if(c==='title')return b.title;return a(b,c)})}else if(Prototype.Browser.IE){Element.Methods.getOffsetParent=Element.Methods.getOffsetParent.wrap(function(a,b){b=$(b);var c=b.getStyle('position');if(c!=='static')return a(b);b.setStyle({position:'relative'});var d=a(b);b.setStyle({position:c});return d});$w('positionedOffset viewportOffset').each(function(f){Element.Methods[f]=Element.Methods[f].wrap(function(a,b){b=$(b);var c=b.getStyle('position');if(c!=='static')return a(b);var d=b.getOffsetParent();if(d&&d.getStyle('position')==='fixed')d.setStyle({zoom:1});b.setStyle({position:'relative'});var e=a(b);b.setStyle({position:c});return e})});Element.Methods.getStyle=function(a,b){a=$(a);b=(b=='float'||b=='cssFloat')?'styleFloat':b.camelize();var c=a.style[b];if(!c&&a.currentStyle)c=a.currentStyle[b];if(b=='opacity'){if(c=(a.getStyle('filter')||'').match(/alpha\(opacity=(.*)\)/))if(c[1])return parseFloat(c[1])/100;return 1.0}if(c=='auto'){if((b=='width'||b=='height')&&(a.getStyle('display')!='none'))return a['offset'+b.capitalize()]+'px';return null}return c};Element.Methods.setOpacity=function(b,c){function stripAlpha(a){return a.replace(/alpha\([^\)]*\)/gi,'')}b=$(b);var d=b.currentStyle;if((d&&!d.hasLayout)||(!d&&b.style.zoom=='normal'))b.style.zoom=1;var e=b.getStyle('filter'),style=b.style;if(c==1||c===''){(e=stripAlpha(e))?style.filter=e:style.removeAttribute('filter');return b}else if(c<0.00001)c=0;style.filter=stripAlpha(e)+'alpha(opacity='+(c*100)+')';return b};Element._attributeTranslations={read:{names:{'class':'className','for':'htmlFor'},values:{_getAttr:function(a,b){return a.getAttribute(b,2)},_getAttrNode:function(a,b){var c=a.getAttributeNode(b);return c?c.value:""},_getEv:function(a,b){b=a.getAttribute(b);return b?b.toString().slice(23,-2):null},_flag:function(a,b){return $(a).hasAttribute(b)?b:null},style:function(a){return a.style.cssText.toLowerCase()},title:function(a){return a.title}}}};Element._attributeTranslations.write={names:Object.extend({cellpadding:'cellPadding',cellspacing:'cellSpacing'},Element._attributeTranslations.read.names),values:{checked:function(a,b){a.checked=!!b},style:function(a,b){a.style.cssText=b?b:''}}};Element._attributeTranslations.has={};$w('colSpan rowSpan vAlign dateTime accessKey tabIndex '+'encType maxLength readOnly longDesc').each(function(a){Element._attributeTranslations.write.names[a.toLowerCase()]=a;Element._attributeTranslations.has[a.toLowerCase()]=a});(function(v){Object.extend(v,{href:v._getAttr,src:v._getAttr,type:v._getAttr,action:v._getAttrNode,disabled:v._flag,checked:v._flag,readonly:v._flag,multiple:v._flag,onload:v._getEv,onunload:v._getEv,onclick:v._getEv,ondblclick:v._getEv,onmousedown:v._getEv,onmouseup:v._getEv,onmouseover:v._getEv,onmousemove:v._getEv,onmouseout:v._getEv,onfocus:v._getEv,onblur:v._getEv,onkeypress:v._getEv,onkeydown:v._getEv,onkeyup:v._getEv,onsubmit:v._getEv,onreset:v._getEv,onselect:v._getEv,onchange:v._getEv})})(Element._attributeTranslations.read.values)}else if(Prototype.Browser.Gecko&&/rv:1\.8\.0/.test(navigator.userAgent)){Element.Methods.setOpacity=function(a,b){a=$(a);a.style.opacity=(b==1)?0.999999:(b==='')?'':(b<0.00001)?0:b;return a}}else if(Prototype.Browser.WebKit){Element.Methods.setOpacity=function(a,b){a=$(a);a.style.opacity=(b==1||b==='')?'':(b<0.00001)?0:b;if(b==1)if(a.tagName=='IMG'&&a.width){a.width++;a.width--}else try{var n=document.createTextNode(' ');a.appendChild(n);a.removeChild(n)}catch(e){}return a};Element.Methods.cumulativeOffset=function(a){var b=0,valueL=0;do{b+=a.offsetTop||0;valueL+=a.offsetLeft||0;if(a.offsetParent==document.body)if(Element.getStyle(a,'position')=='absolute')break;a=a.offsetParent}while(a);return Element._returnOffset(valueL,b)}}if(Prototype.Browser.IE||Prototype.Browser.Opera){Element.Methods.update=function(b,c){b=$(b);if(c&&c.toElement)c=c.toElement();if(Object.isElement(c))return b.update().insert(c);c=Object.toHTML(c);var d=b.tagName.toUpperCase();if(d in Element._insertionTranslations.tags){$A(b.childNodes).each(function(a){b.removeChild(a)});Element._getContentFromAnonymousElement(d,c.stripScripts()).each(function(a){b.appendChild(a)})}else b.innerHTML=c.stripScripts();c.evalScripts.bind(c).defer();return b}}if('outerHTML'in document.createElement('div')){Element.Methods.replace=function(b,c){b=$(b);if(c&&c.toElement)c=c.toElement();if(Object.isElement(c)){b.parentNode.replaceChild(c,b);return b}c=Object.toHTML(c);var d=b.parentNode,tagName=d.tagName.toUpperCase();if(Element._insertionTranslations.tags[tagName]){var e=b.next();var f=Element._getContentFromAnonymousElement(tagName,c.stripScripts());d.removeChild(b);if(e)f.each(function(a){d.insertBefore(a,e)});else f.each(function(a){d.appendChild(a)})}else b.outerHTML=c.stripScripts();c.evalScripts.bind(c).defer();return b}}Element._returnOffset=function(l,t){var a=[l,t];a.left=l;a.top=t;return a};Element._getContentFromAnonymousElement=function(a,b){var c=new Element('div'),t=Element._insertionTranslations.tags[a];if(t){c.innerHTML=t[0]+b+t[1];t[2].times(function(){c=c.firstChild})}else c.innerHTML=b;return $A(c.childNodes)};Element._insertionTranslations={before:function(a,b){a.parentNode.insertBefore(b,a)},top:function(a,b){a.insertBefore(b,a.firstChild)},bottom:function(a,b){a.appendChild(b)},after:function(a,b){a.parentNode.insertBefore(b,a.nextSibling)},tags:{TABLE:['<table>','</table>',1],TBODY:['<table><tbody>','</tbody></table>',2],TR:['<table><tbody><tr>','</tr></tbody></table>',3],TD:['<table><tbody><tr><td>','</td></tr></tbody></table>',4],SELECT:['<select>','</select>',1]}};(function(){Object.extend(this.tags,{THEAD:this.tags.TBODY,TFOOT:this.tags.TBODY,TH:this.tags.TD})}).call(Element._insertionTranslations);Element.Methods.Simulated={hasAttribute:function(a,b){b=Element._attributeTranslations.has[b]||b;var c=$(a).getAttributeNode(b);return c&&c.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.extend=(function(){if(Prototype.BrowserFeatures.SpecificElementExtensions)return Prototype.K;var c={},ByTag=Element.Methods.ByTag;var d=Object.extend(function(a){if(!a||a._extendedByPrototype||a.nodeType!=1||a==window)return a;var b=Object.clone(c),tagName=a.tagName,property,value;if(ByTag[tagName])Object.extend(b,ByTag[tagName]);for(property in b){value=b[property];if(Object.isFunction(value)&&!(property in a))a[property]=value.methodize()}a._extendedByPrototype=Prototype.emptyFunction;return a},{refresh:function(){if(!Prototype.BrowserFeatures.ElementExtensions){Object.extend(c,Element.Methods);Object.extend(c,Element.Methods.Simulated)}}});d.refresh();return d})();Element.hasAttribute=function(a,b){if(a.hasAttribute)return a.hasAttribute(b);return Element.Methods.Simulated.hasAttribute(a,b)};Element.addMethods=function(f){var F=Prototype.BrowserFeatures,T=Element.Methods.ByTag;if(!f){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 g=f;f=arguments[1]}if(!g)Object.extend(Element.Methods,f||{});else{if(Object.isArray(g))g.each(extend);else extend(g)}function extend(a){a=a.toUpperCase();if(!Element.Methods.ByTag[a])Element.Methods.ByTag[a]={};Object.extend(Element.Methods.ByTag[a],f)}function copy(a,b,c){c=c||false;for(var d in a){var e=a[d];if(!Object.isFunction(e))continue;if(!c||!(d in b))b[d]=e.methodize()}}function findDOMClass(a){var b;var c={"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(c[a])b='HTML'+c[a]+'Element';if(window[b])return window[b];b='HTML'+a+'Element';if(window[b])return window[b];b='HTML'+a.capitalize()+'Element';if(window[b])return window[b];window[b]={};window[b].prototype=document.createElement(a).__proto__;return window[b]}if(F.ElementExtensions){copy(Element.Methods,HTMLElement.prototype);copy(Element.Methods.Simulated,HTMLElement.prototype,true)}if(F.SpecificElementExtensions){for(var h in Element.Methods.ByTag){var i=findDOMClass(h);if(Object.isUndefined(i))continue;copy(T[h],i.prototype)}}Object.extend(Element,Element.Methods);delete Element.ByTag;if(Element.extend.refresh)Element.extend.refresh();Element.cache={}};document.viewport={getDimensions:function(){var a={};var B=Prototype.Browser;$w('width height').each(function(d){var D=d.capitalize();a[d]=(B.WebKit&&!document.evaluate)?self['inner'+D]:(B.Opera)?document.body['client'+D]:document.documentElement['client'+D]});return a},getWidth:function(){return this.getDimensions().width},getHeight:function(){return this.getDimensions().height},getScrollOffsets:function(){return Element._returnOffset(window.pageXOffset||document.documentElement.scrollLeft||document.body.scrollLeft,window.pageYOffset||document.documentElement.scrollTop||document.body.scrollTop)}};var Selector=Class.create({initialize:function(a){this.expression=a.strip();this.compileMatcher()},shouldUseXPath:function(){if(!Prototype.BrowserFeatures.XPath)return false;var e=this.expression;if(Prototype.Browser.WebKit&&(e.include("-of-type")||e.include(":empty")))return false;if((/(\[[\w-]*?:|:checked)/).test(this.expression))return false;return true},compileMatcher:function(){if(this.shouldUseXPath())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(Object.isFunction(c[i])?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(Object.isFunction(x[i])?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(a){a=a||document;if(this.xpath)return document._getElementsByXPath(this.xpath,a);return this.matcher(a)},match:function(a){this.tokens=[];var e=this.expression,ps=Selector.patterns,as=Selector.assertions;var b,p,m;while(e&&b!==e&&(/\S/).test(e)){b=e;for(var i in ps){p=ps[i];if(m=e.match(p)){if(as[i]){this.tokens.push([i,Object.clone(m)]);e=e.replace(m[0],'')}else{return this.findElements(document).include(a)}}}}var c=true,name,matches;for(var i=0,token;token=this.tokens[i];i++){name=token[0],matches=token[1];if(!Selector.assertions[name](a,matches)){c=false;break}}return c},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:function(m){m[1]=m[1].toLowerCase();return new Template("[@#{1}]").evaluate(m)},attr:function(m){m[1]=m[1].toLowerCase();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(Object.isFunction(h))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,v;var a=[];while(e&&le!=e&&(/\S/).test(e)){le=e;for(var i in p){if(m=e.match(p[i])){v=Object.isFunction(x[i])?x[i](m):new Template(x[i]).evaluate(m);a.push("("+v.substring(1,v.length-1)+")");e=e.replace(m[0],'');break}}}return"[not("+a.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(c,m){var d,formula=m[6],predicate;if(formula=='even')formula='2n+0';if(formula=='odd')formula='2n+1';if(d=formula.match(/^(\d+)$/))return'['+c+"= "+d[1]+']';if(d=formula.match(/^(-?\d*)?n(([+-])(\d+))?/)){if(d[1]=="-")d[1]=-1;var a=d[1]?Number(d[1]):1;var b=d[2]?Number(d[2]):0;predicate="[((#{fragment} - #{b}) mod #{a} = 0) and "+"((#{fragment} - #{b}) div #{a} >= 0)]";return new Template(predicate).evaluate({fragment:c,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); c = false;',attr:function(m){m[3]=(m[5]||m[6]);return new Template('n = h.attr(n, r, "#{1}", "#{3}", "#{2}", c); 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]*?)\4|([^'"][^\]]*?)))?\]/},assertions:{tagName:function(a,b){return b[1].toUpperCase()==a.tagName.toUpperCase()},className:function(a,b){return Element.hasClassName(a,b[1])},id:function(a,b){return a.id===b[1]},attrPresence:function(a,b){return Element.hasAttribute(a,b[1])},attr:function(a,b){var c=Element.readAttribute(a,b[1]);return c&&Selector.operators[b[2]](c,b[5]||b[6])}},handlers:{concat:function(a,b){for(var i=0,node;node=b[i];i++)a.push(node);return a},mark:function(a){var b=Prototype.emptyFunction;for(var i=0,node;node=a[i];i++)node._countedByPrototype=b;return a},unmark:function(a){for(var i=0,node;node=a[i];i++)node._countedByPrototype=undefined;return a},index:function(a,b,c){a._countedByPrototype=Prototype.emptyFunction;if(b){for(var d=a.childNodes,i=d.length-1,j=1;i>=0;i--){var e=d[i];if(e.nodeType==1&&(!c||e._countedByPrototype))e.nodeIndex=j++}}else{for(var i=0,j=1,d=a.childNodes;e=d[i];i++)if(e.nodeType==1&&(!c||e._countedByPrototype))e.nodeIndex=j++}},unique:function(a){if(a.length==0)return a;var b=[],n;for(var i=0,l=a.length;i<l;i++)if(!(n=a[i])._countedByPrototype){n._countedByPrototype=Prototype.emptyFunction;b.push(Element.extend(n))}return Selector.handlers.unmark(b)},descendant:function(a){var h=Selector.handlers;for(var i=0,results=[],node;node=a[i];i++)h.concat(results,node.getElementsByTagName('*'));return results},child:function(a){var h=Selector.handlers;for(var i=0,results=[],node;node=a[i];i++){for(var j=0,child;child=node.childNodes[j];j++)if(child.nodeType==1&&child.tagName!='!')results.push(child)}return results},adjacent:function(a){for(var i=0,results=[],node;node=a[i];i++){var b=this.nextElementSibling(node);if(b)results.push(b)}return results},laterSibling:function(a){var h=Selector.handlers;for(var i=0,results=[],node;node=a[i];i++)h.concat(results,Element.nextSiblings(node));return results},nextElementSibling:function(a){while(a=a.nextSibling)if(a.nodeType==1)return a;return null},previousElementSibling:function(a){while(a=a.previousSibling)if(a.nodeType==1)return a;return null},tagName:function(a,b,c,d){var e=c.toUpperCase();var f=[],h=Selector.handlers;if(a){if(d){if(d=="descendant"){for(var i=0,node;node=a[i];i++)h.concat(f,node.getElementsByTagName(c));return f}else a=this[d](a);if(c=="*")return a}for(var i=0,node;node=a[i];i++)if(node.tagName.toUpperCase()===e)f.push(node);return f}else return b.getElementsByTagName(c)},id:function(a,b,c,d){var e=$(c),h=Selector.handlers;if(!e)return[];if(!a&&b==document)return[e];if(a){if(d){if(d=='child'){for(var i=0,node;node=a[i];i++)if(e.parentNode==node)return[e]}else if(d=='descendant'){for(var i=0,node;node=a[i];i++)if(Element.descendantOf(e,node))return[e]}else if(d=='adjacent'){for(var i=0,node;node=a[i];i++)if(Selector.handlers.previousElementSibling(e)==node)return[e]}else a=h[d](a)}for(var i=0,node;node=a[i];i++)if(node==e)return[e];return[]}return(e&&Element.descendantOf(e,b))?[e]:[]},className:function(a,b,c,d){if(a&&d)a=this[d](a);return Selector.handlers.byClassName(a,b,c)},byClassName:function(a,b,c){if(!a)a=Selector.handlers.descendant([b]);var d=' '+c+' ';for(var i=0,results=[],node,nodeClassName;node=a[i];i++){nodeClassName=node.className;if(nodeClassName.length==0)continue;if(nodeClassName==c||(' '+nodeClassName+' ').include(d))results.push(node)}return results},attrPresence:function(a,b,c,d){if(!a)a=b.getElementsByTagName("*");if(a&&d)a=this[d](a);var e=[];for(var i=0,node;node=a[i];i++)if(Element.hasAttribute(node,c))e.push(node);return e},attr:function(a,b,c,d,e,f){if(!a)a=b.getElementsByTagName("*");if(a&&f)a=this[f](a);var g=Selector.operators[e],results=[];for(var i=0,node;node=a[i];i++){var h=Element.readAttribute(node,c);if(h===null)continue;if(g(h,d))results.push(node)}return results},pseudo:function(a,b,c,d,e){if(a&&e)a=this[e](a);if(!a)a=d.getElementsByTagName("*");return Selector.pseudos[b](a,c,d)}},pseudos:{'first-child':function(a,b,c){for(var i=0,results=[],node;node=a[i];i++){if(Selector.handlers.previousElementSibling(node))continue;results.push(node)}return results},'last-child':function(a,b,c){for(var i=0,results=[],node;node=a[i];i++){if(Selector.handlers.nextElementSibling(node))continue;results.push(node)}return results},'only-child':function(a,b,c){var h=Selector.handlers;for(var i=0,results=[],node;node=a[i];i++)if(!h.previousElementSibling(node)&&!h.nextElementSibling(node))results.push(node);return results},'nth-child':function(a,b,c){return Selector.pseudos.nth(a,b,c)},'nth-last-child':function(a,b,c){return Selector.pseudos.nth(a,b,c,true)},'nth-of-type':function(a,b,c){return Selector.pseudos.nth(a,b,c,false,true)},'nth-last-of-type':function(a,b,c){return Selector.pseudos.nth(a,b,c,true,true)},'first-of-type':function(a,b,c){return Selector.pseudos.nth(a,"1",c,false,true)},'last-of-type':function(a,b,c){return Selector.pseudos.nth(a,"1",c,true,true)},'only-of-type':function(a,b,c){var p=Selector.pseudos;return p['last-of-type'](p['first-of-type'](a,b,c),b,c)},getIndices:function(a,b,d){if(a==0)return b>0?[b]:[];return $R(1,d).inject([],function(c,i){if(0==(i-b)%a&&(i-b)/a>=0)c.push(i);return c})},nth:function(c,d,e,f,g){if(c.length==0)return[];if(d=='even')d='2n+0';if(d=='odd')d='2n+1';var h=Selector.handlers,results=[],indexed=[],m;h.mark(c);for(var i=0,node;node=c[i];i++){if(!node.parentNode._countedByPrototype){h.index(node.parentNode,f,g);indexed.push(node.parentNode)}}if(d.match(/^\d+$/)){d=Number(d);for(var i=0,node;node=c[i];i++)if(node.nodeIndex==d)results.push(node)}else if(m=d.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 k=Selector.pseudos.getIndices(a,b,c.length);for(var i=0,node,l=k.length;node=c[i];i++){for(var j=0;j<l;j++)if(node.nodeIndex==k[j])results.push(node)}}h.unmark(c);h.unmark(indexed);return results},'empty':function(a,b,c){for(var i=0,results=[],node;node=a[i];i++){if(node.tagName=='!'||(node.firstChild&&!node.innerHTML.match(/^\s*$/)))continue;results.push(node)}return results},'not':function(a,b,c){var h=Selector.handlers,selectorType,m;var d=new Selector(b).findElements(c);h.mark(d);for(var i=0,results=[],node;node=a[i];i++)if(!node._countedByPrototype)results.push(node);h.unmark(d);return results},'enabled':function(a,b,c){for(var i=0,results=[],node;node=a[i];i++)if(!node.disabled)results.push(node);return results},'disabled':function(a,b,c){for(var i=0,results=[],node;node=a[i];i++)if(node.disabled)results.push(node);return results},'checked':function(a,b,c){for(var i=0,results=[],node;node=a[i];i++)if(node.checked)results.push(node);return results}},operators:{'=':function(a,v){return a==v},'!=':function(a,v){return a!=v},'^=':function(a,v){return a.startsWith(v)},'$=':function(a,v){return a.endsWith(v)},'*=':function(a,v){return a.include(v)},'~=':function(a,v){return(' '+a+' ').include(' '+v+' ')},'|=':function(a,v){return('-'+a.toUpperCase()+'-').include('-'+v.toUpperCase()+'-')}},split:function(a){var b=[];a.scan(/(([\w#:.~>+()\s-]+|\*|\[.*?\])+)\s*(,|$)/,function(m){b.push(m[1].strip())});return b},matchElements:function(a,b){var c=$$(b),h=Selector.handlers;h.mark(c);for(var i=0,results=[],element;element=a[i];i++)if(element._countedByPrototype)results.push(element);h.unmark(c);return results},findElement:function(a,b,c){if(Object.isNumber(b)){c=b;b=false}return Selector.matchElements(a,b||'*')[c||0]},findChildElements:function(a,b){b=Selector.split(b.join(','));var c=[],h=Selector.handlers;for(var i=0,l=b.length,selector;i<l;i++){selector=new Selector(b[i].strip());h.concat(c,selector.findElements(a))}return(l>1)?h.unique(c):c}});if(Prototype.Browser.IE){Object.extend(Selector.handlers,{concat:function(a,b){for(var i=0,node;node=b[i];i++)if(node.tagName!=="!")a.push(node);return a},unmark:function(a){for(var i=0,node;node=a[i];i++)node.removeAttribute('_countedByPrototype');return a}})}function $$(){return Selector.findChildElements(document,$A(arguments))}var Form={reset:function(a){$(a).reset();return a},serializeElements:function(c,d){if(typeof d!='object')d={hash:!!d};else if(Object.isUndefined(d.hash))d.hash=true;var e,value,submitted=false,submit=d.submit;var f=c.inject({},function(a,b){if(!b.disabled&&b.name){e=b.name;value=$(b).getValue();if(value!=null&&(b.type!='submit'||(!submitted&&submit!==false&&(!submit||e==submit)&&(submitted=true)))){if(e in a){if(!Object.isArray(a[e]))a[e]=[a[e]];a[e].push(value)}else a[e]=value}}return a});return d.hash?f:Object.toQueryString(f)}};Form.Methods={serialize:function(a,b){return Form.serializeElements(Form.getElements(a),b)},getElements:function(c){return $A($(c).getElementsByTagName('*')).inject([],function(a,b){if(Form.Element.Serializers[b.tagName.toLowerCase()])a.push(Element.extend(b));return a})},getInputs:function(a,b,c){a=$(a);var d=a.getElementsByTagName('input');if(!b&&!c)return $A(d).map(Element.extend);for(var i=0,matchingInputs=[],length=d.length;i<length;i++){var e=d[i];if((b&&e.type!=b)||(c&&e.name!=c))continue;matchingInputs.push(Element.extend(e))}return matchingInputs},disable:function(a){a=$(a);Form.getElements(a).invoke('disable');return a},enable:function(a){a=$(a);Form.getElements(a).invoke('enable');return a},findFirstElement:function(b){var c=$(b).getElements().findAll(function(a){return'hidden'!=a.type&&!a.disabled});var d=c.findAll(function(a){return a.hasAttribute('tabIndex')&&a.tabIndex>=0}).sortBy(function(a){return a.tabIndex}).first();return d?d:c.find(function(a){return['input','select','textarea'].include(a.tagName.toLowerCase())})},focusFirstElement:function(a){a=$(a);a.findFirstElement().activate();return a},request:function(a,b){a=$(a),b=Object.clone(b||{});var c=b.parameters,action=a.readAttribute('action')||'';if(action.blank())action=window.location.href;b.parameters=a.serialize(true);if(c){if(Object.isString(c))c=c.toQueryParams();Object.extend(b.parameters,c)}if(a.hasAttribute('method')&&!b.method)b.method=a.method;return new Ajax.Request(action,b)}};Form.Element={focus:function(a){$(a).focus();return a},select:function(a){$(a).select();return a}};Form.Element.Methods={serialize:function(a){a=$(a);if(!a.disabled&&a.name){var b=a.getValue();if(b!=undefined){var c={};c[a.name]=b;return Object.toQueryString(c)}}return''},getValue:function(a){a=$(a);var b=a.tagName.toLowerCase();return Form.Element.Serializers[b](a)},setValue:function(a,b){a=$(a);var c=a.tagName.toLowerCase();Form.Element.Serializers[c](a,b);return a},clear:function(a){$(a).value='';return a},present:function(a){return $(a).value!=''},activate:function(a){a=$(a);try{a.focus();if(a.select&&(a.tagName.toLowerCase()!='input'||!['button','reset','submit'].include(a.type)))a.select()}catch(e){}return a},disable:function(a){a=$(a);a.blur();a.disabled=true;return a},enable:function(a){a=$(a);a.disabled=false;return a}};var Field=Form.Element;var $F=Form.Element.Methods.getValue;Form.Element.Serializers={input:function(a,b){switch(a.type.toLowerCase()){case'checkbox':case'radio':return Form.Element.Serializers.inputSelector(a,b);default:return Form.Element.Serializers.textarea(a,b)}},inputSelector:function(a,b){if(Object.isUndefined(b))return a.checked?a.value:null;else a.checked=!!b},textarea:function(a,b){if(Object.isUndefined(b))return a.value;else a.value=b},select:function(a,b){if(Object.isUndefined(b))return this[a.type=='select-one'?'selectOne':'selectMany'](a);else{var c,value,single=!Object.isArray(b);for(var i=0,length=a.length;i<length;i++){c=a.options[i];value=this.optionValue(c);if(single){if(value==b){c.selected=true;return}}else c.selected=b.include(value)}}},selectOne:function(a){var b=a.selectedIndex;return b>=0?this.optionValue(a.options[b]):null},selectMany:function(a){var b,length=a.length;if(!length)return null;for(var i=0,b=[];i<length;i++){var c=a.options[i];if(c.selected)b.push(this.optionValue(c))}return b},optionValue:function(a){return Element.extend(a).hasAttribute('value')?a.value:a.text}};Abstract.TimedObserver=Class.create(PeriodicalExecuter,{initialize:function($super,b,c,d){$super(d,c);this.element=$(b);this.lastValue=this.getValue()},execute:function(){var a=this.getValue();if(Object.isString(this.lastValue)&&Object.isString(a)?this.lastValue!=a:String(this.lastValue)!=String(a)){this.callback(this.element,a);this.lastValue=a}}});Form.Element.Observer=Class.create(Abstract.TimedObserver,{getValue:function(){return Form.Element.getValue(this.element)}});Form.Observer=Class.create(Abstract.TimedObserver,{getValue:function(){return Form.serialize(this.element)}});Abstract.EventObserver=Class.create({initialize:function(a,b){this.element=$(a);this.callback=b;this.lastValue=this.getValue();if(this.element.tagName.toLowerCase()=='form')this.registerFormCallbacks();else this.registerCallback(this.element)},onElementEvent:function(){var a=this.getValue();if(this.lastValue!=a){this.callback(this.element,a);this.lastValue=a}},registerFormCallbacks:function(){Form.getElements(this.element).each(this.registerCallback,this)},registerCallback:function(a){if(a.type){switch(a.type.toLowerCase()){case'checkbox':case'radio':Event.observe(a,'click',this.onElementEvent.bind(this));break;default:Event.observe(a,'change',this.onElementEvent.bind(this));break}}}});Form.Element.EventObserver=Class.create(Abstract.EventObserver,{getValue:function(){return Form.Element.getValue(this.element)}});Form.EventObserver=Class.create(Abstract.EventObserver,{getValue:function(){return Form.serialize(this.element)}});if(!window.Event)var Event={};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,KEY_INSERT:45,cache:{},relatedTarget:function(a){var b;switch(a.type){case'mouseover':b=a.fromElement;break;case'mouseout':b=a.toElement;break;default:return null}return Element.extend(b)}});Event.Methods=(function(){var e;if(Prototype.Browser.IE){var f={0:1,1:4,2:2};e=function(a,b){return a.button==f[b]}}else if(Prototype.Browser.WebKit){e=function(a,b){switch(b){case 0:return a.which==1&&!a.metaKey;case 1:return a.which==1&&a.metaKey;default:return false}}}else{e=function(a,b){return a.which?(a.which===b+1):(a.button===b)}}return{isLeftClick:function(a){return e(a,0)},isMiddleClick:function(a){return e(a,1)},isRightClick:function(a){return e(a,2)},element:function(a){var b=Event.extend(a).target;return Element.extend(b.nodeType==Node.TEXT_NODE?b.parentNode:b)},findElement:function(a,b){var c=Event.element(a);if(!b)return c;var d=[c].concat(c.ancestors());return Selector.findElement(d,b,0)},pointer:function(a){return{x:a.pageX||(a.clientX+(document.documentElement.scrollLeft||document.body.scrollLeft)),y:a.pageY||(a.clientY+(document.documentElement.scrollTop||document.body.scrollTop))}},pointerX:function(a){return Event.pointer(a).x},pointerY:function(a){return Event.pointer(a).y},stop:function(a){Event.extend(a);a.preventDefault();a.stopPropagation();a.stopped=true}}})();Event.extend=(function(){var c=Object.keys(Event.Methods).inject({},function(m,a){m[a]=Event.Methods[a].methodize();return m});if(Prototype.Browser.IE){Object.extend(c,{stopPropagation:function(){this.cancelBubble=true},preventDefault:function(){this.returnValue=false},inspect:function(){return"[object Event]"}});return function(a){if(!a)return false;if(a._extendedByPrototype)return a;a._extendedByPrototype=Prototype.emptyFunction;var b=Event.pointer(a);Object.extend(a,{target:a.srcElement,relatedTarget:Event.relatedTarget(a),pageX:b.x,pageY:b.y});return Object.extend(a,c)}}else{Event.prototype=Event.prototype||document.createEvent("HTMLEvents").__proto__;Object.extend(Event.prototype,c);return Prototype.K}})();Object.extend(Event,(function(){var h=Event.cache;function getEventID(a){if(a._prototypeEventID)return a._prototypeEventID[0];arguments.callee.id=arguments.callee.id||1;return a._prototypeEventID=[++arguments.callee.id]}function getDOMEventName(a){if(a&&a.include(':'))return"dataavailable";return a}function getCacheForID(a){return h[a]=h[a]||{}}function getWrappersForEventName(a,b){var c=getCacheForID(a);return c[b]=c[b]||[]}function createWrapper(b,d,e){var f=getEventID(b);var c=getWrappersForEventName(f,d);if(c.pluck("handler").include(e))return false;var g=function(a){if(!Event||!Event.extend||(a.eventName&&a.eventName!=d))return false;Event.extend(a);e.call(b,a)};g.handler=e;c.push(g);return g}function findWrapper(b,d,e){var c=getWrappersForEventName(b,d);return c.find(function(a){return a.handler==e})}function destroyWrapper(a,b,d){var c=getCacheForID(a);if(!c[b])return false;c[b]=c[b].without(findWrapper(a,b,d))}function destroyCache(){for(var a in h)for(var b in h[a])h[a][b]=null}if(window.attachEvent){window.attachEvent("onunload",destroyCache)}return{observe:function(a,b,c){a=$(a);var d=getDOMEventName(b);var e=createWrapper(a,b,c);if(!e)return a;if(a.addEventListener){a.addEventListener(d,e,false)}else{a.attachEvent("on"+d,e)}return a},stopObserving:function(b,c,d){b=$(b);var e=getEventID(b),name=getDOMEventName(c);if(!d&&c){getWrappersForEventName(e,c).each(function(a){b.stopObserving(c,a.handler)});return b}else if(!c){Object.keys(getCacheForID(e)).each(function(a){b.stopObserving(a)});return b}var f=findWrapper(e,c,d);if(!f)return b;if(b.removeEventListener){b.removeEventListener(name,f,false)}else{b.detachEvent("on"+name,f)}destroyWrapper(e,c,d);return b},fire:function(a,b,c){a=$(a);if(a==document&&document.createEvent&&!a.dispatchEvent)a=document.documentElement;var d;if(document.createEvent){d=document.createEvent("HTMLEvents");d.initEvent("dataavailable",true,true)}else{d=document.createEventObject();d.eventType="ondataavailable"}d.eventName=b;d.memo=c||{};if(document.createEvent){a.dispatchEvent(d)}else{a.fireEvent(d.eventType,d)}return Event.extend(d)}}})());Object.extend(Event,Event.Methods);Element.addMethods({fire:Event.fire,observe:Event.observe,stopObserving:Event.stopObserving});Object.extend(document,{fire:Element.Methods.fire.methodize(),observe:Element.Methods.observe.methodize(),stopObserving:Element.Methods.stopObserving.methodize(),loaded:false});(function(){var a;function fireContentLoadedEvent(){if(document.loaded)return;if(a)window.clearInterval(a);document.fire("dom:loaded");document.loaded=true}if(document.addEventListener){if(Prototype.Browser.WebKit){a=window.setInterval(function(){if(/loaded|complete/.test(document.readyState))fireContentLoadedEvent()},0);Event.observe(window,"load",fireContentLoadedEvent)}else{document.addEventListener("DOMContentLoaded",fireContentLoadedEvent,false)}}else{document.write("<script id=__onDOMContentLoaded defer src=//:><\/script>");$("__onDOMContentLoaded").onreadystatechange=function(){if(this.readyState=="complete"){this.onreadystatechange=null;fireContentLoadedEvent()}}}})();Hash.toQueryString=Object.toQueryString;var Toggle={display:Element.toggle};Element.Methods.childOf=Element.Methods.descendantOf;var Insertion={Before:function(a,b){return Element.insert(a,{before:b})},Top:function(a,b){return Element.insert(a,{top:b})},Bottom:function(a,b){return Element.insert(a,{bottom:b})},After:function(a,b){return Element.insert(a,{after:b})}};var $continue=new Error('"throw $continue" is deprecated, use "return" instead');var Position={includeScrollOffsets:false,prepare:function(){this.deltaX=window.pageXOffset||document.documentElement.scrollLeft||document.body.scrollLeft||0;this.deltaY=window.pageYOffset||document.documentElement.scrollTop||document.body.scrollTop||0},within:function(a,x,y){if(this.includeScrollOffsets)return this.withinIncludingScrolloffsets(a,x,y);this.xcomp=x;this.ycomp=y;this.offset=Element.cumulativeOffset(a);return(y>=this.offset[1]&&y<this.offset[1]+a.offsetHeight&&x>=this.offset[0]&&x<this.offset[0]+a.offsetWidth)},withinIncludingScrolloffsets:function(a,x,y){var b=Element.cumulativeScrollOffset(a);this.xcomp=x+b[0]-this.deltaX;this.ycomp=y+b[1]-this.deltaY;this.offset=Element.cumulativeOffset(a);return(this.ycomp>=this.offset[1]&&this.ycomp<this.offset[1]+a.offsetHeight&&this.xcomp>=this.offset[0]&&this.xcomp<this.offset[0]+a.offsetWidth)},overlap:function(a,b){if(!a)return 0;if(a=='vertical')return((this.offset[1]+b.offsetHeight)-this.ycomp)/b.offsetHeight;if(a=='horizontal')return((this.offset[0]+b.offsetWidth)-this.xcomp)/b.offsetWidth},cumulativeOffset:Element.Methods.cumulativeOffset,positionedOffset:Element.Methods.positionedOffset,absolutize:function(a){Position.prepare();return Element.absolutize(a)},relativize:function(a){Position.prepare();return Element.relativize(a)},realOffset:Element.Methods.cumulativeScrollOffset,offsetParent:Element.Methods.getOffsetParent,page:Element.Methods.viewportOffset,clone:function(a,b,c){c=c||{};return Element.clonePosition(b,a,c)}};if(!document.getElementsByClassName)document.getElementsByClassName=function(f){function iter(a){return a.blank()?null:"[contains(concat(' ', @class, ' '), ' "+a+" ')]"}f.getElementsByClassName=Prototype.BrowserFeatures.XPath?function(a,b){b=b.toString().strip();var c=/\s/.test(b)?$w(b).map(iter).join(''):iter(b);return c?document._getElementsByXPath('.//*'+c,a):[]}:function(b,c){c=c.toString().strip();var d=[],classNames=(/\s/.test(c)?$w(c):null);if(!classNames&&!c)return d;var e=$(b).getElementsByTagName('*');c=' '+c+' ';for(var i=0,child,cn;child=e[i];i++){if(child.className&&(cn=' '+child.className+' ')&&(cn.include(c)||(classNames&&classNames.all(function(a){return!a.toString().blank()&&cn.include(' '+a+' ')}))))d.push(Element.extend(child))}return d};return function(a,b){return $(b||document.body).getElementsByClassName(a)}}(Element.Methods);Element.ClassNames=Class.create();Element.ClassNames.prototype={initialize:function(a){this.element=$(a)},_each:function(b){this.element.className.split(/\s+/).select(function(a){return a.length>0})._each(b)},set:function(a){this.element.className=a},add:function(a){if(this.include(a))return;this.set($A(this).concat(a).join(' '))},remove:function(a){if(!this.include(a))return;this.set($A(this).without(a).join(' '))},toString:function(){return $A(this).join(' ')}};Object.extend(Element.ClassNames.prototype,Enumerable);Element.addMethods();
//scriptaculous.js
var Scriptaculous={Version:'1.8.1',require:function(a){document.write('<script type="text/javascript" src="'+a+'"><\/script>')},REQUIRED_PROTOTYPE:'1.6.0',load:function(){function convertVersionString(a){var r=a.split('.');return parseInt(r[0])*100000+parseInt(r[1])*1000+parseInt(r[2])}if((typeof Prototype=='undefined')||(typeof Element=='undefined')||(typeof Element.Methods=='undefined')||(convertVersionString(Prototype.Version)<convertVersionString(Scriptaculous.REQUIRED_PROTOTYPE)))throw("script.aculo.us requires the Prototype JavaScript framework >= "+Scriptaculous.REQUIRED_PROTOTYPE);var d=/(proto|scripta)culous[a-z0-9._-]*\.js(\?.*)?$/;$A(document.getElementsByTagName("script")).findAll(function(s){return(s.src&&s.src.match(d))}).each(function(s){var b=s.src.replace(d,'');var c=(s.src.match(/\?.*load=([a-z,]*)/)||[,''])[1];c.split(',').without('').each(function(a){Scriptaculous.require(b+a+'.js')})})}};
//builder.js
var Builder={NODEMAP:{AREA:'map',CAPTION:'table',COL:'table',COLGROUP:'table',LEGEND:'fieldset',OPTGROUP:'select',OPTION:'select',PARAM:'object',TBODY:'table',TD:'table',TFOOT:'table',TH:'table',THEAD:'table',TR:'table'},node:function(a){a=a.toUpperCase();var b=this.NODEMAP[a]||'div';var c=document.createElement(b);try{c.innerHTML="<"+a+"></"+a+">"}catch(e){}var d=c.firstChild||null;if(d&&(d.tagName.toUpperCase()!=a))d=d.getElementsByTagName(a)[0];if(!d)d=document.createElement(a);if(!d)return;if(arguments[1])if(this._isStringOrNumber(arguments[1])||(arguments[1]instanceof Array)||arguments[1].tagName){this._children(d,arguments[1])}else{var f=this._attributes(arguments[1]);if(f.length){try{c.innerHTML="<"+a+" "+f+"></"+a+">"}catch(e){}d=c.firstChild||null;if(!d){d=document.createElement(a);for(attr in arguments[1])d[attr=='class'?'className':attr]=arguments[1][attr]}if(d.tagName.toUpperCase()!=a)d=c.getElementsByTagName(a)[0]}}if(arguments[2])this._children(d,arguments[2]);return d},_text:function(a){return document.createTextNode(a)},ATTR_MAP:{'className':'class','htmlFor':'for'},_attributes:function(a){var b=[];for(attribute in a)b.push((attribute in this.ATTR_MAP?this.ATTR_MAP[attribute]:attribute)+'="'+a[attribute].toString().escapeHTML().gsub(/"/,'&quot;')+'"');return b.join(" ")},_children:function(a,b){if(b.tagName){a.appendChild(b);return}if(typeof b=='object'){b.flatten().each(function(e){if(typeof e=='object')a.appendChild(e);else if(Builder._isStringOrNumber(e))a.appendChild(Builder._text(e))})}else if(Builder._isStringOrNumber(b))a.appendChild(Builder._text(b))},_isStringOrNumber:function(a){return(typeof a=='string'||typeof a=='number')},build:function(a){var b=this.node('div');$(b).update(a.strip());return b.down()},dump:function(b){if(typeof b!='object'&&typeof b!='function')b=window;var c=("A ABBR ACRONYM ADDRESS APPLET AREA B BASE BASEFONT BDO BIG BLOCKQUOTE BODY "+"BR BUTTON CAPTION CENTER CITE CODE COL COLGROUP DD DEL DFN DIR DIV DL DT EM FIELDSET "+"FONT FORM FRAME FRAMESET H1 H2 H3 H4 H5 H6 HEAD HR HTML I IFRAME IMG INPUT INS ISINDEX "+"KBD LABEL LEGEND LI LINK MAP MENU META NOFRAMES NOSCRIPT OBJECT OL OPTGROUP OPTION P "+"PARAM PRE Q S SAMP SCRIPT SELECT SMALL SPAN STRIKE STRONG STYLE SUB SUP TABLE TBODY TD "+"TEXTAREA TFOOT TH THEAD TITLE TR TT U UL VAR").split(/\s+/);c.each(function(a){b[a]=function(){return Builder.node.apply(Builder,[a].concat($A(arguments)))}})}};
//effects.js
String.prototype.parseColor=function(){var a='#';if(this.slice(0,4)=='rgb('){var b=this.slice(4,this.length-1).split(',');var i=0;do{a+=parseInt(b[i]).toColorPart()}while(++i<3)}else{if(this.slice(0,1)=='#'){if(this.length==4)for(var i=1;i<4;i++)a+=(this.charAt(i)+this.charAt(i)).toLowerCase();if(this.length==7)a=this.toLowerCase()}}return(a.length==7?a:(arguments[0]||this))};Element.collectTextNodes=function(b){return $A($(b).childNodes).collect(function(a){return(a.nodeType==3?a.nodeValue:(a.hasChildNodes()?Element.collectTextNodes(a):''))}).flatten().join('')};Element.collectTextNodesIgnoreClass=function(b,c){return $A($(b).childNodes).collect(function(a){return(a.nodeType==3?a.nodeValue:((a.hasChildNodes()&&!Element.hasClassName(a,c))?Element.collectTextNodesIgnoreClass(a,c):''))}).flatten().join('')};Element.setContentZoom=function(a,b){a=$(a);a.setStyle({fontSize:(b/100)+'em'});if(Prototype.Browser.WebKit)window.scrollBy(0,0);return a};Element.getInlineOpacity=function(a){return $(a).style.opacity||''};Element.forceRerendering=function(a){try{a=$(a);var n=document.createTextNode(' ');a.appendChild(n);a.removeChild(n)}catch(e){}};var Effect={_elementDoesNotExistError:{name:'ElementDoesNotExistError',message:'The specified DOM element does not exist, but is required for this effect to operate'},Transitions:{linear:Prototype.K,sinoidal:function(a){return(-Math.cos(a*Math.PI)/2)+0.5},reverse:function(a){return 1-a},flicker:function(a){var a=((-Math.cos(a*Math.PI)/4)+0.75)+Math.random()/4;return a>1?1:a},wobble:function(a){return(-Math.cos(a*Math.PI*(9*a))/2)+0.5},pulse:function(a,b){b=b||5;return(((a%(1/b))*b).round()==0?((a*b*2)-(a*b*2).floor()):1-((a*b*2)-(a*b*2).floor()))},spring:function(a){return 1-(Math.cos(a*4.5*Math.PI)*Math.exp(-a*6))},none:function(a){return 0},full:function(a){return 1}},DefaultOptions:{duration:1.0,fps:100,sync:false,from:0.0,to:1.0,delay:0.0,queue:'parallel'},tagifyText:function(c){var d='position:relative';if(Prototype.Browser.IE)d+=';zoom:1';c=$(c);$A(c.childNodes).each(function(b){if(b.nodeType==3){b.nodeValue.toArray().each(function(a){c.insertBefore(new Element('span',{style:d}).update(a==' '?String.fromCharCode(160):a),b)});Element.remove(b)}})},multiple:function(c,d){var e;if(((typeof c=='object')||Object.isFunction(c))&&(c.length))e=c;else e=$(c).childNodes;var f=Object.extend({speed:0.1,delay:0.0},arguments[2]||{});var g=f.delay;$A(e).each(function(a,b){new d(a,Object.extend(f,{delay:b*f.speed+g}))})},PAIRS:{'slide':['SlideDown','SlideUp'],'blind':['BlindDown','BlindUp'],'appear':['Appear','Fade']},toggle:function(a,b){a=$(a);b=(b||'appear').toLowerCase();var c=Object.extend({queue:{position:'end',scope:(a.id||'global'),limit:1}},arguments[2]||{});Effect[a.visible()?Effect.PAIRS[b][1]:Effect.PAIRS[b][0]](a,c)}};Effect.DefaultOptions.transition=Effect.Transitions.sinoidal;Effect.ScopedQueue=Class.create(Enumerable,{initialize:function(){this.effects=[];this.interval=null},_each:function(a){this.effects._each(a)},add:function(a){var b=new Date().getTime();var c=Object.isString(a.options.queue)?a.options.queue:a.options.queue.position;switch(c){case'front':this.effects.findAll(function(e){return e.state=='idle'}).each(function(e){e.startOn+=a.finishOn;e.finishOn+=a.finishOn});break;case'with-last':b=this.effects.pluck('startOn').max()||b;break;case'end':b=this.effects.pluck('finishOn').max()||b;break}a.startOn+=b;a.finishOn+=b;if(!a.options.queue.limit||(this.effects.length<a.options.queue.limit))this.effects.push(a);if(!this.interval)this.interval=setInterval(this.loop.bind(this),15)},remove:function(a){this.effects=this.effects.reject(function(e){return e==a});if(this.effects.length==0){clearInterval(this.interval);this.interval=null}},loop:function(){var a=new Date().getTime();for(var i=0,len=this.effects.length;i<len;i++)this.effects[i]&&this.effects[i].loop(a)}});Effect.Queues={instances:$H(),get:function(a){if(!Object.isString(a))return a;return this.instances.get(a)||this.instances.set(a,new Effect.ScopedQueue())}};Effect.Queue=Effect.Queues.get('global');Effect.Base=Class.create({position:null,start:function(c){function codeForEvent(a,b){return((a[b+'Internal']?'this.options.'+b+'Internal(this);':'')+(a[b]?'this.options.'+b+'(this);':''))}if(c&&c.transition===false)c.transition=Effect.Transitions.linear;this.options=Object.extend(Object.extend({},Effect.DefaultOptions),c||{});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(this.options,'beforeSetup')+(this.setup?'this.setup();':'')+codeForEvent(this.options,'afterSetup')+'};if (this.state=="running"){'+'pos=this.options.transition(pos)*'+this.fromToDelta+'+'+this.options.from+';'+'this.position=pos;'+codeForEvent(this.options,'beforeUpdate')+(this.update?'this.update(pos);':'')+codeForEvent(this.options,'afterUpdate')+'}}');this.event('beforeStart');if(!this.options.sync)Effect.Queues.get(Object.isString(this.options.queue)?'global':this.options.queue.scope).add(this)},loop:function(a){if(a>=this.startOn){if(a>=this.finishOn){this.render(1.0);this.cancel();this.event('beforeFinish');if(this.finish)this.finish();this.event('afterFinish');return}var b=(a-this.startOn)/this.totalTime,frame=(b*this.totalFrames).round();if(frame>this.currentFrame){this.render(b);this.currentFrame=frame}}},cancel:function(){if(!this.options.sync)Effect.Queues.get(Object.isString(this.options.queue)?'global':this.options.queue.scope).remove(this);this.state='finished'},event:function(a){if(this.options[a+'Internal'])this.options[a+'Internal'](this);if(this.options[a])this.options[a](this)},inspect:function(){var a=$H();for(property in this)if(!Object.isFunction(this[property]))a.set(property,this[property]);return'#<Effect:'+a.inspect()+',options:'+$H(this.options).inspect()+'>'}});Effect.Parallel=Class.create(Effect.Base,{initialize:function(a){this.effects=a||[];this.start(arguments[1])},update:function(a){this.effects.invoke('render',a)},finish:function(b){this.effects.each(function(a){a.render(1.0);a.cancel();a.event('beforeFinish');if(a.finish)a.finish(b);a.event('afterFinish')})}});Effect.Tween=Class.create(Effect.Base,{initialize:function(b,c,d){b=Object.isString(b)?$(b):b;var e=$A(arguments),method=e.last(),options=e.length==5?e[3]:null;this.method=Object.isFunction(method)?method.bind(b):Object.isFunction(b[method])?b[method].bind(b):function(a){b[method]=a};this.start(Object.extend({from:c,to:d},options||{}))},update:function(a){this.method(a)}});Effect.Event=Class.create(Effect.Base,{initialize:function(){this.start(Object.extend({duration:0},arguments[0]||{}))},update:Prototype.emptyFunction});Effect.Opacity=Class.create(Effect.Base,{initialize:function(a){this.element=$(a);if(!this.element)throw(Effect._elementDoesNotExistError);if(Prototype.Browser.IE&&(!this.element.currentStyle.hasLayout))this.element.setStyle({zoom:1});var b=Object.extend({from:this.element.getOpacity()||0.0,to:1.0},arguments[1]||{});this.start(b)},update:function(a){this.element.setOpacity(a)}});Effect.Move=Class.create(Effect.Base,{initialize:function(a){this.element=$(a);if(!this.element)throw(Effect._elementDoesNotExistError);var b=Object.extend({x:0,y:0,mode:'relative'},arguments[1]||{});this.start(b)},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(a){this.element.setStyle({left:(this.options.x*a+this.originalLeft).round()+'px',top:(this.options.y*a+this.originalTop).round()+'px'})}});Effect.MoveBy=function(a,b,c){return new Effect.Move(a,Object.extend({x:c,y:b},arguments[3]||{}))};Effect.Scale=Class.create(Effect.Base,{initialize:function(a,b){this.element=$(a);if(!this.element)throw(Effect._elementDoesNotExistError);var c=Object.extend({scaleX:true,scaleY:true,scaleContent:true,scaleFromCenter:false,scaleMode:'box',scaleFrom:100.0,scaleTo:b},arguments[2]||{});this.start(c)},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 b=this.element.getStyle('font-size')||'100%';['em','px','%','pt'].each(function(a){if(b.indexOf(a)>0){this.fontSize=parseFloat(b);this.fontSizeType=a}}.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(a){var b=(this.options.scaleFrom/100.0)+(this.factor*a);if(this.options.scaleContent&&this.fontSize)this.element.setStyle({fontSize:this.fontSize*b+this.fontSizeType});this.setDimensions(this.dims[0]*b,this.dims[1]*b)},finish:function(a){if(this.restoreAfterFinish)this.element.setStyle(this.originalStyle)},setDimensions:function(a,b){var d={};if(this.options.scaleX)d.width=b.round()+'px';if(this.options.scaleY)d.height=a.round()+'px';if(this.options.scaleFromCenter){var c=(a-this.dims[0])/2;var e=(b-this.dims[1])/2;if(this.elementPositioning=='absolute'){if(this.options.scaleY)d.top=this.originalTop-c+'px';if(this.options.scaleX)d.left=this.originalLeft-e+'px'}else{if(this.options.scaleY)d.top=-c+'px';if(this.options.scaleX)d.left=-e+'px'}}this.element.setStyle(d)}});Effect.Highlight=Class.create(Effect.Base,{initialize:function(a){this.element=$(a);if(!this.element)throw(Effect._elementDoesNotExistError);var b=Object.extend({startcolor:'#ffff99'},arguments[1]||{});this.start(b)},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(a){this.element.setStyle({backgroundColor:$R(0,2).inject('#',function(m,v,i){return m+((this._base[i]+(this._delta[i]*a)).round().toColorPart())}.bind(this))})},finish:function(){this.element.setStyle(Object.extend(this.oldStyle,{backgroundColor:this.options.restorecolor}))}});Effect.ScrollTo=function(a){var b=arguments[1]||{},scrollOffsets=document.viewport.getScrollOffsets(),elementOffsets=$(a).cumulativeOffset(),max=document.viewport.getScrollOffsets[0]-document.viewport.getHeight();if(b.offset)elementOffsets[1]+=b.offset;return new Effect.Tween(null,scrollOffsets.top,elementOffsets[1]>max?max:elementOffsets[1],b,function(p){scrollTo(scrollOffsets.left,p.round())})};Effect.Fade=function(b){b=$(b);var c=b.getInlineOpacity();var d=Object.extend({from:b.getOpacity()||1.0,to:0.0,afterFinishInternal:function(a){if(a.options.to!=0)return;a.element.hide().setStyle({opacity:c})}},arguments[1]||{});return new Effect.Opacity(b,d)};Effect.Appear=function(b){b=$(b);var c=Object.extend({from:(b.getStyle('display')=='none'?0.0:b.getOpacity()||0.0),to:1.0,afterFinishInternal:function(a){a.element.forceRerendering()},beforeSetup:function(a){a.element.setOpacity(a.options.from).show()}},arguments[1]||{});return new Effect.Opacity(b,c)};Effect.Puff=function(b){b=$(b);var c={opacity:b.getInlineOpacity(),position:b.getStyle('position'),top:b.style.top,left:b.style.left,width:b.style.width,height:b.style.height};return new Effect.Parallel([new Effect.Scale(b,200,{sync:true,scaleFromCenter:true,scaleContent:true,restoreAfterFinish:true}),new Effect.Opacity(b,{sync:true,to:0.0})],Object.extend({duration:1.0,beforeSetupInternal:function(a){Position.absolutize(a.effects[0].element)},afterFinishInternal:function(a){a.effects[0].element.hide().setStyle(c)}},arguments[1]||{}))};Effect.BlindUp=function(b){b=$(b);b.makeClipping();return new Effect.Scale(b,0,Object.extend({scaleContent:false,scaleX:false,restoreAfterFinish:true,afterFinishInternal:function(a){a.element.hide().undoClipping()}},arguments[1]||{}))};Effect.BlindDown=function(b){b=$(b);var c=b.getDimensions();return new Effect.Scale(b,100,Object.extend({scaleContent:false,scaleX:false,scaleFrom:0,scaleMode:{originalHeight:c.height,originalWidth:c.width},restoreAfterFinish:true,afterSetup:function(a){a.element.makeClipping().setStyle({height:'0px'}).show()},afterFinishInternal:function(a){a.element.undoClipping()}},arguments[1]||{}))};Effect.SwitchOff=function(c){c=$(c);var d=c.getInlineOpacity();return new Effect.Appear(c,Object.extend({duration:0.4,from:0,transition:Effect.Transitions.flicker,afterFinishInternal:function(b){new Effect.Scale(b.element,1,{duration:0.3,scaleFromCenter:true,scaleX:false,scaleContent:false,restoreAfterFinish:true,beforeSetup:function(a){a.element.makePositioned().makeClipping()},afterFinishInternal:function(a){a.element.hide().undoClipping().undoPositioned().setStyle({opacity:d})}})}},arguments[1]||{}))};Effect.DropOut=function(b){b=$(b);var c={top:b.getStyle('top'),left:b.getStyle('left'),opacity:b.getInlineOpacity()};return new Effect.Parallel([new Effect.Move(b,{x:0,y:100,sync:true}),new Effect.Opacity(b,{sync:true,to:0.0})],Object.extend({duration:0.5,beforeSetup:function(a){a.effects[0].element.makePositioned()},afterFinishInternal:function(a){a.effects[0].element.hide().undoPositioned().setStyle(c)}},arguments[1]||{}))};Effect.Shake=function(g){g=$(g);var h=Object.extend({distance:20,duration:0.5},arguments[1]||{});var i=parseFloat(h.distance);var j=parseFloat(h.duration)/10.0;var k={top:g.getStyle('top'),left:g.getStyle('left')};return new Effect.Move(g,{x:i,y:0,duration:j,afterFinishInternal:function(f){new Effect.Move(f.element,{x:-i*2,y:0,duration:j*2,afterFinishInternal:function(e){new Effect.Move(e.element,{x:i*2,y:0,duration:j*2,afterFinishInternal:function(d){new Effect.Move(d.element,{x:-i*2,y:0,duration:j*2,afterFinishInternal:function(c){new Effect.Move(c.element,{x:i*2,y:0,duration:j*2,afterFinishInternal:function(b){new Effect.Move(b.element,{x:-i,y:0,duration:j,afterFinishInternal:function(a){a.element.undoPositioned().setStyle(k)}})}})}})}})}})}})};Effect.SlideDown=function(b){b=$(b).cleanWhitespace();var c=b.down().getStyle('bottom');var d=b.getDimensions();return new Effect.Scale(b,100,Object.extend({scaleContent:false,scaleX:false,scaleFrom:window.opera?0:1,scaleMode:{originalHeight:d.height,originalWidth:d.width},restoreAfterFinish:true,afterSetup:function(a){a.element.makePositioned();a.element.down().makePositioned();if(window.opera)a.element.setStyle({top:''});a.element.makeClipping().setStyle({height:'0px'}).show()},afterUpdateInternal:function(a){a.element.down().setStyle({bottom:(a.dims[0]-a.element.clientHeight)+'px'})},afterFinishInternal:function(a){a.element.undoClipping().undoPositioned();a.element.down().undoPositioned().setStyle({bottom:c})}},arguments[1]||{}))};Effect.SlideUp=function(b){b=$(b).cleanWhitespace();var c=b.down().getStyle('bottom');var d=b.getDimensions();return new Effect.Scale(b,window.opera?0:1,Object.extend({scaleContent:false,scaleX:false,scaleMode:'box',scaleFrom:100,scaleMode:{originalHeight:d.height,originalWidth:d.width},restoreAfterFinish:true,afterSetup:function(a){a.element.makePositioned();a.element.down().makePositioned();if(window.opera)a.element.setStyle({top:''});a.element.makeClipping().show()},afterUpdateInternal:function(a){a.element.down().setStyle({bottom:(a.dims[0]-a.element.clientHeight)+'px'})},afterFinishInternal:function(a){a.element.hide().undoClipping().undoPositioned();a.element.down().undoPositioned().setStyle({bottom:c})}},arguments[1]||{}))};Effect.Squish=function(b){return new Effect.Scale(b,window.opera?1:0,{restoreAfterFinish:true,beforeSetup:function(a){a.element.makeClipping()},afterFinishInternal:function(a){a.element.hide().undoClipping()}})};Effect.Grow=function(c){c=$(c);var d=Object.extend({direction:'center',moveTransition:Effect.Transitions.sinoidal,scaleTransition:Effect.Transitions.sinoidal,opacityTransition:Effect.Transitions.full},arguments[1]||{});var e={top:c.style.top,left:c.style.left,height:c.style.height,width:c.style.width,opacity:c.getInlineOpacity()};var f=c.getDimensions();var g,initialMoveY;var h,moveY;switch(d.direction){case'top-left':g=initialMoveY=h=moveY=0;break;case'top-right':g=f.width;initialMoveY=moveY=0;h=-f.width;break;case'bottom-left':g=h=0;initialMoveY=f.height;moveY=-f.height;break;case'bottom-right':g=f.width;initialMoveY=f.height;h=-f.width;moveY=-f.height;break;case'center':g=f.width/2;initialMoveY=f.height/2;h=-f.width/2;moveY=-f.height/2;break}return new Effect.Move(c,{x:g,y:initialMoveY,duration:0.01,beforeSetup:function(a){a.element.hide().makeClipping().makePositioned()},afterFinishInternal:function(b){new Effect.Parallel([new Effect.Opacity(b.element,{sync:true,to:1.0,from:0.0,transition:d.opacityTransition}),new Effect.Move(b.element,{x:h,y:moveY,sync:true,transition:d.moveTransition}),new Effect.Scale(b.element,100,{scaleMode:{originalHeight:f.height,originalWidth:f.width},sync:true,scaleFrom:window.opera?1:0,transition:d.scaleTransition,restoreAfterFinish:true})],Object.extend({beforeSetup:function(a){a.effects[0].element.setStyle({height:'0px'}).show()},afterFinishInternal:function(a){a.effects[0].element.undoClipping().undoPositioned().setStyle(e)}},d))}})};Effect.Shrink=function(b){b=$(b);var c=Object.extend({direction:'center',moveTransition:Effect.Transitions.sinoidal,scaleTransition:Effect.Transitions.sinoidal,opacityTransition:Effect.Transitions.none},arguments[1]||{});var d={top:b.style.top,left:b.style.left,height:b.style.height,width:b.style.width,opacity:b.getInlineOpacity()};var e=b.getDimensions();var f,moveY;switch(c.direction){case'top-left':f=moveY=0;break;case'top-right':f=e.width;moveY=0;break;case'bottom-left':f=0;moveY=e.height;break;case'bottom-right':f=e.width;moveY=e.height;break;case'center':f=e.width/2;moveY=e.height/2;break}return new Effect.Parallel([new Effect.Opacity(b,{sync:true,to:0.0,from:1.0,transition:c.opacityTransition}),new Effect.Scale(b,window.opera?1:0,{sync:true,transition:c.scaleTransition,restoreAfterFinish:true}),new Effect.Move(b,{x:f,y:moveY,sync:true,transition:c.moveTransition})],Object.extend({beforeStartInternal:function(a){a.effects[0].element.makePositioned().makeClipping()},afterFinishInternal:function(a){a.effects[0].element.hide().undoClipping().undoPositioned().setStyle(d)}},c))};Effect.Pulsate=function(b){b=$(b);var c=arguments[1]||{};var d=b.getInlineOpacity();var e=c.transition||Effect.Transitions.sinoidal;var f=function(a){return e(1-Effect.Transitions.pulse(a,c.pulses))};f.bind(e);return new Effect.Opacity(b,Object.extend(Object.extend({duration:2.0,from:0,afterFinishInternal:function(a){a.element.setStyle({opacity:d})}},c),{transition:f}))};Effect.Fold=function(c){c=$(c);var d={top:c.style.top,left:c.style.left,width:c.style.width,height:c.style.height};c.makeClipping();return new Effect.Scale(c,5,Object.extend({scaleContent:false,scaleX:false,afterFinishInternal:function(b){new Effect.Scale(c,1,{scaleContent:false,scaleY:false,afterFinishInternal:function(a){a.element.hide().undoClipping().setStyle(d)}})}},arguments[1]||{}))};Effect.Morph=Class.create(Effect.Base,{initialize:function(c){this.element=$(c);if(!this.element)throw(Effect._elementDoesNotExistError);var d=Object.extend({style:{}},arguments[1]||{});if(!Object.isString(d.style))this.style=$H(d.style);else{if(d.style.include(':'))this.style=d.style.parseStyle();else{this.element.addClassName(d.style);this.style=$H(this.element.getStyles());this.element.removeClassName(d.style);var e=this.element.getStyles();this.style=this.style.reject(function(a){return a.value==e[a.key]});d.afterFinishInternal=function(b){b.element.addClassName(b.options.style);b.transforms.each(function(a){b.element.style[a.style]=''})}}}this.start(d)},setup:function(){function parseColor(a){if(!a||['rgba(0, 0, 0, 0)','transparent'].include(a))a='#ffffff';a=a.parseColor();return $R(0,2).map(function(i){return parseInt(a.slice(i*2+1,i*2+3),16)})}this.transforms=this.style.map(function(a){var b=a[0],value=a[1],unit=null;if(value.parseColor('#zzzzzz')!='#zzzzzz'){value=value.parseColor();unit='color'}else if(b=='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 c=value.match(/^([\+\-]?[0-9\.]+)(.*)$/);value=parseFloat(c[1]);unit=(c.length==3)?c[2]:null}var d=this.element.getStyle(b);return{style:b.camelize(),originalValue:unit=='color'?parseColor(d):parseFloat(d||0),targetValue:unit=='color'?parseColor(value):value,unit:unit}}.bind(this)).reject(function(a){return((a.originalValue==a.targetValue)||(a.unit!='color'&&(isNaN(a.originalValue)||isNaN(a.targetValue))))})},update:function(a){var b={},transform,i=this.transforms.length;while(i--)b[(transform=this.transforms[i]).style]=transform.unit=='color'?'#'+(Math.round(transform.originalValue[0]+(transform.targetValue[0]-transform.originalValue[0])*a)).toColorPart()+(Math.round(transform.originalValue[1]+(transform.targetValue[1]-transform.originalValue[1])*a)).toColorPart()+(Math.round(transform.originalValue[2]+(transform.targetValue[2]-transform.originalValue[2])*a)).toColorPart():(transform.originalValue+(transform.targetValue-transform.originalValue)*a).toFixed(3)+(transform.unit===null?'':transform.unit);this.element.setStyle(b,true)}});Effect.Transform=Class.create({initialize:function(a){this.tracks=[];this.options=arguments[1]||{};this.addTracks(a)},addTracks:function(c){c.each(function(a){a=$H(a);var b=a.values().first();this.tracks.push($H({ids:a.keys().first(),effect:Effect.Morph,options:{style:b}}))}.bind(this));return this},play:function(){return new Effect.Parallel(this.tracks.map(function(a){var b=a.get('ids'),effect=a.get('effect'),options=a.get('options');var c=[$(b)||$$(b)].flatten();return c.map(function(e){return new effect(e,Object.extend({sync:true},options))})}).flatten(),this.options)}});Element.CSS_PROPERTIES=$w('backgroundColor backgroundPosition borderBottomColor borderBottomStyle '+'borderBottomWidth borderLeftColor borderLeftStyle borderLeftWidth '+'borderRightColor borderRightStyle borderRightWidth borderSpacing '+'borderTopColor borderTopStyle borderTopWidth bottom clip color '+'fontSize fontWeight height left letterSpacing lineHeight '+'marginBottom marginLeft marginRight marginTop markerOffset maxHeight '+'maxWidth minHeight minWidth opacity outlineColor outlineOffset '+'outlineWidth paddingBottom paddingLeft paddingRight paddingTop '+'right textIndent top width wordSpacing zIndex');Element.CSS_LENGTH=/^(([\+\-]?[0-9\.]+)(em|ex|px|in|cm|mm|pt|pc|\%))|0$/;String.__parseStyleElement=document.createElement('div');String.prototype.parseStyle=function(){var b,styleRules=$H();if(Prototype.Browser.WebKit)b=new Element('div',{style:this}).style;else{String.__parseStyleElement.innerHTML='<div style="'+this+'"></div>';b=String.__parseStyleElement.childNodes[0].style}Element.CSS_PROPERTIES.each(function(a){if(b[a])styleRules.set(a,b[a])});if(Prototype.Browser.IE&&this.include('opacity'))styleRules.set('opacity',this.match(/opacity:\s*((?:0|1)?(?:\.\d*)?)/)[1]);return styleRules};if(document.defaultView&&document.defaultView.getComputedStyle){Element.getStyles=function(c){var d=document.defaultView.getComputedStyle($(c),null);return Element.CSS_PROPERTIES.inject({},function(a,b){a[b]=d[b];return a})}}else{Element.getStyles=function(c){c=$(c);var d=c.currentStyle,styles;styles=Element.CSS_PROPERTIES.inject({},function(a,b){a[b]=d[b];return a});if(!styles.opacity)styles.opacity=c.getOpacity();return styles}}Effect.Methods={morph:function(a,b){a=$(a);new Effect.Morph(a,Object.extend({style:b},arguments[2]||{}));return a},visualEffect:function(a,b,c){a=$(a);var s=b.dasherize().camelize(),klass=s.charAt(0).toUpperCase()+s.substring(1);new Effect[klass](a,c);return a},highlight:function(a,b){a=$(a);new Effect.Highlight(a,b);return a}};$w('fade appear grow shrink fold blindUp blindDown slideUp slideDown '+'pulsate shake puff squish switchOff dropOut').each(function(c){Effect.Methods[c]=function(a,b){a=$(a);Effect[c.charAt(0).toUpperCase()+c.substring(1)](a,b);return a}});$w('getInlineOpacity forceRerendering setContentZoom collectTextNodes collectTextNodesIgnoreClass getStyles').each(function(f){Effect.Methods[f]=Element[f]});Element.addMethods(Effect.Methods);
//dragdrop.js
if(Object.isUndefined(Effect))throw("dragdrop.js requires including script.aculo.us' effects.js library");var Droppables={drops:[],remove:function(a){this.drops=this.drops.reject(function(d){return d.element==$(a)})},add:function(a){a=$(a);var b=Object.extend({greedy:true,hoverclass:null,tree:false},arguments[1]||{});if(b.containment){b._containers=[];var d=b.containment;if(Object.isArray(d)){d.each(function(c){b._containers.push($(c))})}else{b._containers.push($(d))}}if(b.accept)b.accept=[b.accept].flatten();Element.makePositioned(a);b.element=a;this.drops.push(b)},findDeepestChild:function(a){deepest=a[0];for(i=1;i<a.length;++i)if(Element.isParent(a[i].element,deepest.element))deepest=a[i];return deepest},isContained:function(a,b){var d;if(b.tree){d=a.treeNode}else{d=a.parentNode}return b._containers.detect(function(c){return d==c})},isAffected:function(a,b,c){return((c.element!=b)&&((!c._containers)||this.isContained(b,c))&&((!c.accept)||(Element.classNames(b).detect(function(v){return c.accept.include(v)})))&&Position.within(c.element,a[0],a[1]))},deactivate:function(a){if(a.hoverclass)Element.removeClassName(a.element,a.hoverclass);this.last_active=null},activate:function(a){if(a.hoverclass)Element.addClassName(a.element,a.hoverclass);this.last_active=a},show:function(b,c){if(!this.drops.length)return;var d,affected=[];this.drops.each(function(a){if(Droppables.isAffected(b,c,a))affected.push(a)});if(affected.length>0)d=Droppables.findDeepestChild(affected);if(this.last_active&&this.last_active!=d)this.deactivate(this.last_active);if(d){Position.within(d.element,b[0],b[1]);if(d.onHover)d.onHover(c,d.element,Position.overlap(d.overlap,d.element));if(d!=this.last_active)Droppables.activate(d)}},fire:function(a,b){if(!this.last_active)return;Position.prepare();if(this.isAffected([Event.pointerX(a),Event.pointerY(a)],b,this.last_active))if(this.last_active.onDrop){this.last_active.onDrop(b,this.last_active.element,a);return true}},reset:function(){if(this.last_active)this.deactivate(this.last_active)}};var Draggables={drags:[],observers:[],register:function(a){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(a)},unregister:function(a){this.drags=this.drags.reject(function(d){return d==a});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(a){if(a.options.delay){this._timeout=setTimeout(function(){Draggables._timeout=null;window.focus();Draggables.activeDraggable=a}.bind(this),a.options.delay)}else{window.focus();this.activeDraggable=a}},deactivate:function(){this.activeDraggable=null},updateDrag:function(a){if(!this.activeDraggable)return;var b=[Event.pointerX(a),Event.pointerY(a)];if(this._lastPointer&&(this._lastPointer.inspect()==b.inspect()))return;this._lastPointer=b;this.activeDraggable.updateDrag(a,b)},endDrag:function(a){if(this._timeout){clearTimeout(this._timeout);this._timeout=null}if(!this.activeDraggable)return;this._lastPointer=null;this.activeDraggable.endDrag(a);this.activeDraggable=null},keyPress:function(a){if(this.activeDraggable)this.activeDraggable.keyPress(a)},addObserver:function(a){this.observers.push(a);this._cacheObserverCallbacks()},removeObserver:function(a){this.observers=this.observers.reject(function(o){return o.element==a});this._cacheObserverCallbacks()},notify:function(a,b,c){if(this[a+'Count']>0)this.observers.each(function(o){if(o[a])o[a](a,b,c)});if(b.options[a])b.options[a](b,c)},_cacheObserverCallbacks:function(){['onStart','onEnd','onDrag'].each(function(a){Draggables[a+'Count']=Draggables.observers.select(function(o){return o[a]}).length})}};var Draggable=Class.create({initialize:function(e){var f={handle:false,reverteffect:function(a,b,c){var d=Math.sqrt(Math.abs(b^2)+Math.abs(c^2))*0.02;new Effect.Move(a,{x:-c,y:-b,duration:d,queue:{scope:'_draggable',position:'end'}})},endeffect:function(a){var b=Object.isNumber(a._opacity)?a._opacity:1.0;new Effect.Opacity(a,{duration:0.2,from:0.7,to:b,queue:{scope:'_draggable',position:'end'},afterFinish:function(){Draggable._dragging[a]=false}})},zindex:1000,revert:false,quiet:false,scroll:false,scrollSensitivity:20,scrollSpeed:15,snap:false,delay:0};if(!arguments[1]||Object.isUndefined(arguments[1].endeffect))Object.extend(f,{starteffect:function(a){a._opacity=Element.getOpacity(a);Draggable._dragging[a]=true;new Effect.Opacity(a,{duration:0.2,from:a._opacity,to:0.7})}});var g=Object.extend(f,arguments[1]||{});this.element=$(e);if(g.handle&&Object.isString(g.handle))this.handle=this.element.down('.'+g.handle,0);if(!this.handle)this.handle=$(g.handle);if(!this.handle)this.handle=this.element;if(g.scroll&&!g.scroll.scrollTo&&!g.scroll.outerHTML){g.scroll=$(g.scroll);this._isScrollChild=Element.childOf(this.element,g.scroll)}Element.makePositioned(this.element);this.options=g;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(a){if(!Object.isUndefined(Draggable._dragging[this.element])&&Draggable._dragging[this.element])return;if(Event.isLeftClick(a)){var b=Event.element(a);if((tag_name=b.tagName.toUpperCase())&&(tag_name=='INPUT'||tag_name=='SELECT'||tag_name=='OPTION'||tag_name=='BUTTON'||tag_name=='TEXTAREA'))return;var c=[Event.pointerX(a),Event.pointerY(a)];var d=Position.cumulativeOffset(this.element);this.offset=[0,1].map(function(i){return(c[i]-d[i])});Draggables.activate(this);Event.stop(a)}},startDrag:function(a){this.dragging=true;if(!this.delta)this.delta=this.currentDelta();if(this.options.zindex){this.originalZ=parseInt(Element.getStyle(this.element,'z-index')||0);this.element.style.zIndex=this.options.zindex}if(this.options.ghosting){this._clone=this.element.cloneNode(true);this._originallyAbsolute=(this.element.getStyle('position')=='absolute');if(!this._originallyAbsolute)Position.absolutize(this.element);this.element.parentNode.insertBefore(this._clone,this.element)}if(this.options.scroll){if(this.options.scroll==window){var b=this._getWindowScroll(this.options.scroll);this.originalScrollLeft=b.left;this.originalScrollTop=b.top}else{this.originalScrollLeft=this.options.scroll.scrollLeft;this.originalScrollTop=this.options.scroll.scrollTop}}Draggables.notify('onStart',this,a);if(this.options.starteffect)this.options.starteffect(this.element)},updateDrag:function(a,b){if(!this.dragging)this.startDrag(a);if(!this.options.quiet){Position.prepare();Droppables.show(b,this.element)}Draggables.notify('onDrag',this,a);this.draw(b);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 c=[0,0];if(b[0]<(p[0]+this.options.scrollSensitivity))c[0]=b[0]-(p[0]+this.options.scrollSensitivity);if(b[1]<(p[1]+this.options.scrollSensitivity))c[1]=b[1]-(p[1]+this.options.scrollSensitivity);if(b[0]>(p[2]-this.options.scrollSensitivity))c[0]=b[0]-(p[2]-this.options.scrollSensitivity);if(b[1]>(p[3]-this.options.scrollSensitivity))c[1]=b[1]-(p[3]-this.options.scrollSensitivity);this.startScrolling(c)}if(Prototype.Browser.WebKit)window.scrollBy(0,0);Event.stop(a)},finishDrag:function(a,b){this.dragging=false;if(this.options.quiet){Position.prepare();var c=[Event.pointerX(a),Event.pointerY(a)];Droppables.show(c,this.element)}if(this.options.ghosting){if(!this._originallyAbsolute)Position.relativize(this.element);delete this._originallyAbsolute;Element.remove(this._clone);this._clone=null}var e=false;if(b){e=Droppables.fire(a,this.element);if(!e)e=false}if(e&&this.options.onDropped)this.options.onDropped(this.element);Draggables.notify('onEnd',this,a);var f=this.options.revert;if(f&&Object.isFunction(f))f=f(this.element);var d=this.currentDelta();if(f&&this.options.reverteffect){if(e==0||f!='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(a){if(a.keyCode!=Event.KEY_ESC)return;this.finishDrag(a,false);Event.stop(a)},endDrag:function(a){if(!this.dragging)return;this.stopScrolling();this.finishDrag(a,true);Event.stop(a)},draw:function(a){var b=Position.cumulativeOffset(this.element);if(this.options.ghosting){var r=Position.realOffset(this.element);b[0]+=r[0]-Position.deltaX;b[1]+=r[1]-Position.deltaY}var d=this.currentDelta();b[0]-=d[0];b[1]-=d[1];if(this.options.scroll&&(this.options.scroll!=window&&this._isScrollChild)){b[0]-=this.options.scroll.scrollLeft-this.originalScrollLeft;b[1]-=this.options.scroll.scrollTop-this.originalScrollTop}var p=[0,1].map(function(i){return(a[i]-b[i]-this.offset[i])}.bind(this));if(this.options.snap){if(Object.isFunction(this.options.snap)){p=this.options.snap(p[0],p[1],this)}else{if(Object.isArray(this.options.snap)){p=p.map(function(v,i){return(v/this.options.snap[i]).round()*this.options.snap[i]}.bind(this))}else{p=p.map(function(v){return(v/this.options.snap).round()*this.options.snap}.bind(this))}}}var c=this.element.style;if((!this.options.constraint)||(this.options.constraint=='horizontal'))c.left=p[0]+"px";if((!this.options.constraint)||(this.options.constraint=='vertical'))c.top=p[1]+"px";if(c.visibility=="hidden")c.visibility=""},stopScrolling:function(){if(this.scrollInterval){clearInterval(this.scrollInterval);this.scrollInterval=null;Draggables._lastScrollPointer=null}},startScrolling:function(a){if(!(a[0]||a[1]))return;this.scrollSpeed=[a[0]*this.options.scrollSpeed,a[1]*this.options.scrollSpeed];this.lastScrolled=new Date();this.scrollInterval=setInterval(this.scroll.bind(this),10)},scroll:function(){var a=new Date();var b=a-this.lastScrolled;this.lastScrolled=a;if(this.options.scroll==window){with(this._getWindowScroll(this.options.scroll)){if(this.scrollSpeed[0]||this.scrollSpeed[1]){var d=b/1000;this.options.scroll.scrollTo(left+d*this.scrollSpeed[0],top+d*this.scrollSpeed[1])}}}else{this.options.scroll.scrollLeft+=this.scrollSpeed[0]*b/1000;this.options.scroll.scrollTop+=this.scrollSpeed[1]*b/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]*b/1000;Draggables._lastScrollPointer[1]+=this.scrollSpeed[1]*b/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}}});Draggable._dragging={};var SortableObserver=Class.create({initialize:function(a,b){this.element=$(a);this.observer=b;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(a){while(a.tagName.toUpperCase()!="BODY"){if(a.id&&Sortable.sortables[a.id])return a;a=a.parentNode}},options:function(a){a=Sortable._findRootElement($(a));if(!a)return;return Sortable.sortables[a.id]},destroy:function(a){var s=Sortable.options(a);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(b){b=$(b);var c=Object.extend({element:b,tag:'li',dropOnEmpty:false,tree:false,treeTag:'ul',overlap:'vertical',constraint:'vertical',containment:b,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(b);var d={revert:true,quiet:c.quiet,scroll:c.scroll,scrollSpeed:c.scrollSpeed,scrollSensitivity:c.scrollSensitivity,delay:c.delay,ghosting:c.ghosting,constraint:c.constraint,handle:c.handle};if(c.starteffect)d.starteffect=c.starteffect;if(c.reverteffect)d.reverteffect=c.reverteffect;else if(c.ghosting)d.reverteffect=function(a){a.style.top=0;a.style.left=0};if(c.endeffect)d.endeffect=c.endeffect;if(c.zindex)d.zindex=c.zindex;var f={overlap:c.overlap,containment:c.containment,tree:c.tree,hoverclass:c.hoverclass,onHover:Sortable.onHover};var g={onHover:Sortable.onEmptyHover,overlap:c.overlap,containment:c.containment,hoverclass:c.hoverclass};Element.cleanWhitespace(b);c.draggables=[];c.droppables=[];if(c.dropOnEmpty||c.tree){Droppables.add(b,g);c.droppables.push(b)}(c.elements||this.findElements(b,c)||[]).each(function(e,i){var a=c.handles?$(c.handles[i]):(c.handle?$(e).select('.'+c.handle)[0]:e);c.draggables.push(new Draggable(e,Object.extend(d,{handle:a})));Droppables.add(e,f);if(c.tree)e.treeNode=b;c.droppables.push(e)});if(c.tree){(Sortable.findTreeElements(b,c)||[]).each(function(e){Droppables.add(e,g);e.treeNode=b;c.droppables.push(e)})}this.sortables[b.id]=c;Draggables.addObserver(new SortableObserver(b,c.onUpdate))},findElements:function(a,b){return Element.findChildren(a,b.only,b.tree?true:false,b.tag)},findTreeElements:function(a,b){return Element.findChildren(a,b.only,b.tree?true:false,b.treeTag)},onHover:function(a,b,c){if(Element.isParent(b,a))return;if(c>.33&&c<.66&&Sortable.options(b).tree){return}else if(c>0.5){Sortable.mark(b,'before');if(b.previousSibling!=a){var d=a.parentNode;a.style.visibility="hidden";b.parentNode.insertBefore(a,b);if(b.parentNode!=d)Sortable.options(d).onChange(a);Sortable.options(b.parentNode).onChange(a)}}else{Sortable.mark(b,'after');var e=b.nextSibling||null;if(e!=a){var d=a.parentNode;a.style.visibility="hidden";b.parentNode.insertBefore(a,e);if(b.parentNode!=d)Sortable.options(d).onChange(a);Sortable.options(b.parentNode).onChange(a)}}},onEmptyHover:function(a,b,c){var d=a.parentNode;var e=Sortable.options(b);if(!Element.isParent(b,a)){var f;var g=Sortable.findElements(b,{tag:e.tag,only:e.only});var h=null;if(g){var i=Element.offsetSize(b,e.overlap)*(1.0-c);for(f=0;f<g.length;f+=1){if(i-Element.offsetSize(g[f],e.overlap)>=0){i-=Element.offsetSize(g[f],e.overlap)}else if(i-(Element.offsetSize(g[f],e.overlap)/2)>=0){h=f+1<g.length?g[f+1]:null;break}else{h=g[f];break}}}b.insertBefore(a,h);Sortable.options(d).onChange(a);e.onChange(a)}},unmark:function(){if(Sortable._marker)Sortable._marker.hide()},mark:function(a,b){var c=Sortable.options(a.parentNode);if(c&&!c.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 d=Position.cumulativeOffset(a);Sortable._marker.setStyle({left:d[0]+'px',top:d[1]+'px'});if(b=='after')if(c.overlap=='horizontal')Sortable._marker.setStyle({left:(d[0]+a.clientWidth)+'px'});else Sortable._marker.setStyle({top:(d[1]+a.clientHeight)+'px'});Sortable._marker.show()},_tree:function(a,b,c){var d=Sortable.findElements(a,b)||[];for(var i=0;i<d.length;++i){var e=d[i].id.match(b.format);if(!e)continue;var f={id:encodeURIComponent(e?e[1]:null),element:a,parent:c,children:[],position:c.children.length,container:$(d[i]).down(b.treeTag)};if(f.container)this._tree(f.container,b,f);c.children.push(f)}return c},tree:function(a){a=$(a);var b=this.options(a);var c=Object.extend({tag:b.tag,treeTag:b.treeTag,only:b.only,name:a.id,format:b.format},arguments[1]||{});var d={id:null,parent:null,children:[],container:a,position:0};return Sortable._tree(a,c,d)},_constructIndex:function(a){var b='';do{if(a.id)b='['+a.position+']'+b}while((a=a.parent)!=null);return b},sequence:function(b){b=$(b);var c=Object.extend(this.options(b),arguments[1]||{});return $(this.findElements(b,c)||[]).map(function(a){return a.id.match(c.format)?a.id.match(c.format)[1]:''})},setSequence:function(b,c){b=$(b);var d=Object.extend(this.options(b),arguments[2]||{});var e={};this.findElements(b,d).each(function(n){if(n.id.match(d.format))e[n.id.match(d.format)[1]]=[n,n.parentNode];n.parentNode.removeChild(n)});c.each(function(a){var n=e[a];if(n){n[1].appendChild(n[0]);delete e[a]}})},serialize:function(b){b=$(b);var c=Object.extend(Sortable.options(b),arguments[1]||{});var d=encodeURIComponent((arguments[1]&&arguments[1].name)?arguments[1].name:b.id);if(c.tree){return Sortable.tree(b,arguments[1]).children.map(function(a){return[d+Sortable._constructIndex(a)+"[id]="+encodeURIComponent(a.id)].concat(a.children.map(arguments.callee))}).flatten().join('&')}else{return Sortable.sequence(b,arguments[1]).map(function(a){return d+"[]="+encodeURIComponent(a)}).join('&')}}};Element.isParent=function(a,b){if(!a.parentNode||a==b)return false;if(a.parentNode==b)return true;return Element.isParent(a.parentNode,b)};Element.findChildren=function(b,c,d,f){if(!b.hasChildNodes())return null;f=f.toUpperCase();if(c)c=[c].flatten();var g=[];$A(b.childNodes).each(function(e){if(e.tagName&&e.tagName.toUpperCase()==f&&(!c||(Element.classNames(e).detect(function(v){return c.include(v)}))))g.push(e);if(d){var a=Element.findChildren(e,c,d,f);if(a)g.push(a)}});return(g.length>0?g.flatten():[])};Element.offsetSize=function(a,b){return a['offset'+((b=='vertical'||b=='height')?'Height':'Width')]};
//controls.js
if(typeof Effect=='undefined')throw("controls.js requires including script.aculo.us' effects.js library");var Autocompleter={};Autocompleter.Base=Class.create({baseInitialize:function(c,d,e){c=$(c);this.element=c;this.update=$(d);this.hasFocus=false;this.changed=false;this.active=false;this.index=0;this.entryCount=0;this.oldElementValue=this.element.value;if(this.setOptions)this.setOptions(e);else this.options=e||{};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(a,b){if(!b.style.position||b.style.position=='absolute'){b.style.position='absolute';Position.clone(a,b,{setHeight:false,offsetTop:a.offsetHeight})}Effect.Appear(b,{duration:0.15})};this.options.onHide=this.options.onHide||function(a,b){new Effect.Fade(b,{duration:0.15})};if(typeof(this.options.tokens)=='string')this.options.tokens=new Array(this.options.tokens);if(!this.options.tokens.include('\n'))this.options.tokens.push('\n');this.observer=null;this.element.setAttribute('autocomplete','off');Element.hide(this.update);Event.observe(this.element,'blur',this.onBlur.bindAsEventListener(this));Event.observe(this.element,'keydown',this.onKeyPress.bindAsEventListener(this))},show:function(){if(Element.getStyle(this.update,'display')=='none')this.options.onShow(this.element,this.update);if(!this.iefix&&(Prototype.Browser.IE)&&(Element.getStyle(this.update,'position')=='absolute')){new Insertion.After(this.update,'<iframe id="'+this.update.id+'_iefix" '+'style="display:none;position:absolute;filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0);" '+'src="javascript:false;" frameborder="0" scrolling="no"></iframe>');this.iefix=$(this.update.id+'_iefix')}if(this.iefix)setTimeout(this.fixIEOverlapping.bind(this),50)},fixIEOverlapping:function(){Position.clone(this.update,this.iefix,{setTop:(!this.update.style.height)});this.iefix.style.zIndex=1;this.update.style.zIndex=2;Element.show(this.iefix)},hide:function(){this.stopIndicator();if(Element.getStyle(this.update,'display')!='none')this.options.onHide(this.element,this.update);if(this.iefix)Element.hide(this.iefix)},startIndicator:function(){if(this.options.indicator)Element.show(this.options.indicator)},stopIndicator:function(){if(this.options.indicator)Element.hide(this.options.indicator)},onKeyPress:function(a){if(this.active)switch(a.keyCode){case Event.KEY_TAB:case Event.KEY_RETURN:this.selectEntry();Event.stop(a);case Event.KEY_ESC:this.hide();this.active=false;Event.stop(a);return;case Event.KEY_LEFT:case Event.KEY_RIGHT:return;case Event.KEY_UP:this.markPrevious();this.render();Event.stop(a);return;case Event.KEY_DOWN:this.markNext();this.render();Event.stop(a);return}else if(a.keyCode==Event.KEY_TAB||a.keyCode==Event.KEY_RETURN||(Prototype.Browser.WebKit>0&&a.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(a){var b=Event.findElement(a,'LI');if(this.index!=b.autocompleteIndex){this.index=b.autocompleteIndex;this.render()}Event.stop(a)},onClick:function(a){var b=Event.findElement(a,'LI');this.index=b.autocompleteIndex;this.selectEntry();this.hide()},onBlur:function(a){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(a){return this.update.firstChild.childNodes[a]},getCurrentEntry:function(){return this.getEntry(this.index)},selectEntry:function(){this.active=false;this.updateElement(this.getCurrentEntry())},updateElement:function(a){if(this.options.updateElement){this.options.updateElement(a);return}var b='';if(this.options.select){var c=$(a).select('.'+this.options.select)||[];if(c.length>0)b=Element.collectTextNodes(c[0],this.options.select)}else b=Element.collectTextNodesIgnoreClass(a,'informal');var d=this.getTokenBounds();if(d[0]!=-1){var e=this.element.value.substr(0,d[0]);var f=this.element.value.substr(d[0]).match(/^\s+/);if(f)e+=f[0];this.element.value=e+b+this.element.value.substr(d[1])}else{this.element.value=b}this.oldElementValue=this.element.value;this.element.focus();if(this.options.afterUpdateElement)this.options.afterUpdateElement(this.element,a)},updateChoices:function(a){if(!this.changed&&this.hasFocus){this.update.innerHTML=a;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 b=this.getEntry(i);b.autocompleteIndex=i;this.addObservers(b)}}else{this.entryCount=0}this.stopIndicator();this.index=0;if(this.entryCount==1&&this.options.autoSelect){this.selectEntry();this.hide()}else{this.render()}}},addObservers:function(a){Event.observe(a,"mouseover",this.onHover.bindAsEventListener(this));Event.observe(a,"click",this.onClick.bindAsEventListener(this))},onObserverEvent:function(){this.changed=false;this.tokenBounds=null;if(this.getToken().length>=this.options.minChars){this.getUpdatedChoices()}else{this.active=false;this.hide()}this.oldElementValue=this.element.value},getToken:function(){var a=this.getTokenBounds();return this.element.value.substring(a[0],a[1]).strip()},getTokenBounds:function(){if(null!=this.tokenBounds)return this.tokenBounds;var a=this.element.value;if(a.strip().empty())return[-1,0];var b=arguments.callee.getFirstDifferencePos(a,this.oldElementValue);var c=(b==this.oldElementValue.length?1:0);var d=-1,nextTokenPos=a.length;var e;for(var f=0,l=this.options.tokens.length;f<l;++f){e=a.lastIndexOf(this.options.tokens[f],b+c-1);if(e>d)d=e;e=a.indexOf(this.options.tokens[f],b+c);if(-1!=e&&e<nextTokenPos)nextTokenPos=e}return(this.tokenBounds=[d+1,nextTokenPos])}});Autocompleter.Base.prototype.getTokenBounds.getFirstDifferencePos=function(a,b){var c=Math.min(a.length,b.length);for(var d=0;d<c;++d)if(a[d]!=b[d])return d;return c};Ajax.Autocompleter=Class.create(Autocompleter.Base,{initialize:function(a,b,c,d){this.baseInitialize(a,b,d);this.options.asynchronous=true;this.options.onComplete=this.onComplete.bind(this);this.options.defaultParams=this.options.parameters||null;this.url=c},getUpdatedChoices:function(){this.startIndicator();var a=encodeURIComponent(this.options.paramName)+'='+encodeURIComponent(this.getToken());this.options.parameters=this.options.callback?this.options.callback(this.element,a):a;if(this.options.defaultParams)this.options.parameters+='&'+this.options.defaultParams;new Ajax.Request(this.url,this.options)},onComplete:function(a){this.updateChoices(a.responseText)}});Autocompleter.Local=Class.create(Autocompleter.Base,{initialize:function(a,b,c,d){this.baseInitialize(a,b,d);this.options.array=c},getUpdatedChoices:function(){this.updateChoices(this.options.selector(this))},setOptions:function(h){this.options=Object.extend({choices:10,partialSearch:true,partialChars:2,ignoreCase:true,fullSearch:false,selector:function(a){var b=[];var c=[];var d=a.getToken();var e=0;for(var i=0;i<a.options.array.length&&b.length<a.options.choices;i++){var f=a.options.array[i];var g=a.options.ignoreCase?f.toLowerCase().indexOf(d.toLowerCase()):f.indexOf(d);while(g!=-1){if(g==0&&f.length!=d.length){b.push("<li><strong>"+f.substr(0,d.length)+"</strong>"+f.substr(d.length)+"</li>");break}else if(d.length>=a.options.partialChars&&a.options.partialSearch&&g!=-1){if(a.options.fullSearch||/\s/.test(f.substr(g-1,1))){c.push("<li>"+f.substr(0,g)+"<strong>"+f.substr(g,d.length)+"</strong>"+f.substr(g+d.length)+"</li>");break}}g=a.options.ignoreCase?f.toLowerCase().indexOf(d.toLowerCase(),g+1):f.indexOf(d,g+1)}}if(c.length)b=b.concat(c.slice(0,a.options.choices-b.length));return"<ul>"+b.join('')+"</ul>"}},h||{})}});Field.scrollFreeActivate=function(a){setTimeout(function(){Field.activate(a)},1)};Ajax.InPlaceEditor=Class.create({initialize:function(a,b,c){this.url=b;this.element=a=$(a);this.prepareOptions();this._controls={};arguments.callee.dealWithDeprecatedOptions(c);Object.extend(this.options,c||{});if(!this.options.formId&&this.element.id){this.options.formId=this.element.id+'-inplaceeditor';if($(this.options.formId))this.options.formId=''}if(this.options.externalControl)this.options.externalControl=$(this.options.externalControl);if(!this.options.externalControl)this.options.externalControlOnly=false;this._originalBackground=this.element.getStyle('background-color')||'transparent';this.element.title=this.options.clickToEditText;this._boundCancelHandler=this.handleFormCancellation.bind(this);this._boundComplete=(this.options.onComplete||Prototype.emptyFunction).bind(this);this._boundFailureHandler=this.handleAJAXFailure.bind(this);this._boundSubmitHandler=this.handleFormSubmission.bind(this);this._boundWrapperHandler=this.wrapUp.bind(this);this.registerListeners()},checkForEscapeOrReturn:function(e){if(!this._editing||e.ctrlKey||e.altKey||e.shiftKey)return;if(Event.KEY_ESC==e.keyCode)this.handleFormCancellation(e);else if(Event.KEY_RETURN==e.keyCode)this.handleFormSubmission(e)},createControl:function(a,b,c){var d=this.options[a+'Control'];var e=this.options[a+'Text'];if('button'==d){var f=document.createElement('input');f.type='submit';f.value=e;f.className='editor_'+a+'_button';if('cancel'==a)f.onclick=this._boundCancelHandler;this._form.appendChild(f);this._controls[a]=f}else if('link'==d){var g=document.createElement('a');g.href='#';g.appendChild(document.createTextNode(e));g.onclick='cancel'==a?this._boundCancelHandler:this._boundSubmitHandler;g.className='editor_'+a+'_link';if(c)g.className+=' '+c;this._form.appendChild(g);this._controls[a]=g}},createEditField:function(){var a=(this.options.loadTextURL?this.options.loadingText:this.getText());var b;if(1>=this.options.rows&&!/\r|\n/.test(this.getText())){b=document.createElement('input');b.type='text';var c=this.options.size||this.options.cols||0;if(0<c)b.size=c}else{b=document.createElement('textarea');b.rows=(1>=this.options.rows?this.options.autoRows:this.options.rows);b.cols=this.options.cols||40}b.name=this.options.paramName;b.value=a;b.className='editor_field';if(this.options.submitOnBlur)b.onblur=this._boundSubmitHandler;this._controls.editor=b;if(this.options.loadTextURL)this.loadExternalText();this._form.appendChild(this._controls.editor)},createForm:function(){var d=this;function addText(a,b){var c=d.options['text'+a+'Controls'];if(!c||b===false)return;d._form.appendChild(document.createTextNode(c))};this._form=$(document.createElement('form'));this._form.id=this.options.formId;this._form.addClassName(this.options.formClassName);this._form.onsubmit=this._boundSubmitHandler;this.createEditField();if('textarea'==this._controls.editor.tagName.toLowerCase())this._form.appendChild(document.createElement('br'));if(this.options.onFormCustomization)this.options.onFormCustomization(this,this._form);addText('Before',this.options.okControl||this.options.cancelControl);this.createControl('ok',this._boundSubmitHandler);addText('Between',this.options.okControl&&this.options.cancelControl);this.createControl('cancel',this._boundCancelHandler,'editor_cancel');addText('After',this.options.okControl||this.options.cancelControl)},destroy:function(){if(this._oldInnerHTML)this.element.innerHTML=this._oldInnerHTML;this.leaveEditMode();this.unregisterListeners()},enterEditMode:function(e){if(this._saving||this._editing)return;this._editing=true;this.triggerCallback('onEnterEditMode');if(this.options.externalControl)this.options.externalControl.hide();this.element.hide();this.createForm();this.element.parentNode.insertBefore(this._form,this.element);if(!this.options.loadTextURL)this.postProcessEditField();if(e)Event.stop(e)},enterHover:function(e){if(this.options.hoverClassName)this.element.addClassName(this.options.hoverClassName);if(this._saving)return;this.triggerCallback('onEnterHover')},getText:function(){return this.element.innerHTML},handleAJAXFailure:function(a){this.triggerCallback('onFailure',a);if(this._oldInnerHTML){this.element.innerHTML=this._oldInnerHTML;this._oldInnerHTML=null}},handleFormCancellation:function(e){this.wrapUp();if(e)Event.stop(e)},handleFormSubmission:function(e){var a=this._form;var b=$F(this._controls.editor);this.prepareSubmission();var c=this.options.callback(a,b)||'';if(Object.isString(c))c=c.toQueryParams();c.editorId=this.element.id;if(this.options.htmlResponse){var d=Object.extend({evalScripts:true},this.options.ajaxOptions);Object.extend(d,{parameters:c,onComplete:this._boundWrapperHandler,onFailure:this._boundFailureHandler});new Ajax.Updater({success:this.element},this.url,d)}else{var d=Object.extend({method:'get'},this.options.ajaxOptions);Object.extend(d,{parameters:c,onComplete:this._boundWrapperHandler,onFailure:this._boundFailureHandler});new Ajax.Request(this.url,d)}if(e)Event.stop(e)},leaveEditMode:function(){this.element.removeClassName(this.options.savingClassName);this.removeForm();this.leaveHover();this.element.style.backgroundColor=this._originalBackground;this.element.show();if(this.options.externalControl)this.options.externalControl.show();this._saving=false;this._editing=false;this._oldInnerHTML=null;this.triggerCallback('onLeaveEditMode')},leaveHover:function(e){if(this.options.hoverClassName)this.element.removeClassName(this.options.hoverClassName);if(this._saving)return;this.triggerCallback('onLeaveHover')},loadExternalText:function(){this._form.addClassName(this.options.loadingClassName);this._controls.editor.disabled=true;var c=Object.extend({method:'get'},this.options.ajaxOptions);Object.extend(c,{parameters:'editorId='+encodeURIComponent(this.element.id),onComplete:Prototype.emptyFunction,onSuccess:function(a){this._form.removeClassName(this.options.loadingClassName);var b=a.responseText;if(this.options.stripLoadedTextTags)b=b.stripTags();this._controls.editor.value=b;this._controls.editor.disabled=false;this.postProcessEditField()}.bind(this),onFailure:this._boundFailureHandler});new Ajax.Request(this.options.loadTextURL,c)},postProcessEditField:function(){var a=this.options.fieldPostCreation;if(a)$(this._controls.editor)['focus'==a?'focus':'activate']()},prepareOptions:function(){this.options=Object.clone(Ajax.InPlaceEditor.DefaultOptions);Object.extend(this.options,Ajax.InPlaceEditor.DefaultCallbacks);[this._extraDefaultOptions].flatten().compact().each(function(a){Object.extend(this.options,a)}.bind(this))},prepareSubmission:function(){this._saving=true;this.removeForm();this.leaveHover();this.showSaving()},registerListeners:function(){this._listeners={};var b;$H(Ajax.InPlaceEditor.Listeners).each(function(a){b=this[a.value].bind(this);this._listeners[a.key]=b;if(!this.options.externalControlOnly)this.element.observe(a.key,b);if(this.options.externalControl)this.options.externalControl.observe(a.key,b)}.bind(this))},removeForm:function(){if(!this._form)return;this._form.remove();this._form=null;this._controls={}},showSaving:function(){this._oldInnerHTML=this.element.innerHTML;this.element.innerHTML=this.options.savingText;this.element.addClassName(this.options.savingClassName);this.element.style.backgroundColor=this._originalBackground;this.element.show()},triggerCallback:function(a,b){if('function'==typeof this.options[a]){this.options[a](this,b)}},unregisterListeners:function(){$H(this._listeners).each(function(a){if(!this.options.externalControlOnly)this.element.stopObserving(a.key,a.value);if(this.options.externalControl)this.options.externalControl.stopObserving(a.key,a.value)}.bind(this))},wrapUp:function(a){this.leaveEditMode();this._boundComplete(a,this.element)}});Object.extend(Ajax.InPlaceEditor.prototype,{dispose:Ajax.InPlaceEditor.prototype.destroy});Ajax.InPlaceCollectionEditor=Class.create(Ajax.InPlaceEditor,{initialize:function($super,b,c,d){this._extraDefaultOptions=Ajax.InPlaceCollectionEditor.DefaultOptions;$super(b,c,d)},createEditField:function(){var a=document.createElement('select');a.name=this.options.paramName;a.size=1;this._controls.editor=a;this._collection=this.options.collection||[];if(this.options.loadCollectionURL)this.loadCollection();else this.checkForExternalText();this._form.appendChild(this._controls.editor)},loadCollection:function(){this._form.addClassName(this.options.loadingClassName);this.showLoadingText(this.options.loadingCollectionText);var c=Object.extend({method:'get'},this.options.ajaxOptions);Object.extend(c,{parameters:'editorId='+encodeURIComponent(this.element.id),onComplete:Prototype.emptyFunction,onSuccess:function(a){var b=a.responseText.strip();if(!/^\[.*\]$/.test(b))throw('Server returned an invalid collection representation.');this._collection=eval(b);this.checkForExternalText()}.bind(this),onFailure:this.onFailure});new Ajax.Request(this.options.loadCollectionURL,c)},showLoadingText:function(a){this._controls.editor.disabled=true;var b=this._controls.editor.firstChild;if(!b){b=document.createElement('option');b.value='';this._controls.editor.appendChild(b);b.selected=true}b.update((a||'').stripScripts().stripTags())},checkForExternalText:function(){this._text=this.getText();if(this.options.loadTextURL)this.loadExternalText();else this.buildOptionList()},loadExternalText:function(){this.showLoadingText(this.options.loadingText);var b=Object.extend({method:'get'},this.options.ajaxOptions);Object.extend(b,{parameters:'editorId='+encodeURIComponent(this.element.id),onComplete:Prototype.emptyFunction,onSuccess:function(a){this._text=a.responseText.strip();this.buildOptionList()}.bind(this),onFailure:this.onFailure});new Ajax.Request(this.options.loadTextURL,b)},buildOptionList:function(){this._form.removeClassName(this.options.loadingClassName);this._collection=this._collection.map(function(a){return 2===a.length?a:[a,a].flatten()});var c=('value'in this.options)?this.options.value:this._text;var d=this._collection.any(function(a){return a[0]==c}.bind(this));this._controls.editor.update('');var e;this._collection.each(function(a,b){e=document.createElement('option');e.value=a[0];e.selected=d?a[0]==c:0==b;e.appendChild(document.createTextNode(a[1]));this._controls.editor.appendChild(e)}.bind(this));this._controls.editor.disabled=false;Field.scrollFreeActivate(this._controls.editor)}});Ajax.InPlaceEditor.prototype.initialize.dealWithDeprecatedOptions=function(c){if(!c)return;function fallback(a,b){if(a in c||b===undefined)return;c[a]=b};fallback('cancelControl',(c.cancelLink?'link':(c.cancelButton?'button':c.cancelLink==c.cancelButton==false?false:undefined)));fallback('okControl',(c.okLink?'link':(c.okButton?'button':c.okLink==c.okButton==false?false:undefined)));fallback('highlightColor',c.highlightcolor);fallback('highlightEndColor',c.highlightendcolor)};Object.extend(Ajax.InPlaceEditor,{DefaultOptions:{ajaxOptions:{},autoRows:3,cancelControl:'link',cancelText:'cancel',clickToEditText:'Click to edit',externalControl:null,externalControlOnly:false,fieldPostCreation:'activate',formClassName:'inplaceeditor-form',formId:null,highlightColor:'#ffff99',highlightEndColor:'#ffffff',hoverClassName:'',htmlResponse:true,loadingClassName:'inplaceeditor-loading',loadingText:'Loading...',okControl:'button',okText:'ok',paramName:'value',rows:1,savingClassName:'inplaceeditor-saving',savingText:'Saving...',size:0,stripLoadedTextTags:false,submitOnBlur:false,textAfterControls:'',textBeforeControls:'',textBetweenControls:''},DefaultCallbacks:{callback:function(a){return Form.serialize(a)},onComplete:function(a,b){new Effect.Highlight(b,{startcolor:this.options.highlightColor,keepBackgroundImage:true})},onEnterEditMode:null,onEnterHover:function(a){a.element.style.backgroundColor=a.options.highlightColor;if(a._effect)a._effect.cancel()},onFailure:function(a,b){alert('Error communication with the server: '+a.responseText.stripTags())},onFormCustomization:null,onLeaveEditMode:null,onLeaveHover:function(a){a._effect=new Effect.Highlight(a.element,{startcolor:a.options.highlightColor,endcolor:a.options.highlightEndColor,restorecolor:a._originalBackground,keepBackgroundImage:true})}},Listeners:{click:'enterEditMode',keydown:'checkForEscapeOrReturn',mouseover:'enterHover',mouseout:'leaveHover'}});Ajax.InPlaceCollectionEditor.DefaultOptions={loadingCollectionText:'Loading options...'};Form.Element.DelayedObserver=Class.create({initialize:function(a,b,c){this.delay=b||0.5;this.element=$(a);this.callback=c;this.timer=null;this.lastValue=$F(this.element);Event.observe(this.element,'keyup',this.delayedListener.bindAsEventListener(this))},delayedListener:function(a){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))}});
//slider.js
if(!Control)var Control={};Control.Slider=Class.create({initialize:function(a,b,c){var d=this;if(Object.isArray(a)){this.handles=a.collect(function(e){return $(e)})}else{this.handles=[$(a)]}this.track=$(b);this.options=c||{};this.axis=this.options.axis||'horizontal';this.increment=this.options.increment||1;this.step=parseInt(this.options.step||'1');this.range=this.options.range||$R(0,1);this.value=0;this.values=this.handles.map(function(){return 0});this.spans=this.options.spans?this.options.spans.map(function(s){return $(s)}):false;this.options.startSpan=$(this.options.startSpan||null);this.options.endSpan=$(this.options.endSpan||null);this.restricted=this.options.restricted||false;this.maximum=this.options.maximum||this.range.end;this.minimum=this.options.minimum||this.range.start;this.alignX=parseInt(this.options.alignX||'0');this.alignY=parseInt(this.options.alignY||'0');this.trackLength=this.maximumOffset()-this.minimumOffset();this.handleLength=this.isVertical()?(this.handles[0].offsetHeight!=0?this.handles[0].offsetHeight:this.handles[0].style.height.replace(/px$/,"")):(this.handles[0].offsetWidth!=0?this.handles[0].offsetWidth:this.handles[0].style.width.replace(/px$/,""));this.active=false;this.dragging=false;this.disabled=false;if(this.options.disabled)this.setDisabled();this.allowedValues=this.options.values?this.options.values.sortBy(Prototype.K):false;if(this.allowedValues){this.minimum=this.allowedValues.min();this.maximum=this.allowedValues.max()}this.eventMouseDown=this.startDrag.bindAsEventListener(this);this.eventMouseUp=this.endDrag.bindAsEventListener(this);this.eventMouseMove=this.update.bindAsEventListener(this);this.handles.each(function(h,i){i=d.handles.length-1-i;d.setValue(parseFloat((Object.isArray(d.options.sliderValue)?d.options.sliderValue[i]:d.options.sliderValue)||d.range.start),i);h.makePositioned().observe("mousedown",d.eventMouseDown)});this.track.observe("mousedown",this.eventMouseDown);document.observe("mouseup",this.eventMouseUp);document.observe("mousemove",this.eventMouseMove);this.initialized=true},dispose:function(){var a=this;Event.stopObserving(this.track,"mousedown",this.eventMouseDown);Event.stopObserving(document,"mouseup",this.eventMouseUp);Event.stopObserving(document,"mousemove",this.eventMouseMove);this.handles.each(function(h){Event.stopObserving(h,"mousedown",a.eventMouseDown)})},setDisabled:function(){this.disabled=true},setEnabled:function(){this.disabled=false},getNearestValue:function(b){if(this.allowedValues){if(b>=this.allowedValues.max())return(this.allowedValues.max());if(b<=this.allowedValues.min())return(this.allowedValues.min());var c=Math.abs(this.allowedValues[0]-b);var d=this.allowedValues[0];this.allowedValues.each(function(v){var a=Math.abs(v-b);if(a<=c){d=v;c=a}});return d}if(b>this.range.end)return this.range.end;if(b<this.range.start)return this.range.start;return b},setValue:function(a,b){if(!this.active){this.activeHandleIdx=b||0;this.activeHandle=this.handles[this.activeHandleIdx];this.updateStyles()}b=b||this.activeHandleIdx||0;if(this.initialized&&this.restricted){if((b>0)&&(a<this.values[b-1]))a=this.values[b-1];if((b<(this.handles.length-1))&&(a>this.values[b+1]))a=this.values[b+1]}a=this.getNearestValue(a);this.values[b]=a;this.value=this.values[0];this.handles[b].style[this.isVertical()?'top':'left']=this.translateToPx(a);this.drawSpans();if(!this.dragging||!this.event)this.updateFinished()},setValueBy:function(a,b){this.setValue(this.values[b||this.activeHandleIdx||0]+a,b||this.activeHandleIdx||0)},translateToPx:function(a){return Math.round(((this.trackLength-this.handleLength)/(this.range.end-this.range.start))*(a-this.range.start))+"px"},translateToValue:function(a){return((a/(this.trackLength-this.handleLength)*(this.range.end-this.range.start))+this.range.start)},getRange:function(a){var v=this.values.sortBy(Prototype.K);a=a||0;return $R(v[a],v[a+1])},minimumOffset:function(){return(this.isVertical()?this.alignY:this.alignX)},maximumOffset:function(){return(this.isVertical()?(this.track.offsetHeight!=0?this.track.offsetHeight:this.track.style.height.replace(/px$/,""))-this.alignY:(this.track.offsetWidth!=0?this.track.offsetWidth:this.track.style.width.replace(/px$/,""))-this.alignX)},isVertical:function(){return(this.axis=='vertical')},drawSpans:function(){var a=this;if(this.spans)$R(0,this.spans.length-1).each(function(r){a.setSpan(a.spans[r],a.getRange(r))});if(this.options.startSpan)this.setSpan(this.options.startSpan,$R(0,this.values.length>1?this.getRange(0).min():this.value));if(this.options.endSpan)this.setSpan(this.options.endSpan,$R(this.values.length>1?this.getRange(this.spans.length-1).max():this.value,this.maximum))},setSpan:function(a,b){if(this.isVertical()){a.style.top=this.translateToPx(b.start);a.style.height=this.translateToPx(b.end-b.start+this.range.start)}else{a.style.left=this.translateToPx(b.start);a.style.width=this.translateToPx(b.end-b.start+this.range.start)}},updateStyles:function(){this.handles.each(function(h){Element.removeClassName(h,'selected')});Element.addClassName(this.activeHandle,'selected')},startDrag:function(a){if(Event.isLeftClick(a)){if(!this.disabled){this.active=true;var b=Event.element(a);var c=[Event.pointerX(a),Event.pointerY(a)];var d=b;if(d==this.track){var e=Position.cumulativeOffset(this.track);this.event=a;this.setValue(this.translateToValue((this.isVertical()?c[1]-e[1]:c[0]-e[0])-(this.handleLength/2)));var e=Position.cumulativeOffset(this.activeHandle);this.offsetX=(c[0]-e[0]);this.offsetY=(c[1]-e[1])}else{while((this.handles.indexOf(b)==-1)&&b.parentNode)b=b.parentNode;if(this.handles.indexOf(b)!=-1){this.activeHandle=b;this.activeHandleIdx=this.handles.indexOf(this.activeHandle);this.updateStyles();var e=Position.cumulativeOffset(this.activeHandle);this.offsetX=(c[0]-e[0]);this.offsetY=(c[1]-e[1])}}}Event.stop(a)}},update:function(a){if(this.active){if(!this.dragging)this.dragging=true;this.draw(a);if(Prototype.Browser.WebKit)window.scrollBy(0,0);Event.stop(a)}},draw:function(a){var b=[Event.pointerX(a),Event.pointerY(a)];var c=Position.cumulativeOffset(this.track);b[0]-=this.offsetX+c[0];b[1]-=this.offsetY+c[1];this.event=a;this.setValue(this.translateToValue(this.isVertical()?b[1]:b[0]));if(this.initialized&&this.options.onSlide)this.options.onSlide(this.values.length>1?this.values:this.value,this)},endDrag:function(a){if(this.active&&this.dragging){this.finishDrag(a,true);Event.stop(a)}this.active=false;this.dragging=false},finishDrag:function(a,b){this.active=false;this.dragging=false;this.updateFinished()},updateFinished:function(){if(this.initialized&&this.options.onChange)this.options.onChange(this.values.length>1?this.values:this.value,this);this.event=null}});
//sound.js
Sound={tracks:{},_enabled:true,template:new Template('<embed style="height:0" id="sound_#{track}_#{id}" src="#{url}" loop="false" autostart="true" hidden="true"/>'),enable:function(){Sound._enabled=true},disable:function(){Sound._enabled=false},play:function(c){if(!Sound._enabled)return;var d=Object.extend({track:'global',url:c,replace:false},arguments[1]||{});if(d.replace&&this.tracks[d.track]){$R(0,this.tracks[d.track].id).each(function(a){var b=$('sound_'+d.track+'_'+a);b.Stop&&b.Stop();b.remove()});this.tracks[d.track]=null}if(!this.tracks[d.track])this.tracks[d.track]={id:0};else this.tracks[d.track].id++;d.id=this.tracks[d.track].id;$$('body')[0].insert(Prototype.Browser.IE?new Element('bgsound',{id:'sound_'+d.track+'_'+d.id,src:d.url,loop:1,autostart:true}):Sound.template.evaluate(d))}};if(Prototype.Browser.Gecko&&navigator.userAgent.indexOf("Win")>0){if(navigator.plugins&&$A(navigator.plugins).detect(function(p){return p.name.indexOf('QuickTime')!=-1}))Sound.template=new Template('<object id="sound_#{track}_#{id}" width="0" height="0" type="audio/mpeg" data="#{url}"/>');else Sound.play=function(){}}
//load additional files
Scriptaculous.load();// Copyright (c) 2006 SĂŠbastien Gruhier (http://xilinus.com, http://itseb.com)
// 
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
// 
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// VERSION 1.3

var Window = Class.create();

Window.keepMultiModalWindow = false;
Window.hasEffectLib = (typeof Effect != 'undefined');
Window.resizeEffectDuration = 0.4;

Window.prototype = {
  // Constructor
  // Available parameters : className, blurClassName, title, minWidth, minHeight, maxWidth, maxHeight, width, height, top, left, bottom, right, resizable, zIndex, opacity, recenterAuto, wiredDrag
  //                        hideEffect, showEffect, showEffectOptions, hideEffectOptions, effectOptions, url, draggable, closable, minimizable, maximizable, parent, onload
  //                        add all callbacks (if you do not use an observer)
  //                        onDestroy onStartResize onStartMove onResize onMove onEndResize onEndMove onFocus onBlur onBeforeShow onShow onHide onMinimize onMaximize onClose
  
  initialize: function() {
    var id;
    var optionIndex = 0;
    // For backward compatibility like win= new Window("id", {...}) instead of win = new Window({id: "id", ...})
    if (arguments.length > 0) {
      if (typeof arguments[0] == "string" ) {
        id = arguments[0];
        optionIndex = 1;
      }
      else
        id = arguments[0] ? arguments[0].id : null;
    }
    
    // Generate unique ID if not specified
    if (!id)
      id = "window_" + new Date().getTime();
      
    if ($(id))
      alert("Window " + id + " is already registered in the DOM! Make sure you use setDestroyOnClose() or destroyOnClose: true in the constructor");

    this.options = Object.extend({
      className:         "dialog",
      blurClassName:     null,
      minWidth:          100, 
      minHeight:         20,
      resizable:         true,
      closable:          true,
      minimizable:       true,
      maximizable:       true,
      draggable:         true,
      userData:          null,
      showEffect:        (Window.hasEffectLib ? Effect.Appear : Element.show),
      hideEffect:        (Window.hasEffectLib ? Effect.Fade : Element.hide),
      showEffectOptions: {},
      hideEffectOptions: {},
      effectOptions:     null,
      parent:            document.body,
      title:             "&nbsp;",
      url:               null,
      onload:            Prototype.emptyFunction,
      width:             200,
      height:            300,
      opacity:           1,
      recenterAuto:      true,
      wiredDrag:         false,
      closeCallback:     null,
      destroyOnClose:    false,
      gridX:             1, 
      gridY:             1      
    }, arguments[optionIndex] || {});
    if (this.options.blurClassName)
      this.options.focusClassName = this.options.className;
      
    if (typeof this.options.top == "undefined" &&  typeof this.options.bottom ==  "undefined") 
      this.options.top = this._round(Math.random()*500, this.options.gridY);
    if (typeof this.options.left == "undefined" &&  typeof this.options.right ==  "undefined") 
      this.options.left = this._round(Math.random()*500, this.options.gridX);

    if (this.options.effectOptions) {
      Object.extend(this.options.hideEffectOptions, this.options.effectOptions);
      Object.extend(this.options.showEffectOptions, this.options.effectOptions);
      if (this.options.showEffect == Element.Appear)
        this.options.showEffectOptions.to = this.options.opacity;
    }
    if (Window.hasEffectLib) {
      if (this.options.showEffect == Effect.Appear)
        this.options.showEffectOptions.to = this.options.opacity;
    
      if (this.options.hideEffect == Effect.Fade)
        this.options.hideEffectOptions.from = this.options.opacity;
    }
    if (this.options.hideEffect == Element.hide)
      this.options.hideEffect = function(){ Element.hide(this.element); if (this.options.destroyOnClose) this.destroy(); }.bind(this)
    
    if (this.options.parent != document.body)  
      this.options.parent = $(this.options.parent);
      
    this.element = this._createWindow(id);       
    this.element.win = this;
    
    // Bind event listener
    this.eventMouseDown = this._initDrag.bindAsEventListener(this);
    this.eventMouseUp   = this._endDrag.bindAsEventListener(this);
    this.eventMouseMove = this._updateDrag.bindAsEventListener(this);
    this.eventOnLoad    = this._getWindowBorderSize.bindAsEventListener(this);
    this.eventMouseDownContent = this.toFront.bindAsEventListener(this);
    this.eventResize = this._recenter.bindAsEventListener(this);
 
    this.topbar = $(this.element.id + "_top");
    this.bottombar = $(this.element.id + "_bottom");
    this.content = $(this.element.id + "_content");
    
    Event.observe(this.topbar, "mousedown", this.eventMouseDown);
    Event.observe(this.bottombar, "mousedown", this.eventMouseDown);
    Event.observe(this.content, "mousedown", this.eventMouseDownContent);
    Event.observe(window, "load", this.eventOnLoad);
    Event.observe(window, "resize", this.eventResize);
    Event.observe(window, "scroll", this.eventResize);
    Event.observe(this.options.parent, "scroll", this.eventResize);
    
    if (this.options.draggable)  {
      var that = this;
      [this.topbar, this.topbar.up().previous(), this.topbar.up().next()].each(function(element) {
        element.observe("mousedown", that.eventMouseDown);
        element.addClassName("top_draggable");
      });
      [this.bottombar.up(), this.bottombar.up().previous(), this.bottombar.up().next()].each(function(element) {
        element.observe("mousedown", that.eventMouseDown);
        element.addClassName("bottom_draggable");
      });
      
    }    
    
    if (this.options.resizable) {
      this.sizer = $(this.element.id + "_sizer");
      Event.observe(this.sizer, "mousedown", this.eventMouseDown);
    }  
    
    this.useLeft = null;
    this.useTop = null;
    if (typeof this.options.left != "undefined") {
      this.element.setStyle({left: parseFloat(this.options.left) + 'px'});
      this.useLeft = true;
    }
    else {
      this.element.setStyle({right: parseFloat(this.options.right) + 'px'});
      this.useLeft = false;
    }
    
    if (typeof this.options.top != "undefined") {
      this.element.setStyle({top: parseFloat(this.options.top) + 'px'});
      this.useTop = true;
    }
    else {
      this.element.setStyle({bottom: parseFloat(this.options.bottom) + 'px'});      
      this.useTop = false;
    }
      
    this.storedLocation = null;
    
    this.setOpacity(this.options.opacity);
    if (this.options.zIndex)
      this.setZIndex(this.options.zIndex)

    if (this.options.destroyOnClose)
      this.setDestroyOnClose(true);

    this._getWindowBorderSize();
    this.width = this.options.width;
    this.height = this.options.height;
    this.visible = false;
    
    this.constraint = false;
    this.constraintPad = {top: 0, left:0, bottom:0, right:0};
    
    if (this.width && this.height)
      this.setSize(this.options.width, this.options.height);
    this.setTitle(this.options.title)
    Windows.register(this);      
  },
  
  // Destructor
  destroy: function() {
    this._notify("onDestroy");
    Event.stopObserving(this.topbar, "mousedown", this.eventMouseDown);
    Event.stopObserving(this.bottombar, "mousedown", this.eventMouseDown);
    Event.stopObserving(this.content, "mousedown", this.eventMouseDownContent);
    
    Event.stopObserving(window, "load", this.eventOnLoad);
    Event.stopObserving(window, "resize", this.eventResize);
    Event.stopObserving(window, "scroll", this.eventResize);
    
    Event.stopObserving(this.content, "load", this.options.onload);

    if (this._oldParent) {
      var content = this.getContent();
      var originalContent = null;
      for(var i = 0; i < content.childNodes.length; i++) {
        originalContent = content.childNodes[i];
        if (originalContent.nodeType == 1) 
          break;
        originalContent = null;
      }
      if (originalContent)
        this._oldParent.appendChild(originalContent);
      this._oldParent = null;
    }

    if (this.sizer)
        Event.stopObserving(this.sizer, "mousedown", this.eventMouseDown);

    if (this.options.url) 
      this.content.src = null

     if(this.iefix) 
      Element.remove(this.iefix);

    Element.remove(this.element);
    Windows.unregister(this);      
  },
    
  // Sets close callback, if it sets, it should return true to be able to close the window.
  setCloseCallback: function(callback) {
    this.options.closeCallback = callback;
  },
  
  // Gets window content
  getContent: function () {
    return this.content;
  },
  
  // Sets the content with an element id
  setContent: function(id, autoresize, autoposition) {
    var element = $(id);
    if (null == element) throw "Unable to find element '" + id + "' in DOM";
    this._oldParent = element.parentNode;

    var d = null;
    var p = null;

    if (autoresize) 
      d = Element.getDimensions(element);
    if (autoposition) 
      p = Position.cumulativeOffset(element);

    var content = this.getContent();
    // Clear HTML (and even iframe)
    this.setHTMLContent("");
    content = this.getContent();
    
    content.appendChild(element);
    element.show();
    if (autoresize) 
      this.setSize(d.width, d.height);
    if (autoposition) 
      this.setLocation(p[1] - this.heightN, p[0] - this.widthW);    
  },
  
  setHTMLContent: function(html) {
    // It was an url (iframe), recreate a div content instead of iframe content
    if (this.options.url) {
      this.content.src = null;
      this.options.url = null;
      
  	  var content ="<div id=\"" + this.getId() + "_content\" class=\"" + this.options.className + "_content\"> </div>";
      $(this.getId() +"_table_content").innerHTML = content;
      
      this.content = $(this.element.id + "_content");
    }
      
    this.getContent().innerHTML = html;
  },
  
  setAjaxContent: function(url, options, showCentered, showModal) {
    this.showFunction = showCentered ? "showCenter" : "show";
    this.showModal = showModal || false;
  
    options = options || {};

    // Clear HTML (and even iframe)
    this.setHTMLContent("");
 
    this.onComplete = options.onComplete;
    if (! this._onCompleteHandler)
      this._onCompleteHandler = this._setAjaxContent.bind(this);
    options.onComplete = this._onCompleteHandler;

    new Ajax.Request(url, options);    
    options.onComplete = this.onComplete;
  },
  
  _setAjaxContent: function(originalRequest) {
    Element.update(this.getContent(), originalRequest.responseText);
    if (this.onComplete)
      this.onComplete(originalRequest);
    this.onComplete = null;
    this[this.showFunction](this.showModal)
  },
  
  setURL: function(url) {
    // Not an url content, change div to iframe
    if (this.options.url) 
      this.content.src = null;
    this.options.url = url;
    var content= "<iframe frameborder='0' name='" + this.getId() + "_content'  id='" + this.getId() + "_content' src='" + url + "' width='" + this.width + "' height='" + this.height + "'> </iframe>";
    $(this.getId() +"_table_content").innerHTML = content;
    
    this.content = $(this.element.id + "_content");
  },

  getURL: function() {
  	return this.options.url ? this.options.url : null;
  },

  refresh: function() {
    if (this.options.url)
	    $(this.element.getAttribute('id') + '_content').src = this.options.url;
  },
  
  // Stores position/size in a cookie, by default named with window id
  setCookie: function(name, expires, path, domain, secure) {
    name = name || this.element.id;
    this.cookie = [name, expires, path, domain, secure];
    
    // Get cookie
    var value = WindowUtilities.getCookie(name)
    // If exists
    if (value) {
      var values = value.split(',');
      var x = values[0].split(':');
      var y = values[1].split(':');

      var w = parseFloat(values[2]), h = parseFloat(values[3]);
      var mini = values[4];
      var maxi = values[5];

      this.setSize(w, h);
      if (mini == "true")
        this.doMinimize = true; // Minimize will be done at onload window event
      else if (maxi == "true")
        this.doMaximize = true; // Maximize will be done at onload window event

      this.useLeft = x[0] == "l";
      this.useTop = y[0] == "t";

      this.element.setStyle(this.useLeft ? {left: x[1]} : {right: x[1]});
      this.element.setStyle(this.useTop ? {top: y[1]} : {bottom: y[1]});
    }
  },
  
  // Gets window ID
  getId: function() {
    return this.element.id;
  },
  
  // Detroys itself when closing 
  setDestroyOnClose: function() {
    this.options.destroyOnClose = true;
  },
  
  setConstraint: function(bool, padding) {
    this.constraint = bool;
    this.constraintPad = Object.extend(this.constraintPad, padding || {});
    // Reset location to apply constraint
    if (this.useTop && this.useLeft)
      this.setLocation(parseFloat(this.element.style.top), parseFloat(this.element.style.left));
  },
  
  // initDrag event

  _initDrag: function(event) {
    // No resize on minimized window
    if (Event.element(event) == this.sizer && this.isMinimized())
      return;

    // No move on maximzed window
    if (Event.element(event) != this.sizer && this.isMaximized())
      return;
      
    if (Prototype.Browser.IE && this.heightN == 0)
      this._getWindowBorderSize();
    
    // Get pointer X,Y
    this.pointer = [this._round(Event.pointerX(event), this.options.gridX), this._round(Event.pointerY(event), this.options.gridY)];
    if (this.options.wiredDrag) 
      this.currentDrag = this._createWiredElement();
    else
      this.currentDrag = this.element;
      
    // Resize
    if (Event.element(event) == this.sizer) {
      this.doResize = true;
      this.widthOrg = this.width;
      this.heightOrg = this.height;
      this.bottomOrg = parseFloat(this.element.getStyle('bottom'));
      this.rightOrg = parseFloat(this.element.getStyle('right'));
      this._notify("onStartResize");
    }
    else {
      this.doResize = false;

      // Check if click on close button, 
      var closeButton = $(this.getId() + '_close');
      if (closeButton && Position.within(closeButton, this.pointer[0], this.pointer[1])) {
        this.currentDrag = null;
        return;
      }

      this.toFront();

      if (! this.options.draggable) 
        return;
      this._notify("onStartMove");
    }    
    // Register global event to capture mouseUp and mouseMove
    Event.observe(document, "mouseup", this.eventMouseUp, false);
    Event.observe(document, "mousemove", this.eventMouseMove, false);
    
    // Add an invisible div to keep catching mouse event over iframes
    WindowUtilities.disableScreen('__invisible__', '__invisible__', this.overlayOpacity);

    // Stop selection while dragging
    document.body.ondrag = function () { return false; };
    document.body.onselectstart = function () { return false; };
    
    this.currentDrag.show();
    Event.stop(event);
  },
  
  _round: function(val, round) {
    return round == 1 ? val  : val = Math.floor(val / round) * round;
  },

  // updateDrag event
  _updateDrag: function(event) {
    var pointer =  [this._round(Event.pointerX(event), this.options.gridX), this._round(Event.pointerY(event), this.options.gridY)];  
    var dx = pointer[0] - this.pointer[0];
    var dy = pointer[1] - this.pointer[1];
    
    // Resize case, update width/height
    if (this.doResize) {
      var w = this.widthOrg + dx;
      var h = this.heightOrg + dy;
      
      dx = this.width - this.widthOrg
      dy = this.height - this.heightOrg
      
      // Check if it's a right position, update it to keep upper-left corner at the same position
      if (this.useLeft) 
        w = this._updateWidthConstraint(w)
      else 
        this.currentDrag.setStyle({right: (this.rightOrg -dx) + 'px'});
      // Check if it's a bottom position, update it to keep upper-left corner at the same position
      if (this.useTop) 
        h = this._updateHeightConstraint(h)
      else
        this.currentDrag.setStyle({bottom: (this.bottomOrg -dy) + 'px'});
        
      this.setSize(w , h);
      this._notify("onResize");
    }
    // Move case, update top/left
    else {
      this.pointer = pointer;
      
      if (this.useLeft) {
        var left =  parseFloat(this.currentDrag.getStyle('left')) + dx;
        var newLeft = this._updateLeftConstraint(left);
        // Keep mouse pointer correct
        this.pointer[0] += newLeft-left;
        this.currentDrag.setStyle({left: newLeft + 'px'});
      }
      else 
        this.currentDrag.setStyle({right: parseFloat(this.currentDrag.getStyle('right')) - dx + 'px'});
      
      if (this.useTop) {
        var top =  parseFloat(this.currentDrag.getStyle('top')) + dy;
        var newTop = this._updateTopConstraint(top);
        // Keep mouse pointer correct
        this.pointer[1] += newTop - top;
        this.currentDrag.setStyle({top: newTop + 'px'});
      }
      else 
        this.currentDrag.setStyle({bottom: parseFloat(this.currentDrag.getStyle('bottom')) - dy + 'px'});

      this._notify("onMove");
    }
    if (this.iefix) 
      this._fixIEOverlapping(); 
      
    this._removeStoreLocation();
    Event.stop(event);
  },

   // endDrag callback
   _endDrag: function(event) {
    // Remove temporary div over iframes
     WindowUtilities.enableScreen('__invisible__');
    
    if (this.doResize)
      this._notify("onEndResize");
    else
      this._notify("onEndMove");
    
    // Release event observing
    Event.stopObserving(document, "mouseup", this.eventMouseUp,false);
    Event.stopObserving(document, "mousemove", this.eventMouseMove, false);

    Event.stop(event);
    
    this._hideWiredElement();

    // Store new location/size if need be
    this._saveCookie()
      
    // Restore selection
    document.body.ondrag = null;
    document.body.onselectstart = null;
  },

  _updateLeftConstraint: function(left) {
    if (this.constraint && this.useLeft && this.useTop) {
      var width = this.options.parent == document.body ? WindowUtilities.getPageSize().windowWidth : this.options.parent.getDimensions().width;

      if (left < this.constraintPad.left)
        left = this.constraintPad.left;
      if (left + this.width + this.widthE + this.widthW > width - this.constraintPad.right) 
        left = width - this.constraintPad.right - this.width - this.widthE - this.widthW;
    }
    return left;
  },
  
  _updateTopConstraint: function(top) {
    if (this.constraint && this.useLeft && this.useTop) {        
      var height = this.options.parent == document.body ? WindowUtilities.getPageSize().windowHeight : this.options.parent.getDimensions().height;
      
      var h = this.height + this.heightN + this.heightS;

      if (top < this.constraintPad.top)
        top = this.constraintPad.top;
      if (top + h > height - this.constraintPad.bottom) 
        top = height - this.constraintPad.bottom - h;
    }
    return top;
  },
  
  _updateWidthConstraint: function(w) {
    if (this.constraint && this.useLeft && this.useTop) {
      var width = this.options.parent == document.body ? WindowUtilities.getPageSize().windowWidth : this.options.parent.getDimensions().width;
      var left =  parseFloat(this.element.getStyle("left"));

      if (left + w + this.widthE + this.widthW > width - this.constraintPad.right) 
        w = width - this.constraintPad.right - left - this.widthE - this.widthW;
    }
    return w;
  },
  
  _updateHeightConstraint: function(h) {
    if (this.constraint && this.useLeft && this.useTop) {
      var height = this.options.parent == document.body ? WindowUtilities.getPageSize().windowHeight : this.options.parent.getDimensions().height;
      var top =  parseFloat(this.element.getStyle("top"));

      if (top + h + this.heightN + this.heightS > height - this.constraintPad.bottom) 
        h = height - this.constraintPad.bottom - top - this.heightN - this.heightS;
    }
    return h;
  },
  
  
  // Creates HTML window code
  _createWindow: function(id) {
    var className = this.options.className;
    var win = document.createElement("div");
    win.setAttribute('id', id);
    win.className = "dialog";

    var content;
    if (this.options.url)
      content= "<iframe frameborder=\"0\" name=\"" + id + "_content\"  id=\"" + id + "_content\" src=\"" + this.options.url + "\"> </iframe>";
    else
      content ="<div id=\"" + id + "_content\" class=\"" +className + "_content\"> </div>";

    var closeDiv = this.options.closable ? "<div class='"+ className +"_close' id='"+ id +"_close' onclick='Windows.close(\""+ id +"\", event)'> </div>" : "";
    var minDiv = this.options.minimizable ? "<div class='"+ className + "_minimize' id='"+ id +"_minimize' onclick='Windows.minimize(\""+ id +"\", event)'> </div>" : "";
    var maxDiv = this.options.maximizable ? "<div class='"+ className + "_maximize' id='"+ id +"_maximize' onclick='Windows.maximize(\""+ id +"\", event)'> </div>" : "";
    var seAttributes = this.options.resizable ? "class='" + className + "_sizer' id='" + id + "_sizer'" : "class='"  + className + "_se'";
    var blank = "../themes/default/blank.gif";
    
    win.innerHTML = closeDiv + minDiv + maxDiv + "\
      <table id='"+ id +"_row1' class=\"top table_window\">\
        <tr>\
          <td class='"+ className +"_nw'></td>\
          <td class='"+ className +"_n'><div id='"+ id +"_top' class='"+ className +"_title title_window'>"+ this.options.title +"</div></td>\
          <td class='"+ className +"_ne'></td>\
        </tr>\
      </table>\
      <table id='"+ id +"_row2' class=\"mid table_window\">\
        <tr>\
          <td class='"+ className +"_w'></td>\
            <td id='"+ id +"_table_content' class='"+ className +"_content' valign='top'>" + content + "</td>\
          <td class='"+ className +"_e'></td>\
        </tr>\
      </table>\
        <table id='"+ id +"_row3' class=\"bot table_window\">\
        <tr>\
          <td class='"+ className +"_sw'></td>\
            <td class='"+ className +"_s'><div id='"+ id +"_bottom' class='status_bar'><span style='float:left; width:1px; height:1px'></span></div></td>\
            <td " + seAttributes + "></td>\
        </tr>\
      </table>\
    ";
    Element.hide(win);
    this.options.parent.insertBefore(win, this.options.parent.firstChild);
    Event.observe($(id + "_content"), "load", this.options.onload);
    return win;
  },
  
  
  changeClassName: function(newClassName) {    
    var className = this.options.className;
    var id = this.getId();
    $A(["_close", "_minimize", "_maximize", "_sizer", "_content"]).each(function(value) { this._toggleClassName($(id + value), className + value, newClassName + value) }.bind(this));
    this._toggleClassName($(id + "_top"), className + "_title", newClassName + "_title");
    $$("#" + id + " td").each(function(td) {td.className = td.className.sub(className,newClassName); });
    this.options.className = newClassName;
  },
  
  _toggleClassName: function(element, oldClassName, newClassName) { 
    if (element) {
      element.removeClassName(oldClassName);
      element.addClassName(newClassName);
    }
  },
  
  // Sets window location
  setLocation: function(top, left) {
    top = this._updateTopConstraint(top);
    left = this._updateLeftConstraint(left);

    var e = this.currentDrag || this.element;
    e.setStyle({top: top + 'px'});
    e.setStyle({left: left + 'px'});

    this.useLeft = true;
    this.useTop = true;
  },
    
  getLocation: function() {
    var location = {};
    if (this.useTop)
      location = Object.extend(location, {top: this.element.getStyle("top")});
    else
      location = Object.extend(location, {bottom: this.element.getStyle("bottom")});
    if (this.useLeft)
      location = Object.extend(location, {left: this.element.getStyle("left")});
    else
      location = Object.extend(location, {right: this.element.getStyle("right")});
    
    return location;
  },
  
  // Gets window size
  getSize: function() {
    return {width: this.width, height: this.height};
  },
    
  // Sets window size
  setSize: function(width, height, useEffect) {    
    width = parseFloat(width);
    height = parseFloat(height);
    
    // Check min and max size
    if (!this.minimized && width < this.options.minWidth)
      width = this.options.minWidth;

    if (!this.minimized && height < this.options.minHeight)
      height = this.options.minHeight;
      
    if (this.options. maxHeight && height > this.options. maxHeight)
      height = this.options. maxHeight;

    if (this.options. maxWidth && width > this.options. maxWidth)
      width = this.options. maxWidth;

    
    if (this.useTop && this.useLeft && Window.hasEffectLib && Effect.ResizeWindow && useEffect) {
      new Effect.ResizeWindow(this, null, null, width, height, {duration: Window.resizeEffectDuration});
    } else {
      this.width = width;
      this.height = height;
      var e = this.currentDrag ? this.currentDrag : this.element;

      e.setStyle({width: width + this.widthW + this.widthE + "px"})
      e.setStyle({height: height  + this.heightN + this.heightS + "px"})

      // Update content size
      if (!this.currentDrag || this.currentDrag == this.element) {
        var content = $(this.element.id + '_content');
        content.setStyle({height: height  + 'px'});
        content.setStyle({width: width  + 'px'});
      }
    }
  },
  
  updateHeight: function() {
    this.setSize(this.width, this.content.scrollHeight, true);
  },
  
  updateWidth: function() {
    this.setSize(this.content.scrollWidth, this.height, true);
  },
  
  // Brings window to front
  toFront: function() {
    if (this.element.style.zIndex < Windows.maxZIndex)  
      this.setZIndex(Windows.maxZIndex + 1);
    if (this.iefix) 
      this._fixIEOverlapping(); 
  },
   
  getBounds: function(insideOnly) {
    if (! this.width || !this.height || !this.visible)  
      this.computeBounds();
    var w = this.width;
    var h = this.height;

    if (!insideOnly) {
      w += this.widthW + this.widthE;
      h += this.heightN + this.heightS;
    }
    var bounds = Object.extend(this.getLocation(), {width: w + "px", height: h + "px"});
    return bounds;
  },
      
  computeBounds: function() {
     if (! this.width || !this.height) {
      var size = WindowUtilities._computeSize(this.content.innerHTML, this.content.id, this.width, this.height, 0, this.options.className)
      if (this.height)
        this.width = size + 5
      else
        this.height = size + 5
    }

    this.setSize(this.width, this.height);
    if (this.centered)
      this._center(this.centerTop, this.centerLeft);    
  },
  
  // Displays window modal state or not
  show: function(modal) {
    this.visible = true;
    if (modal) {
      // Hack for Safari !!
      if (typeof this.overlayOpacity == "undefined") {
        var that = this;
        setTimeout(function() {that.show(modal)}, 10);
        return;
      }
      Windows.addModalWindow(this);
      
      this.modal = true;      
      this.setZIndex(Windows.maxZIndex + 1);
      Windows.unsetOverflow(this);
    }
    else    
      if (!this.element.style.zIndex) 
        this.setZIndex(Windows.maxZIndex + 1);        
      
    // To restore overflow if need be
    if (this.oldStyle)
      this.getContent().setStyle({overflow: this.oldStyle});
      
    this.computeBounds();
    
    this._notify("onBeforeShow");   
    if (this.options.showEffect != Element.show && this.options.showEffectOptions)
      this.options.showEffect(this.element, this.options.showEffectOptions);  
    else
      this.options.showEffect(this.element);  
      
    this._checkIEOverlapping();
    WindowUtilities.focusedWindow = this
    this._notify("onShow");   
  },
  
  // Displays window modal state or not at the center of the page
  showCenter: function(modal, top, left) {
    this.centered = true;
    this.centerTop = top;
    this.centerLeft = left;

    this.show(modal);
  },
  
  isVisible: function() {
    return this.visible;
  },
  
  _center: function(top, left) {    
    var windowScroll = WindowUtilities.getWindowScroll(this.options.parent);    
    var pageSize = WindowUtilities.getPageSize(this.options.parent);    
    if (typeof top == "undefined")
      top = (pageSize.windowHeight - (this.height + this.heightN + this.heightS))/2;
    top += windowScroll.top
    
    if (typeof left == "undefined")
      left = (pageSize.windowWidth - (this.width + this.widthW + this.widthE))/2;
    left += windowScroll.left      
    this.setLocation(top, left);
    this.toFront();
  },
  
  _recenter: function(event) {     
    if (this.centered) {
      var pageSize = WindowUtilities.getPageSize(this.options.parent);
      var windowScroll = WindowUtilities.getWindowScroll(this.options.parent);    

      // Check for this stupid IE that sends dumb events
      if (this.pageSize && this.pageSize.windowWidth == pageSize.windowWidth && this.pageSize.windowHeight == pageSize.windowHeight && 
          this.windowScroll.left == windowScroll.left && this.windowScroll.top == windowScroll.top) 
        return;
      this.pageSize = pageSize;
      this.windowScroll = windowScroll;
      // set height of Overlay to take up whole page and show
      if ($('overlay_modal')) 
        $('overlay_modal').setStyle({height: (pageSize.pageHeight + 'px')});
      
      if (this.options.recenterAuto)
        this._center(this.centerTop, this.centerLeft);    
    }
  },
  
  // Hides window
  hide: function() {
    this.visible = false;
    if (this.modal) {
      Windows.removeModalWindow(this);
      Windows.resetOverflow();
    }
    // To avoid bug on scrolling bar
    this.oldStyle = this.getContent().getStyle('overflow') || "auto"
    this.getContent().setStyle({overflow: "hidden"});

    this.options.hideEffect(this.element, this.options.hideEffectOptions);  

     if(this.iefix) 
      this.iefix.hide();

    if (!this.doNotNotifyHide)
      this._notify("onHide");
  },

  close: function() {
    // Asks closeCallback if exists
    if (this.visible) {
      if (this.options.closeCallback && ! this.options.closeCallback(this)) 
        return;

      if (this.options.destroyOnClose) {
        var destroyFunc = this.destroy.bind(this);
        if (this.options.hideEffectOptions.afterFinish) {
          var func = this.options.hideEffectOptions.afterFinish;
          this.options.hideEffectOptions.afterFinish = function() {func();destroyFunc() }
        }
        else 
          this.options.hideEffectOptions.afterFinish = function() {destroyFunc() }
      }
      Windows.updateFocusedWindow();
      
      this.doNotNotifyHide = true;
      this.hide();
      this.doNotNotifyHide = false;
      this._notify("onClose");
    }
  },
  
  minimize: function() {
    if (this.resizing)
      return;
    
    var r2 = $(this.getId() + "_row2");
    
    if (!this.minimized) {
      this.minimized = true;

      var dh = r2.getDimensions().height;
      this.r2Height = dh;
      var h  = this.element.getHeight() - dh;

      if (this.useLeft && this.useTop && Window.hasEffectLib && Effect.ResizeWindow) {
        new Effect.ResizeWindow(this, null, null, null, this.height -dh, {duration: Window.resizeEffectDuration});
      } else  {
        this.height -= dh;
        this.element.setStyle({height: h + "px"});
        r2.hide();
      }

      if (! this.useTop) {
        var bottom = parseFloat(this.element.getStyle('bottom'));
        this.element.setStyle({bottom: (bottom + dh) + 'px'});
      }
    } 
    else {      
      this.minimized = false;
      
      var dh = this.r2Height;
      this.r2Height = null;
      if (this.useLeft && this.useTop && Window.hasEffectLib && Effect.ResizeWindow) {
        new Effect.ResizeWindow(this, null, null, null, this.height + dh, {duration: Window.resizeEffectDuration});
      }
      else {
        var h  = this.element.getHeight() + dh;
        this.height += dh;
        this.element.setStyle({height: h + "px"})
        r2.show();
      }
      if (! this.useTop) {
        var bottom = parseFloat(this.element.getStyle('bottom'));
        this.element.setStyle({bottom: (bottom - dh) + 'px'});
      }
      this.toFront();
    }
    this._notify("onMinimize");
    
    // Store new location/size if need be
    this._saveCookie()
  },
  
  maximize: function() {
    if (this.isMinimized() || this.resizing)
      return;
  
    if (Prototype.Browser.IE && this.heightN == 0)
      this._getWindowBorderSize();
      
    if (this.storedLocation != null) {
      this._restoreLocation();
      if(this.iefix) 
        this.iefix.hide();
    }
    else {
      this._storeLocation();
      Windows.unsetOverflow(this);
      
      var windowScroll = WindowUtilities.getWindowScroll(this.options.parent);
      var pageSize = WindowUtilities.getPageSize(this.options.parent);    
      var left = windowScroll.left;
      var top = windowScroll.top;
      
      if (this.options.parent != document.body) {
        windowScroll =  {top:0, left:0, bottom:0, right:0};
        var dim = this.options.parent.getDimensions();
        pageSize.windowWidth = dim.width;
        pageSize.windowHeight = dim.height;
        top = 0; 
        left = 0;
      }
      
      if (this.constraint) {
        pageSize.windowWidth -= Math.max(0, this.constraintPad.left) + Math.max(0, this.constraintPad.right);
        pageSize.windowHeight -= Math.max(0, this.constraintPad.top) + Math.max(0, this.constraintPad.bottom);
        left +=  Math.max(0, this.constraintPad.left);
        top +=  Math.max(0, this.constraintPad.top);
      }
      
      var width = pageSize.windowWidth - this.widthW - this.widthE;
      var height= pageSize.windowHeight - this.heightN - this.heightS;

      if (this.useLeft && this.useTop && Window.hasEffectLib && Effect.ResizeWindow) {
        new Effect.ResizeWindow(this, top, left, width, height, {duration: Window.resizeEffectDuration});
      }
      else {
        this.setSize(width, height);
        this.element.setStyle(this.useLeft ? {left: left} : {right: left});
        this.element.setStyle(this.useTop ? {top: top} : {bottom: top});
      }
        
      this.toFront();
      if (this.iefix) 
        this._fixIEOverlapping(); 
    }
    this._notify("onMaximize");

    // Store new location/size if need be
    this._saveCookie()
  },
  
  isMinimized: function() {
    return this.minimized;
  },
  
  isMaximized: function() {
    return (this.storedLocation != null);
  },
  
  setOpacity: function(opacity) {
    if (Element.setOpacity)
      Element.setOpacity(this.element, opacity);
  },
  
  setZIndex: function(zindex) {
    this.element.setStyle({zIndex: zindex});
    Windows.updateZindex(zindex, this);
  },

  setTitle: function(newTitle) {
    if (!newTitle || newTitle == "") 
      newTitle = "&nbsp;";
      
    Element.update(this.element.id + '_top', newTitle);
  },
   
  getTitle: function() {
    return $(this.element.id + '_top').innerHTML;
  },
  
  setStatusBar: function(element) {
    var statusBar = $(this.getId() + "_bottom");

    if (typeof(element) == "object") {
      if (this.bottombar.firstChild)
        this.bottombar.replaceChild(element, this.bottombar.firstChild);
      else
        this.bottombar.appendChild(element);
    }
    else
      this.bottombar.innerHTML = element;
  },

  _checkIEOverlapping: function() {
    if(!this.iefix && (navigator.appVersion.indexOf('MSIE')>0) && (navigator.userAgent.indexOf('Opera')<0) && (this.element.getStyle('position')=='absolute')) {
        new Insertion.After(this.element.id, '<iframe id="' + this.element.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.element.id+'_iefix');
    }
    if(this.iefix) 
      setTimeout(this._fixIEOverlapping.bind(this), 50);
  },

  _fixIEOverlapping: function() {
      Position.clone(this.element, this.iefix);
      this.iefix.style.zIndex = this.element.style.zIndex - 1;
      this.iefix.show();
  },
  
  _getWindowBorderSize: function(event) {
    // Hack to get real window border size!!
    var div = this._createHiddenDiv(this.options.className + "_n")
    this.heightN = Element.getDimensions(div).height;    
    div.parentNode.removeChild(div)

    var div = this._createHiddenDiv(this.options.className + "_s")
    this.heightS = Element.getDimensions(div).height;    
    div.parentNode.removeChild(div)

    var div = this._createHiddenDiv(this.options.className + "_e")
    this.widthE = Element.getDimensions(div).width;    
    div.parentNode.removeChild(div)

    var div = this._createHiddenDiv(this.options.className + "_w")
    this.widthW = Element.getDimensions(div).width;
    div.parentNode.removeChild(div);
    
    var div = document.createElement("div");
    div.className = "overlay_" + this.options.className ;
    document.body.appendChild(div);
    //alert("no timeout:\nopacity: " + div.getStyle("opacity") + "\nwidth: " + document.defaultView.getComputedStyle(div, null).width);
    var that = this;
    
    // Workaround for Safari!!
    setTimeout(function() {that.overlayOpacity = ($(div).getStyle("opacity")); div.parentNode.removeChild(div);}, 10);
    
    // Workaround for IE!!
    if (Prototype.Browser.IE) {
      this.heightS = $(this.getId() +"_row3").getDimensions().height;
      this.heightN = $(this.getId() +"_row1").getDimensions().height;
    }

    // Safari size fix
    if (Prototype.Browser.WebKit && Prototype.Browser.WebKitVersion < 420)
      this.setSize(this.width, this.height);
    if (this.doMaximize)
      this.maximize();
    if (this.doMinimize)
      this.minimize();
  },
 
  _createHiddenDiv: function(className) {
    var objBody = document.body;
    var win = document.createElement("div");
    win.setAttribute('id', this.element.id+ "_tmp");
    win.className = className;
    win.style.display = 'none';
    win.innerHTML = '';
    objBody.insertBefore(win, objBody.firstChild);
    return win;
  },
  
  _storeLocation: function() {
    if (this.storedLocation == null) {
      this.storedLocation = {useTop: this.useTop, useLeft: this.useLeft, 
                             top: this.element.getStyle('top'), bottom: this.element.getStyle('bottom'),
                             left: this.element.getStyle('left'), right: this.element.getStyle('right'),
                             width: this.width, height: this.height };
    }
  },
  
  _restoreLocation: function() {
    if (this.storedLocation != null) {
      this.useLeft = this.storedLocation.useLeft;
      this.useTop = this.storedLocation.useTop;
      
      if (this.useLeft && this.useTop && Window.hasEffectLib && Effect.ResizeWindow)
        new Effect.ResizeWindow(this, this.storedLocation.top, this.storedLocation.left, this.storedLocation.width, this.storedLocation.height, {duration: Window.resizeEffectDuration});
      else {
        this.element.setStyle(this.useLeft ? {left: this.storedLocation.left} : {right: this.storedLocation.right});
        this.element.setStyle(this.useTop ? {top: this.storedLocation.top} : {bottom: this.storedLocation.bottom});
        this.setSize(this.storedLocation.width, this.storedLocation.height);
      }
      
      Windows.resetOverflow();
      this._removeStoreLocation();
    }
  },
  
  _removeStoreLocation: function() {
    this.storedLocation = null;
  },
  
  _saveCookie: function() {
    if (this.cookie) {
      var value = "";
      if (this.useLeft)
        value += "l:" +  (this.storedLocation ? this.storedLocation.left : this.element.getStyle('left'))
      else
        value += "r:" + (this.storedLocation ? this.storedLocation.right : this.element.getStyle('right'))
      if (this.useTop)
        value += ",t:" + (this.storedLocation ? this.storedLocation.top : this.element.getStyle('top'))
      else
        value += ",b:" + (this.storedLocation ? this.storedLocation.bottom :this.element.getStyle('bottom'))
        
      value += "," + (this.storedLocation ? this.storedLocation.width : this.width);
      value += "," + (this.storedLocation ? this.storedLocation.height : this.height);
      value += "," + this.isMinimized();
      value += "," + this.isMaximized();
      WindowUtilities.setCookie(value, this.cookie)
    }
  },
  
  _createWiredElement: function() {
    if (! this.wiredElement) {
      if (Prototype.Browser.IE)
        this._getWindowBorderSize();
      var div = document.createElement("div");
      div.className = "wired_frame " + this.options.className + "_wired_frame";
      
      div.style.position = 'absolute';
      this.options.parent.insertBefore(div, this.options.parent.firstChild);
      this.wiredElement = $(div);
    }
    if (this.useLeft) 
      this.wiredElement.setStyle({left: this.element.getStyle('left')});
    else 
      this.wiredElement.setStyle({right: this.element.getStyle('right')});
      
    if (this.useTop) 
      this.wiredElement.setStyle({top: this.element.getStyle('top')});
    else 
      this.wiredElement.setStyle({bottom: this.element.getStyle('bottom')});

    var dim = this.element.getDimensions();
    this.wiredElement.setStyle({width: dim.width + "px", height: dim.height +"px"});

    this.wiredElement.setStyle({zIndex: Windows.maxZIndex+30});
    return this.wiredElement;
  },
  
  _hideWiredElement: function() {
    if (! this.wiredElement || ! this.currentDrag)
      return;
    if (this.currentDrag == this.element) 
      this.currentDrag = null;
    else {
      if (this.useLeft) 
        this.element.setStyle({left: this.currentDrag.getStyle('left')});
      else 
        this.element.setStyle({right: this.currentDrag.getStyle('right')});

      if (this.useTop) 
        this.element.setStyle({top: this.currentDrag.getStyle('top')});
      else 
        this.element.setStyle({bottom: this.currentDrag.getStyle('bottom')});

      this.currentDrag.hide();
      this.currentDrag = null;
      if (this.doResize)
        this.setSize(this.width, this.height);
    } 
  },
  
  _notify: function(eventName) {
    if (this.options[eventName])
      this.options[eventName](this);
    else
      Windows.notify(eventName, this);
  }
};

// Windows containers, register all page windows
var Windows = {
  windows: [],
  modalWindows: [],
  observers: [],
  focusedWindow: null,
  maxZIndex: 0,
  overlayShowEffectOptions: {duration: 0.5},
  overlayHideEffectOptions: {duration: 0.5},

  addObserver: function(observer) {
    this.removeObserver(observer);
    this.observers.push(observer);
  },
  
  removeObserver: function(observer) {  
    this.observers = this.observers.reject( function(o) { return o==observer });
  },
  
  // onDestroy onStartResize onStartMove onResize onMove onEndResize onEndMove onFocus onBlur onBeforeShow onShow onHide onMinimize onMaximize onClose
  notify: function(eventName, win) {  
    this.observers.each( function(o) {if(o[eventName]) o[eventName](eventName, win);});
  },

  // Gets window from its id
  getWindow: function(id) {
    return this.windows.detect(function(d) { return d.getId() ==id });
  },

  // Gets the last focused window
  getFocusedWindow: function() {
    return this.focusedWindow;
  },

  updateFocusedWindow: function() {
    this.focusedWindow = this.windows.length >=2 ? this.windows[this.windows.length-2] : null;    
  },
  
  // Registers a new window (called by Windows constructor)
  register: function(win) {
    this.windows.push(win);
  },
    
  // Add a modal window in the stack
  addModalWindow: function(win) {
    // Disable screen if first modal window
    if (this.modalWindows.length == 0) {
      WindowUtilities.disableScreen(win.options.className, 'overlay_modal', win.overlayOpacity, win.getId(), win.options.parent);
    }
    else {
      // Move overlay over all windows
      if (Window.keepMultiModalWindow) {
        $('overlay_modal').style.zIndex = Windows.maxZIndex + 1;
        Windows.maxZIndex += 1;
        WindowUtilities._hideSelect(this.modalWindows.last().getId());
      }
      // Hide current modal window
      else
        this.modalWindows.last().element.hide();
      // Fucking IE select issue
      WindowUtilities._showSelect(win.getId());
    }      
    this.modalWindows.push(win);    
  },
  
  removeModalWindow: function(win) {
    this.modalWindows.pop();
    
    // No more modal windows
    if (this.modalWindows.length == 0)
      WindowUtilities.enableScreen();     
    else {
      if (Window.keepMultiModalWindow) {
        this.modalWindows.last().toFront();
        WindowUtilities._showSelect(this.modalWindows.last().getId());        
      }
      else
        this.modalWindows.last().element.show();
    }
  },
  
  // Registers a new window (called by Windows constructor)
  register: function(win) {
    this.windows.push(win);
  },
  
  // Unregisters a window (called by Windows destructor)
  unregister: function(win) {
    this.windows = this.windows.reject(function(d) { return d==win });
  }, 
  
  // Closes all windows
  closeAll: function() {  
    this.windows.each( function(w) {Windows.close(w.getId())} );
  },
  
  closeAllModalWindows: function() {
    WindowUtilities.enableScreen();     
    this.modalWindows.each( function(win) {if (win) win.close()});    
  },

  // Minimizes a window with its id
  minimize: function(id, event) {
    var win = this.getWindow(id)
    if (win && win.visible)
      win.minimize();
    Event.stop(event);
  },
  
  // Maximizes a window with its id
  maximize: function(id, event) {
    var win = this.getWindow(id)
    if (win && win.visible)
      win.maximize();
    Event.stop(event);
  },

  // Closes a window with its id
  close: function(id, event) {
    var win = this.getWindow(id);
    if (win) 
      win.close();
    if (event)
      Event.stop(event);
  },
  
  blur: function(id) {
    var win = this.getWindow(id);  
    if (!win)
      return;
    if (win.options.blurClassName)
      win.changeClassName(win.options.blurClassName);
    if (this.focusedWindow == win)  
      this.focusedWindow = null;
    win._notify("onBlur");  
  },
  
  focus: function(id) {
    var win = this.getWindow(id);  
    if (!win)
      return;       
    if (this.focusedWindow)
      this.blur(this.focusedWindow.getId())

    if (win.options.focusClassName)
      win.changeClassName(win.options.focusClassName);  
    this.focusedWindow = win;
    win._notify("onFocus");
  },
  
  unsetOverflow: function(except) {    
    this.windows.each(function(d) { d.oldOverflow = d.getContent().getStyle("overflow") || "auto" ; d.getContent().setStyle({overflow: "hidden"}) });
    if (except && except.oldOverflow)
      except.getContent().setStyle({overflow: except.oldOverflow});
  },

  resetOverflow: function() {
    this.windows.each(function(d) { if (d.oldOverflow) d.getContent().setStyle({overflow: d.oldOverflow}) });
  },

  updateZindex: function(zindex, win) { 
    if (zindex > this.maxZIndex) {   
      this.maxZIndex = zindex;    
      if (this.focusedWindow) 
        this.blur(this.focusedWindow.getId())
    }
    this.focusedWindow = win;
    if (this.focusedWindow) 
      this.focus(this.focusedWindow.getId())
  }
};

var Dialog = {
  dialogId: null,
  onCompleteFunc: null,
  callFunc: null, 
  parameters: null, 
    
  confirm: function(content, parameters) {
    // Get Ajax return before
    if (content && typeof content != "string") {
      Dialog._runAjaxRequest(content, parameters, Dialog.confirm);
      return 
    }
    content = content || "";
    
    parameters = parameters || {};
    var okLabel = parameters.okLabel ? parameters.okLabel : "Ok";
    var cancelLabel = parameters.cancelLabel ? parameters.cancelLabel : "Cancel";

    // Backward compatibility
    parameters = Object.extend(parameters, parameters.windowParameters || {});
    parameters.windowParameters = parameters.windowParameters || {};

    parameters.className = parameters.className || "alert";

    var okButtonClass = "class ='" + (parameters.buttonClass ? parameters.buttonClass + " " : "") + " ok_button'" 
    var cancelButtonClass = "class ='" + (parameters.buttonClass ? parameters.buttonClass + " " : "") + " cancel_button'" 
    var content = "\
      <div class='" + parameters.className + "_message'>" + content  + "</div>\
        <div class='" + parameters.className + "_buttons'>\
          <input type='button' value='" + okLabel + "' onclick='Dialog.okCallback()' " + okButtonClass + "/>\
          <input type='button' value='" + cancelLabel + "' onclick='Dialog.cancelCallback()' " + cancelButtonClass + "/>\
        </div>\
    ";
    return this._openDialog(content, parameters)
  },
  
  alert: function(content, parameters) {
    // Get Ajax return before
    if (content && typeof content != "string") {
      Dialog._runAjaxRequest(content, parameters, Dialog.alert);
      return 
    }
    content = content || "";
    
    parameters = parameters || {};
    var okLabel = parameters.okLabel ? parameters.okLabel : "Ok";

    // Backward compatibility    
    parameters = Object.extend(parameters, parameters.windowParameters || {});
    parameters.windowParameters = parameters.windowParameters || {};
    
    parameters.className = parameters.className || "alert";
    
    var okButtonClass = "class ='" + (parameters.buttonClass ? parameters.buttonClass + " " : "") + " ok_button'" 
    var content = "\
      <div class='" + parameters.className + "_message'>" + content  + "</div>\
        <div class='" + parameters.className + "_buttons'>\
          <input type='button' value='" + okLabel + "' onclick='Dialog.okCallback()' " + okButtonClass + "/>\
        </div>";                  
    return this._openDialog(content, parameters)
  },
  
  info: function(content, parameters) {   
    // Get Ajax return before
    if (content && typeof content != "string") {
      Dialog._runAjaxRequest(content, parameters, Dialog.info);
      return 
    }
    content = content || "";
     
    // Backward compatibility
    parameters = parameters || {};
    parameters = Object.extend(parameters, parameters.windowParameters || {});
    parameters.windowParameters = parameters.windowParameters || {};
    
    parameters.className = parameters.className || "alert";
    
    var content = "<div id='modal_dialog_message' class='" + parameters.className + "_message'>" + content  + "</div>";
    if (parameters.showProgress)
      content += "<div id='modal_dialog_progress' class='" + parameters.className + "_progress'>  </div>";

    parameters.ok = null;
    parameters.cancel = null;
    
    return this._openDialog(content, parameters)
  },
  
  setInfoMessage: function(message) {
    $('modal_dialog_message').update(message);
  },
  
  closeInfo: function() {
    Windows.close(this.dialogId);
  },
  
  _openDialog: function(content, parameters) {
    var className = parameters.className;
    
    if (! parameters.height && ! parameters.width) {
      parameters.width = WindowUtilities.getPageSize(parameters.options.parent || document.body).pageWidth / 2;
    }
    if (parameters.id)
      this.dialogId = parameters.id;
    else { 
      var t = new Date();
      this.dialogId = 'modal_dialog_' + t.getTime();
      parameters.id = this.dialogId;
    }

    // compute height or width if need be
    if (! parameters.height || ! parameters.width) {
      var size = WindowUtilities._computeSize(content, this.dialogId, parameters.width, parameters.height, 5, className)
      if (parameters.height)
        parameters.width = size + 5
      else
        parameters.height = size + 5
    }
    parameters.effectOptions = parameters.effectOptions ;
    parameters.resizable   = parameters.resizable || false;
    parameters.minimizable = parameters.minimizable || false;
    parameters.maximizable = parameters.maximizable ||  false;
    parameters.draggable   = parameters.draggable || false;
    parameters.closable    = parameters.closable || false;
    
    var win = new Window(parameters);
    win.getContent().innerHTML = content;
    
    win.showCenter(true, parameters.top, parameters.left);  
    win.setDestroyOnClose();
    
    win.cancelCallback = parameters.onCancel || parameters.cancel; 
    win.okCallback = parameters.onOk || parameters.ok;
    
    return win;    
  },
  
  _getAjaxContent: function(originalRequest)  {
      Dialog.callFunc(originalRequest.responseText, Dialog.parameters)
  },
  
  _runAjaxRequest: function(message, parameters, callFunc) {
    if (message.options == null)
      message.options = {}  
    Dialog.onCompleteFunc = message.options.onComplete;
    Dialog.parameters = parameters;
    Dialog.callFunc = callFunc;
    
    message.options.onComplete = Dialog._getAjaxContent;
    new Ajax.Request(message.url, message.options);
  },
  
  okCallback: function() {
    var win = Windows.focusedWindow;
    if (!win.okCallback || win.okCallback(win)) {
      // Remove onclick on button
      $$("#" + win.getId()+" input").each(function(element) {element.onclick=null;})
      win.close();
    }
  },

  cancelCallback: function() {
    var win = Windows.focusedWindow;
    // Remove onclick on button
    $$("#" + win.getId()+" input").each(function(element) {element.onclick=null})
    win.close();
    if (win.cancelCallback)
      win.cancelCallback(win);
  }
}
/*
  Based on Lightbox JS: Fullsize Image Overlays 
  by Lokesh Dhakar - http://www.huddletogether.com

  For more information on this script, visit:
  http://huddletogether.com/projects/lightbox/

  Licensed under the Creative Commons Attribution 2.5 License - http://creativecommons.org/licenses/by/2.5/
  (basically, do anything you want, just leave my name and link)
*/

if (Prototype.Browser.WebKit) {
  var array = navigator.userAgent.match(new RegExp(/AppleWebKit\/([\d\.\+]*)/));
  Prototype.Browser.WebKitVersion = parseFloat(array[1]);
}

var WindowUtilities = {  
  // From dragdrop.js
  getWindowScroll: function(parent) {
    var T, L, W, H;
    parent = parent || document.body;              
    if (parent != document.body) {
      T = parent.scrollTop;
      L = parent.scrollLeft;
      W = parent.scrollWidth;
      H = parent.scrollHeight;
    } 
    else {
      var w = window;
      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 };
  }, 
  //
  // getPageSize()
  // Returns array with page width, height and window width, height
  // Core code from - quirksmode.org
  // Edit for Firefox by pHaez
  //
  getPageSize: function(parent){
    parent = parent || document.body;              
    var windowWidth, windowHeight;
    var pageHeight, pageWidth;
    if (parent != document.body) {
      windowWidth = parent.getWidth();
      windowHeight = parent.getHeight();                                
      pageWidth = parent.scrollWidth;
      pageHeight = parent.scrollHeight;                                
    } 
    else {
      var xScroll, yScroll;

      if (window.innerHeight && window.scrollMaxY) {  
        xScroll = document.body.scrollWidth;
        yScroll = window.innerHeight + window.scrollMaxY;
      } else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
        xScroll = document.body.scrollWidth;
        yScroll = document.body.scrollHeight;
      } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
        xScroll = document.body.offsetWidth;
        yScroll = document.body.offsetHeight;
      }


      if (self.innerHeight) {  // all except Explorer
        windowWidth = self.innerWidth;
        windowHeight = self.innerHeight;
      } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
        windowWidth = document.documentElement.clientWidth;
        windowHeight = document.documentElement.clientHeight;
      } else if (document.body) { // other Explorers
        windowWidth = document.body.clientWidth;
        windowHeight = document.body.clientHeight;
      }  

      // for small pages with total height less then height of the viewport
      if(yScroll < windowHeight){
        pageHeight = windowHeight;
      } else { 
        pageHeight = yScroll;
      }

      // for small pages with total width less then width of the viewport
      if(xScroll < windowWidth){  
        pageWidth = windowWidth;
      } else {
        pageWidth = xScroll;
      }
    }             
    return {pageWidth: pageWidth ,pageHeight: pageHeight , windowWidth: windowWidth, windowHeight: windowHeight};
  },

  disableScreen: function(className, overlayId, overlayOpacity, contentId, parent) {
    WindowUtilities.initLightbox(overlayId, className, function() {this._disableScreen(className, overlayId, overlayOpacity, contentId)}.bind(this), parent || document.body);
  },

  _disableScreen: function(className, overlayId, overlayOpacity, contentId) {
    // prep objects
    var objOverlay = $(overlayId);

    var pageSize = WindowUtilities.getPageSize(objOverlay.parentNode);

    // Hide select boxes as they will 'peek' through the image in IE, store old value
    if (contentId && Prototype.Browser.IE) {
      WindowUtilities._hideSelect();
      WindowUtilities._showSelect(contentId);
    }  
  
    // set height of Overlay to take up whole page and show
    objOverlay.style.height = (pageSize.pageHeight + 'px');
    objOverlay.style.display = 'none'; 
    if (overlayId == "overlay_modal" && Window.hasEffectLib && Windows.overlayShowEffectOptions) {
      objOverlay.overlayOpacity = overlayOpacity;
      new Effect.Appear(objOverlay, Object.extend({from: 0, to: overlayOpacity}, Windows.overlayShowEffectOptions));
    }
    else
      objOverlay.style.display = "block";
  },
  
  enableScreen: function(id) {
    id = id || 'overlay_modal';
    var objOverlay =  $(id);
    if (objOverlay) {
      // hide lightbox and overlay
      if (id == "overlay_modal" && Window.hasEffectLib && Windows.overlayHideEffectOptions)
        new Effect.Fade(objOverlay, Object.extend({from: objOverlay.overlayOpacity, to:0}, Windows.overlayHideEffectOptions));
      else {
        objOverlay.style.display = 'none';
        objOverlay.parentNode.removeChild(objOverlay);
      }
      
      // make select boxes visible using old value
      if (id != "__invisible__") 
        WindowUtilities._showSelect();
    }
  },

  _hideSelect: function(id) {
    if (Prototype.Browser.IE) {
      id = id ==  null ? "" : "#" + id + " ";
      $$(id + 'select').each(function(element) {
        if (! WindowUtilities.isDefined(element.oldVisibility)) {
          element.oldVisibility = element.style.visibility ? element.style.visibility : "visible";
          element.style.visibility = "hidden";
        }
      });
    }
  },
  
  _showSelect: function(id) {
    if (Prototype.Browser.IE) {
      id = id ==  null ? "" : "#" + id + " ";
      $$(id + 'select').each(function(element) {
        if (WindowUtilities.isDefined(element.oldVisibility)) {
          // Why?? Ask IE
          try {
            element.style.visibility = element.oldVisibility;
          } catch(e) {
            element.style.visibility = "visible";
          }
          element.oldVisibility = null;
        }
        else {
          if (element.style.visibility)
            element.style.visibility = "visible";
        }
      });
    }
  },

  isDefined: function(object) {
    return typeof(object) != "undefined" && object != null;
  },
  
  // initLightbox()
  // Function runs on window load, going through link tags looking for rel="lightbox".
  // These links receive onclick events that enable the lightbox display for their targets.
  // The function also inserts html markup at the top of the page which will be used as a
  // container for the overlay pattern and the inline image.
  initLightbox: function(id, className, doneHandler, parent) {
    // Already done, just update zIndex
    if ($(id)) {
      Element.setStyle(id, {zIndex: Windows.maxZIndex + 1});
      Windows.maxZIndex++;
      doneHandler();
    }
    // create overlay div and hardcode some functional styles (aesthetic styles are in CSS file)
    else {
      var objOverlay = document.createElement("div");
      objOverlay.setAttribute('id', id);
      objOverlay.className = "overlay_" + className
      objOverlay.style.display = 'none';
      objOverlay.style.position = 'absolute';
      objOverlay.style.top = '0';
      objOverlay.style.left = '0';
      objOverlay.style.zIndex = Windows.maxZIndex + 1;
      Windows.maxZIndex++;
      objOverlay.style.width = '100%';
      parent.insertBefore(objOverlay, parent.firstChild);
      if (Prototype.Browser.WebKit && id == "overlay_modal") {
        setTimeout(function() {doneHandler()}, 10);
      }
      else
        doneHandler();
    }    
  },
  
  setCookie: function(value, parameters) {
    document.cookie= parameters[0] + "=" + escape(value) +
      ((parameters[1]) ? "; expires=" + parameters[1].toGMTString() : "") +
      ((parameters[2]) ? "; path=" + parameters[2] : "") +
      ((parameters[3]) ? "; domain=" + parameters[3] : "") +
      ((parameters[4]) ? "; secure" : "");
  },

  getCookie: function(name) {
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1) {
      begin = dc.indexOf(prefix);
      if (begin != 0) return null;
    } else {
      begin += 2;
    }
    var end = document.cookie.indexOf(";", begin);
    if (end == -1) {
      end = dc.length;
    }
    return unescape(dc.substring(begin + prefix.length, end));
  },
    
  _computeSize: function(content, id, width, height, margin, className) {
    var objBody = document.body;
    var tmpObj = document.createElement("div");
    tmpObj.setAttribute('id', id);
    tmpObj.className = className + "_content";

    if (height)
      tmpObj.style.height = height + "px"
    else
      tmpObj.style.width = width + "px"
  
    tmpObj.style.position = 'absolute';
    tmpObj.style.top = '0';
    tmpObj.style.left = '0';
    tmpObj.style.display = 'none';

    tmpObj.innerHTML = content;
    objBody.insertBefore(tmpObj, objBody.firstChild);

    var size;
    if (height)
      size = $(tmpObj).getDimensions().width + margin;
    else
      size = $(tmpObj).getDimensions().height + margin;
    objBody.removeChild(tmpObj);
    return size;
  }  
}



if(typeof(Control) == 'undefined') var Control = {};

Control.Menu = Class.create({
  initialize: function(options) {
    this.options = {
      idvalue: 'deke',
      idlist: 'deke2',
      classelt:  'attack',
      button:  'button',
      position:  'bottom',
      event:  'mouseover',
      container:  false,
      onchange:  this.selectvalue,
      zIndex:  100,
      offset:{x:0,y:0}
    };
    Object.extend(this.options, options || { });
		Event.observe(document, 'mouseout', function(e){
			var p = Event.pointer(e), elt=$(this.options.idlist);
			if (!Position.within(elt,p.x,p.y)) elt.hide();
		}.bind(this));

		if (this.options.onchange){
		  $$('#'+this.options.idlist+' .'+this.options.classelt).each(function(d){
			  d.onclick = this.options.onchange.bindAsEventListener(this,d);
		  }.bind(this));
		}

		Event.observe($(this.options.button), this.options.event, this.activate.bindAsEventListener(this));
  },
  selectvalue: function(e,elt){
//		elt.visualEffect('pulsate',{duration:0.5});
//		$(this.options.idvalue).innerHTML = elt.innerHTML;
//		$(this.options.idlist).hide();
		Effect.SwitchOff(this.options.idlist);
		
  },
  activate: function(e){
		var elt = $(this.options.idlist);
		var p = $(this.options.idvalue);
		elt.setStyle({zIndex: this.options.zIndex});
		elt.clonePosition(p,{setWidth:false, setHeight:false, offsetLeft:this.options.offset.x, offsetTop:this.options.offset.y });
		elt.show();
  },
  innerDim: function(){
		if (self.innerHeight)	return {x:self.innerWidth, y:self.innerHeight};
		else if (document.documentElement && document.documentElement.clientHeight)
			return {x:document.documentElement.clientWidth, y:document.documentElement.clientHeight};
		else if (document.body)
			return {x:document.body.clientWidth, y:document.body.clientHeight};
		return {x:0, y:0};
	}
});
/* protoload 0.1 beta by Andreas Kalsch
 * last change: 09.07.2007
 *
 * This simple piece of code automates the creating of Ajax loading symbols.
 * The loading symbol covers an HTML element with correct position and size - example:
 * $('myElement').startWaiting() and $('myElement').stopWaiting()
 */
 
Protoload = {
	// the script to wait this amount of msecs until it shows the loading element
	timeUntilShow: 250,
	
	// opacity of loading element
	opacity: 0.8,

	// Start waiting status - show loading element
	startWaiting: function(element, className, timeUntilShow) {
		if (typeof element == 'string')
			element = document.getElementById(element);
		if (className == undefined)
			className = 'waiting';
		if (timeUntilShow == undefined)
			timeUntilShow = Protoload.timeUntilShow;
		
		element._waiting = true;
		if (!element._loading) {
			var e = document.createElement('div');
			(element.offsetParent || document.body).appendChild(element._loading = e);
			e.style.position = 'absolute';
			try {e.style.opacity = Protoload.opacity;} catch(e) {}
			try {e.style.MozOpacity = Protoload.opacity;} catch(e) {}
			try {e.style.filter = 'alpha(opacity='+Math.round(Protoload.opacity * 100)+')';} catch(e) {}
			try {e.style.KhtmlOpacity = Protoload.opacity;} catch(e) {}
			
			/*var zIndex = 0;
			if (window.UI)
				if (UI.zIndex)
					zIndex = ++UI.zIndex;
			if (!zIndex)
				zIndex = ++Protoload._zIndex;
			e.style.zIndex = zIndex;*/
		}
		element._loading.className = className;
		window.setTimeout((function() {
			if (this._waiting) {
				var left = this.offsetLeft, 
					top = this.offsetTop,
					width = this.offsetWidth,
					height = this.offsetHeight,
					l = this._loading;
					
				l.style.left = left+'px';
				l.style.top = top+'px';
				l.style.width = width+'px';
				l.style.height = height+'px';
				l.style.display = 'inline';
			}
		}).bind(element), timeUntilShow);
	},
	
	// Stop waiting status - hide loading element
	stopWaiting: function(element) {
		if (element._waiting) {
			element._waiting = false;
			element._loading.parentNode.removeChild(element._loading);
			element._loading = null;
		}
	}/*,
	
	_zIndex: 1000000*/
};

if (Prototype) {
	Element.addMethods(Protoload);
	Object.extend(Element, Protoload);
}
/* *//**
 * TrimPath Template. Release 1.0.38.
 * Copyright (C) 2004, 2005 Metaha.
 * 
 * TrimPath Template is licensed under the GNU General Public License
 * and the Apache License, Version 2.0, as follows:
 *
 * This program is free software; you can redistribute it and/or 
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 * 
 * This program is distributed WITHOUT ANY WARRANTY; without even the 
 * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
 * See the GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
var TrimPath;

// TODO: Debugging mode vs stop-on-error mode - runtime flag.
// TODO: Handle || (or) characters and backslashes.
// TODO: Add more modifiers.

(function() {               // Using a closure to keep global namespace clean.
    if (TrimPath == null)
        TrimPath = new Object();
    if (TrimPath.evalEx == null)
        TrimPath.evalEx = function(src) { return eval(src); };

    var UNDEFINED;
    if (Array.prototype.pop == null)  // IE 5.x fix from Igor Poteryaev.
        Array.prototype.pop = function() {
            if (this.length === 0) {return UNDEFINED;}
            return this[--this.length];
        };
    if (Array.prototype.push == null) // IE 5.x fix from Igor Poteryaev.
        Array.prototype.push = function() {
            for (var i = 0; i < arguments.length; ++i) {this[this.length] = arguments[i];}
            return this.length;
        };

    TrimPath.parseTemplate = function(tmplContent, optTmplName, optEtc) {
        if (optEtc == null)
            optEtc = TrimPath.parseTemplate_etc;
        var funcSrc = parse(tmplContent, optTmplName, optEtc);
        var func = TrimPath.evalEx(funcSrc, optTmplName, 1);
        if (func != null)
            return new optEtc.Template(optTmplName, tmplContent, funcSrc, func, optEtc);
        return null;
    }
    
    try {
        String.prototype.process = function(context, optFlags) {
            var template = TrimPath.parseTemplate(this, null);
            if (template != null)
                return template.process(context, optFlags);
            return this;
        }
    } catch (e) { // Swallow exception, such as when String.prototype is sealed.
    }
    
    TrimPath.parseTemplate_etc = {};            // Exposed for extensibility.
    TrimPath.parseTemplate_etc.statementTag = "forelse|for|if|elseif|else|var|macro";
    TrimPath.parseTemplate_etc.statementDef = { // Lookup table for statement tags.
        "if"     : { delta:  1, prefix: "if (", suffix: ") {", paramMin: 1 },
        "else"   : { delta:  0, prefix: "} else {" },
        "elseif" : { delta:  0, prefix: "} else if (", suffix: ") {", paramDefault: "true" },
        "/if"    : { delta: -1, prefix: "}" },
        "for"    : { delta:  1, paramMin: 3, 
                     prefixFunc : function(stmtParts, state, tmplName, etc) {
                        if (stmtParts[2] != "in")
                            throw new etc.ParseError(tmplName, state.line, "bad for loop statement: " + stmtParts.join(' '));
                        var iterVar = stmtParts[1];
                        var listVar = "__LIST__" + iterVar;
                        return [ "var ", listVar, " = ", stmtParts[3], ";",
                             // Fix from Ross Shaull for hash looping, make sure that we have an array of loop lengths to treat like a stack.
                             "var __LENGTH_STACK__;",
                             "if (typeof(__LENGTH_STACK__) == 'undefined' || !__LENGTH_STACK__.length) __LENGTH_STACK__ = new Array();", 
                             "__LENGTH_STACK__[__LENGTH_STACK__.length] = 0;", // Push a new for-loop onto the stack of loop lengths.
                             "if ((", listVar, ") != null) { ",
                             "var ", iterVar, "_ct = 0;",       // iterVar_ct variable, added by B. Bittman     
                             "for (var ", iterVar, "_index in ", listVar, ") { ",
                             iterVar, "_ct++;",
                             "if (typeof(", listVar, "[", iterVar, "_index]) == 'function') {continue;}", // IE 5.x fix from Igor Poteryaev.
                             "__LENGTH_STACK__[__LENGTH_STACK__.length - 1]++;",
                             "var ", iterVar, " = ", listVar, "[", iterVar, "_index];" ].join("");
                     } },
        "forelse" : { delta:  0, prefix: "} } if (__LENGTH_STACK__[__LENGTH_STACK__.length - 1] == 0) { if (", suffix: ") {", paramDefault: "true" },
        "/for"    : { delta: -1, prefix: "} }; delete __LENGTH_STACK__[__LENGTH_STACK__.length - 1];" }, // Remove the just-finished for-loop from the stack of loop lengths.
        "var"     : { delta:  0, prefix: "var ", suffix: ";" },
        "macro"   : { delta:  1, 
                      prefixFunc : function(stmtParts, state, tmplName, etc) {
                          var macroName = stmtParts[1].split('(')[0];
                          return [ "var ", macroName, " = function", 
                                   stmtParts.slice(1).join(' ').substring(macroName.length),
                                   "{ var _OUT_arr = []; var _OUT = { write: function(m) { if (m) _OUT_arr.push(m); } }; " ].join('');
                     } }, 
        "/macro"  : { delta: -1, prefix: " return _OUT_arr.join(''); };" }
    }
    TrimPath.parseTemplate_etc.modifierDef = {
        "eat"        : function(v)    { return ""; },
        "escape"     : function(s)    { return String(s).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;"); },
        "capitalize" : function(s)    { return String(s).toUpperCase(); },
        "default"    : function(s, d) { return s != null ? s : d; }
    }
    TrimPath.parseTemplate_etc.modifierDef.h = TrimPath.parseTemplate_etc.modifierDef.escape;

    TrimPath.parseTemplate_etc.Template = function(tmplName, tmplContent, funcSrc, func, etc) {
        this.process = function(context, flags) {
            if (context == null)
                context = {};
            if (context._MODIFIERS == null)
                context._MODIFIERS = {};
            if (context.defined == null)
                context.defined = function(str) { return (context[str] != undefined); };
            for (var k in etc.modifierDef) {
                if (context._MODIFIERS[k] == null)
                    context._MODIFIERS[k] = etc.modifierDef[k];
            }
            if (flags == null)
                flags = {};
            var resultArr = [];
            var resultOut = { write: function(m) { resultArr.push(m); } };
            try {
                func(resultOut, context, flags);
            } catch (e) {
                if (flags.throwExceptions == true)
                    throw e;
                var result = new String(resultArr.join("") + "[ERROR: " + e.toString() + (e.message ? '; ' + e.message : '') + "]");
                result["exception"] = e;
                return result;
            }
            return resultArr.join("");
        }
        this.name       = tmplName;
        this.source     = tmplContent; 
        this.sourceFunc = funcSrc;
        this.toString   = function() { return "TrimPath.Template [" + tmplName + "]"; }
    }
    TrimPath.parseTemplate_etc.ParseError = function(name, line, message) {
        this.name    = name;
        this.line    = line;
        this.message = message;
    }
    TrimPath.parseTemplate_etc.ParseError.prototype.toString = function() { 
        return ("TrimPath template ParseError in " + this.name + ": line " + this.line + ", " + this.message);
    }
    
    var parse = function(body, tmplName, etc) {
        body = cleanWhiteSpace(body);
        var funcText = [ "var TrimPath_Template_TEMP = function(_OUT, _CONTEXT, _FLAGS) { with (_CONTEXT) {" ];
        var state    = { stack: [], line: 1 };                              // TODO: Fix line number counting.
        var endStmtPrev = -1;
        while (endStmtPrev + 1 < body.length) {
            var begStmt = endStmtPrev;
            // Scan until we find some statement markup.
            begStmt = body.indexOf("{", begStmt + 1);
            while (begStmt >= 0) {
                var endStmt = body.indexOf('}', begStmt + 1);
                var stmt = body.substring(begStmt, endStmt);
                var blockrx = stmt.match(/^\{(cdata|minify|eval)/); // From B. Bittman, minify/eval/cdata implementation.
                if (blockrx) {
                    var blockType = blockrx[1]; 
                    var blockMarkerBeg = begStmt + blockType.length + 1;
                    var blockMarkerEnd = body.indexOf('}', blockMarkerBeg);
                    if (blockMarkerEnd >= 0) {
                        var blockMarker;
                        if( blockMarkerEnd - blockMarkerBeg <= 0 ) {
                            blockMarker = "{/" + blockType + "}";
                        } else {
                            blockMarker = body.substring(blockMarkerBeg + 1, blockMarkerEnd);
                        }                        
                        
                        var blockEnd = body.indexOf(blockMarker, blockMarkerEnd + 1);
                        if (blockEnd >= 0) {                            
                            emitSectionText(body.substring(endStmtPrev + 1, begStmt), funcText);
                            
                            var blockText = body.substring(blockMarkerEnd + 1, blockEnd);
                            if (blockType == 'cdata') {
                                emitText(blockText, funcText);
                            } else if (blockType == 'minify') {
                                emitText(scrubWhiteSpace(blockText), funcText);
                            } else if (blockType == 'eval') {
                                if (blockText != null && blockText.length > 0) // From B. Bittman, eval should not execute until process().
                                    funcText.push('_OUT.write( (function() { ' + blockText + ' })() );');
                            }
                            begStmt = endStmtPrev = blockEnd + blockMarker.length - 1;
                        }
                    }                        
                } else if (body.charAt(begStmt - 1) != '$' &&               // Not an expression or backslashed,
                           body.charAt(begStmt - 1) != '\\') {              // so check if it is a statement tag.
                    var offset = (body.charAt(begStmt + 1) == '/' ? 2 : 1); // Close tags offset of 2 skips '/'.
                                                                            // 10 is larger than maximum statement tag length.
                    if (body.substring(begStmt + offset, begStmt + 10 + offset).search(TrimPath.parseTemplate_etc.statementTag) == 0) 
                        break;                                              // Found a match.
                }
                begStmt = body.indexOf("{", begStmt + 1);
            }
            if (begStmt < 0)                              // In "a{for}c", begStmt will be 1.
                break;
            var endStmt = body.indexOf("}", begStmt + 1); // In "a{for}c", endStmt will be 5.
            if (endStmt < 0)
                break;
            emitSectionText(body.substring(endStmtPrev + 1, begStmt), funcText);
            emitStatement(body.substring(begStmt, endStmt + 1), state, funcText, tmplName, etc);
            endStmtPrev = endStmt;
        }
        emitSectionText(body.substring(endStmtPrev + 1), funcText);
        if (state.stack.length != 0)
            throw new etc.ParseError(tmplName, state.line, "unclosed, unmatched statement(s): " + state.stack.join(","));
        funcText.push("}}; TrimPath_Template_TEMP");
        return funcText.join("");
    }
    
    var emitStatement = function(stmtStr, state, funcText, tmplName, etc) {
        var parts = stmtStr.slice(1, -1).split(' ');
        var stmt = etc.statementDef[parts[0]]; // Here, parts[0] == for/if/else/...
        if (stmt == null) {                    // Not a real statement.
            emitSectionText(stmtStr, funcText);
            return;
        }
        if (stmt.delta < 0) {
            if (state.stack.length <= 0)
                throw new etc.ParseError(tmplName, state.line, "close tag does not match any previous statement: " + stmtStr);
            state.stack.pop();
        } 
        if (stmt.delta > 0)
            state.stack.push(stmtStr);

        if (stmt.paramMin != null &&
            stmt.paramMin >= parts.length)
            throw new etc.ParseError(tmplName, state.line, "statement needs more parameters: " + stmtStr);
        if (stmt.prefixFunc != null)
            funcText.push(stmt.prefixFunc(parts, state, tmplName, etc));
        else 
            funcText.push(stmt.prefix);
        if (stmt.suffix != null) {
            if (parts.length <= 1) {
                if (stmt.paramDefault != null)
                    funcText.push(stmt.paramDefault);
            } else {
                for (var i = 1; i < parts.length; i++) {
                    if (i > 1)
                        funcText.push(' ');
                    funcText.push(parts[i]);
                }
            }
            funcText.push(stmt.suffix);
        }
    }

    var emitSectionText = function(text, funcText) {
        if (text.length <= 0)
            return;
        var nlPrefix = 0;               // Index to first non-newline in prefix.
        var nlSuffix = text.length - 1; // Index to first non-space/tab in suffix.
        while (nlPrefix < text.length && (text.charAt(nlPrefix) == '\n'))
            nlPrefix++;
        while (nlSuffix >= 0 && (text.charAt(nlSuffix) == ' ' || text.charAt(nlSuffix) == '\t'))
            nlSuffix--;
        if (nlSuffix < nlPrefix)
            nlSuffix = nlPrefix;
        if (nlPrefix > 0) {
            funcText.push('if (_FLAGS.keepWhitespace == true) _OUT.write("');
            var s = text.substring(0, nlPrefix).replace('\n', '\\n'); // A macro IE fix from BJessen.
            if (s.charAt(s.length - 1) == '\n')
            	s = s.substring(0, s.length - 1);
            funcText.push(s);
            funcText.push('");');
        }
        var lines = text.substring(nlPrefix, nlSuffix + 1).split('\n');
        for (var i = 0; i < lines.length; i++) {
            emitSectionTextLine(lines[i], funcText);
            if (i < lines.length - 1)
                funcText.push('_OUT.write("\\n");\n');
        }
        if (nlSuffix + 1 < text.length) {
            funcText.push('if (_FLAGS.keepWhitespace == true) _OUT.write("');
            var s = text.substring(nlSuffix + 1).replace('\n', '\\n');
            if (s.charAt(s.length - 1) == '\n')
            	s = s.substring(0, s.length - 1);
            funcText.push(s);
            funcText.push('");');
        }
    }
    
    var emitSectionTextLine = function(line, funcText) {
        var endMarkPrev = '}';
        var endExprPrev = -1;
        while (endExprPrev + endMarkPrev.length < line.length) {
            var begMark = "${", endMark = "}";
            var begExpr = line.indexOf(begMark, endExprPrev + endMarkPrev.length); // In "a${b}c", begExpr == 1
            if (begExpr < 0)
                break;
            if (line.charAt(begExpr + 2) == '%') {
                begMark = "${%";
                endMark = "%}";
            }
            var endExpr = line.indexOf(endMark, begExpr + begMark.length);         // In "a${b}c", endExpr == 4;
            if (endExpr < 0)
                break;
            emitText(line.substring(endExprPrev + endMarkPrev.length, begExpr), funcText);                
            // Example: exprs == 'firstName|default:"John Doe"|capitalize'.split('|')
            var exprArr = line.substring(begExpr + begMark.length, endExpr).replace(/\|\|/g, "#@@#").split('|');
            for (var k in exprArr) {
                if (exprArr[k].replace) // IE 5.x fix from Igor Poteryaev.
                    exprArr[k] = exprArr[k].replace(/#@@#/g, '||');
            }
            funcText.push('_OUT.write(');
            emitExpression(exprArr, exprArr.length - 1, funcText); 
            funcText.push(');');
            endExprPrev = endExpr;
            endMarkPrev = endMark;
        }
        emitText(line.substring(endExprPrev + endMarkPrev.length), funcText); 
    }
    
    var emitText = function(text, funcText) {
        if (text == null ||
            text.length <= 0)
            return;
        text = text.replace(/\\/g, '\\\\');
        text = text.replace(/\n/g, '\\n');
        text = text.replace(/"/g,  '\\"');
        funcText.push('_OUT.write("');
        funcText.push(text);
        funcText.push('");');
    }
    
    var emitExpression = function(exprArr, index, funcText) {
        // Ex: foo|a:x|b:y1,y2|c:z1,z2 is emitted as c(b(a(foo,x),y1,y2),z1,z2)
        var expr = exprArr[index]; // Ex: exprArr == [firstName,capitalize,default:"John Doe"]
        if (index <= 0) {          // Ex: expr    == 'default:"John Doe"'
            funcText.push(expr);
            return;
        }
        var parts = expr.split(':');
        funcText.push('_MODIFIERS["');
        funcText.push(parts[0]); // The parts[0] is a modifier function name, like capitalize.
        funcText.push('"](');
        emitExpression(exprArr, index - 1, funcText);
        if (parts.length > 1) {
            funcText.push(',');
            funcText.push(parts[1]);
        }
        funcText.push(')');
    }

    var cleanWhiteSpace = function(result) {
        result = result.replace(/\t/g,   "    ");
        result = result.replace(/\r\n/g, "\n");
        result = result.replace(/\r/g,   "\n");
        result = result.replace(/^(\s*\S*(\s+\S+)*)\s*$/, '$1'); // Right trim by Igor Poteryaev.
        return result;
    }

    var scrubWhiteSpace = function(result) {
        result = result.replace(/^\s+/g,   "");
        result = result.replace(/\s+$/g,   "");
        result = result.replace(/\s+/g,   " ");
        result = result.replace(/^(\s*\S*(\s+\S+)*)\s*$/, '$1'); // Right trim by Igor Poteryaev.
        return result;
    }

    // The DOM helper functions depend on DOM/DHTML, so they only work in a browser.
    // However, these are not considered core to the engine.
    //
    TrimPath.parseDOMTemplate = function(elementId, optDocument, optEtc) {
        if (optDocument == null)
            optDocument = document;
        var element = optDocument.getElementById(elementId);
        var content = element.value;     // Like textarea.value.
        if (content == null)
            content = element.innerHTML; // Like textarea.innerHTML.
        content = content.replace(/&lt;/g, "<").replace(/&gt;/g, ">");
        return TrimPath.parseTemplate(content, elementId, optEtc);
    }

    TrimPath.processDOMTemplate = function(elementId, context, optFlags, optDocument, optEtc) {
        return TrimPath.parseDOMTemplate(elementId, optDocument, optEtc).process(context, optFlags);
    }
}) ();
// -----------------------------------------------------------------------------------
//
//	Lightbox Slideshow v1.2 (compatible with Prototype 1.6)
//	by Justin Barkhuff - http://www.justinbarkhuff.com/lab/lightbox_slideshow/
//  Updated: 2008-01-11
//
//	Largely based on Lightbox v2.02
//	by Lokesh Dhakar - http://huddletogether.com/projects/lightbox2/
//	3/31/06
//
//	Licensed under the Creative Commons Attribution 2.5 License - http://creativecommons.org/licenses/by/2.5/
//
//	The code inserts html at the bottom of the page that looks similar to this:
//
//	<div id="overlay"></div>
//	<div id="lightbox">
//		<div id="outerImageContainer">
//			<div id="imageContainer">
//				<img id="lightboxImage" />
//				<div id="hoverNav">
//					<a href="javascript:void(0);" id="prevLinkImg">&laquo; prev</a>
//					<a href="javascript:void(0);" id="nextLinkImg">next &raquo;</a>
//				</div>
//				<div id="loading">
//					<a href="javascript:void(0);" id="loadingLink">loading</a>
//				</div>
//			</div>
//		</div>
//		<div id="imageDataContainer">
//			<div id="imageData">
//				<div id="imageDetails">
//					<span id="caption"></span>
//					<span id="numberDisplay"></span>
//					<span id="detailsNav">
//						<a id="prevLinkDetails" href="javascript:void(0);">&laquo; prev</a>
//						<a id="nextLinkDetails" href="javascript:void(0);">next &raquo;</a>
//						<a id="slideShowControl" href="javascript:void(0);">stop slideshow</a>
//					</span>
//				</div>
//				<div id="close">
//					<a id="closeLink" href="javascript:void(0);">close</a>
//				</div>
//			</div>
//		</div>
//	</div>
//
// -----------------------------------------------------------------------------------

//
//	Lightbox Object
//

var Lightbox = {	
	activeImage : null,
	badObjects : ['select','object','embed'],
	container : null,
	enableSlideshow : null,
	groupName : null,
	imageArray : [],
	options : null,
	overlayDuration : null,
	overlayOpacity : null,
	playSlides : null,
	refTags : ['a','area'],
	relAttribute : null,
	resizeDuration : null,
	slideShowTimer : null,
	startImage : null,
	
	//
	// initialize()
	// Constructor sets class properties and configuration options and
	// inserts html at the bottom of the page which is used to display the shadow 
	// overlay and the image container.
	//
	initialize: function(options) {
		if (!document.getElementsByTagName){ return; }
		
		this.options = $H({
			animate : true, // resizing animations
			autoPlay : true, // should slideshow start automatically
			borderSize : 10, // if you adjust the padding in the CSS, you will need to update this variable
			containerID : document, // lightbox container object
			enableSlideshow : true, // enable slideshow feature
			googleAnalytics : false, // track individual image views using Google Analytics
			imageDataLocation : 'south', // location of image caption information
			initImage : '', // ID of image link to automatically launch when upon script initialization
			loop : true, // whether to continuously loop slideshow images
			overlayDuration : .2, // time to fade in shadow overlay
			overlayOpacity : .8, // transparency of shadow overlay
			prefix : '', // ID prefix for all dynamically created html elements
			relAttribute : 'lightbox', // specifies the rel attribute value that triggers lightbox
			resizeSpeed : 7, // controls the speed of the image resizing (1=slowest and 10=fastest)
			showGroupName : false, // show group name of images in image details
			slideTime : 2, // time to display images during slideshow
			strings : { // allows for localization
				closeLink : '<img src="images/lightview/closelabel.gif" alt="close"/>',
				loadingMsg : 'Chargement',
				nextLink : '<img src="images/lightview/fleche_next.gif" alt="Suivant">',
				prevLink : '<img src="images/lightview/fleche_prev.gif" alt="Pr&eacute;c&eacute;dent">',
				startSlideshow : '<img src="images/lightview/fleche_play.gif" alt="Démarrer">',
				stopSlideshow : '<img src="images/lightview/pause.gif" alt="Arr&ecirc;ter">',
				numDisplayPrefix : '',
				numDisplaySeparator : '/'
			}
        }).merge(options);
		
		if(this.options.get('animate')){
			this.overlayDuration = Math.max(this.options.get('overlayDuration'),0);
			this.options.set('resizeSpeed',Math.max(Math.min(this.options.get('resizeSpeed'),10),1));
			this.resizeDuration = (11 - this.options.get('resizeSpeed')) * 0.15;
		}else{
			this.overlayDuration = 0;
			this.resizeDuration = 0;
		}
		
		this.enableSlideshow = this.options.get('enableSlideshow');
		this.overlayOpacity = Math.max(Math.min(this.options.get('overlayOpacity'),1),0);
		this.playSlides = this.options.get('autoPlay');
		this.container = $(this.options.get('containerID'));
		this.relAttribute = this.options.get('relAttribute');
		this.updateImageList();
		
		var objBody = this.container != document ? this.container : document.getElementsByTagName('body').item(0);
		
		var objOverlay = document.createElement('div');
		objOverlay.setAttribute('id',this.getID('overlay'));
		objOverlay.style.display = 'none';
		objBody.appendChild(objOverlay);
		Event.observe(objOverlay,'click',this.end.bindAsEventListener(this));


//		objBody.appendChild(Builder.node('div',{id:'overlay'}));
	
        objBody.appendChild(Builder.node('div',{id:'lightbox'}, [
            Builder.node('div',{id:'outerImageContainer'}, [
				Builder.node('div',{id:'bottomNav'},
                        Builder.node('a',{id:'bottomNavClose', href: '#' },
                            Builder.node('img', { src: 'images/lightview/fermer_fenetre.gif' })
                        )
                    ),
                Builder.node('div',{id:'imageContainer'}, [
                    Builder.node('img',{id:'lightboxImage'}), 
                    Builder.node('div',{id:'loading'}, 
                        Builder.node('a',{id:'loadingLink', href: '#' }, 
                            Builder.node('img', {src: 'images/lightview/loading.gif'})
                        )
                    )
                ])
            ]),
            Builder.node('div', {id:'imageDataContainer'},
                Builder.node('div',{id:'imageData'}, [
                    Builder.node('div',{style:"float:left;"}, [
                        Builder.node('a',{id:'prevLink', href: '#' }, 
                            Builder.node('img', {src: 'images/lightview/fleche_prev.gif'})
                        ),
                        Builder.node('span',{id:'numberDisplay'}),
                        Builder.node('a',{id:'nextLink', href: '#' }, 
                            Builder.node('img', {src: 'images/lightview/fleche_next.gif'})
                        ),
                        Builder.node('a',{id:'slideShowControl', href: '#' }, 
                            Builder.node('img', {src: 'images/lightview/pause.gif'})
                        )
                    ]),
                    Builder.node('div',{style:'clear:both'}),
                    Builder.node('div',{id:'imageDetails'}, [
                    Builder.node('p', [
                        Builder.node('span',{id:'caption'}),
                        Builder.node('span',{id:'numberDisplay'})
                    ])
                    ])
                ])
            )
        ]));


//		$('overlay').hide().observe('click', (function() { this.end(); }).bind(this));
//		$('lightbox').hide().observe('click', (function(event) { if (event.element().id == 'lightbox') this.end(); }).bind(this));
		$('outerImageContainer').setStyle({ width: '250px', height: '250px' });
		$('prevLink').observe('click', this.showPrev.bindAsEventListener(this));
		$('nextLink').observe('click', this.showNext.bindAsEventListener(this));
		$('loadingLink').observe('click', this.end.bindAsEventListener(this));
		$('bottomNavClose').observe('click', this.end.bindAsEventListener(this));
		$('slideShowControl').observe('click', this.toggleSlideShow.bindAsEventListener(this));
		$('lightbox').hide();
/*
		Event.observe(objPrevLink,'click',this.showPrev.bindAsEventListener(this));
		Event.observe(objNextLink,'click',this.showNext.bindAsEventListener(this));
		Event.observe(objSlideShowControl,'click',this.toggleSlideShow.bindAsEventListener(this));
		Event.observe(objCloseLink,'click',this.end.bindAsEventListener(this));
		Event.observe(objPrevLinkImg,'click',this.showPrev.bindAsEventListener(this));
		Event.observe(objNextLinkImg,'click',this.showNext.bindAsEventListener(this));
		Event.observe(objLoadingLink,'click',this.end.bindAsEventListener(this));
*/
        var th = this;
        (function(){
            var ids = 
                'overlay lightbox outerImageContainer imageContainer lightboxImage prevLink nextLink loading loadingLink ' + 
                'imageDataContainer imageData imageDetails caption numberDisplay bottomNav bottomNavClose';   
            $w(ids).each(function(id){ th[id] = $(id); });
        }).defer();

		/*
		var objLightbox = document.createElement('div');
		objLightbox.setAttribute('id',this.getID('lightbox'));
		objLightbox.style.display = 'none';
		objBody.appendChild(objLightbox);
		
		
		
		
		var objImageDataContainer = document.createElement('div');
		objImageDataContainer.setAttribute('id',this.getID('imageDataContainer'));
		objImageDataContainer.className = this.getID('clearfix');

		var objImageData = document.createElement('div');
		objImageData.setAttribute('id',this.getID('imageData'));
		objImageDataContainer.appendChild(objImageData);
	
		var objImageDetails = document.createElement('div');
		objImageDetails.setAttribute('id',this.getID('imageDetails'));
		objImageData.appendChild(objImageDetails);
	

		var objDetailsNav = document.createElement('span');
		objDetailsNav.setAttribute('id',this.getID('detailsNav'));
		objImageDetails.appendChild(objDetailsNav);

		var objPrevLink = document.createElement('a');
		objPrevLink.setAttribute('id',this.getID('prevLinkDetails'));
		objPrevLink.setAttribute('href','javascript:void(0);');
		objPrevLink.innerHTML = this.options.get('strings').prevLink;
		objDetailsNav.appendChild(objPrevLink);
		Event.observe(objPrevLink,'click',this.showPrev.bindAsEventListener(this));
		
		var objNumberDisplay = document.createElement('span');
		objNumberDisplay.setAttribute('id',this.getID('numberDisplay'));
		objDetailsNav.appendChild(objNumberDisplay);

		var objNextLink = document.createElement('a');
		objNextLink.setAttribute('id',this.getID('nextLinkDetails'));
		objNextLink.setAttribute('href','javascript:void(0);');
		objNextLink.innerHTML = this.options.get('strings').nextLink;
		objDetailsNav.appendChild(objNextLink);
		Event.observe(objNextLink,'click',this.showNext.bindAsEventListener(this));

		var objSlideShowControl = document.createElement('a');
		objSlideShowControl.setAttribute('id',this.getID('slideShowControl'));
		objSlideShowControl.setAttribute('href','javascript:void(0);');
		objDetailsNav.appendChild(objSlideShowControl);
		Event.observe(objSlideShowControl,'click',this.toggleSlideShow.bindAsEventListener(this));

		var objCaption = document.createElement('span');
		objCaption.setAttribute('id',this.getID('caption'));
		objImageDetails.appendChild(objCaption);

		var objClose = document.createElement('div');
		objClose.setAttribute('id',this.getID('close'));
//		objImageData.appendChild(objClose);
		objLightbox.appendChild(objClose);
	
		var objCloseLink = document.createElement('a');
		objCloseLink.setAttribute('id',this.getID('closeLink'));
		objCloseLink.setAttribute('href','javascript:void(0);');
		objCloseLink.innerHTML = this.options.get('strings').closeLink;
		objClose.appendChild(objCloseLink);	
		Event.observe(objCloseLink,'click',this.end.bindAsEventListener(this));

		if(this.options.get('imageDataLocation') == 'north'){
			objLightbox.appendChild(objImageDataContainer);
		}
	
		var objOuterImageContainer = document.createElement('div');
		objOuterImageContainer.setAttribute('id',this.getID('outerImageContainer'));
		objLightbox.appendChild(objOuterImageContainer);

		var objImageContainer = document.createElement('div');
		objImageContainer.setAttribute('id',this.getID('imageContainer'));
		objOuterImageContainer.appendChild(objImageContainer);
	
		var objLightboxImage = document.createElement('img');
		objLightboxImage.setAttribute('id',this.getID('lightboxImage'));
		objImageContainer.appendChild(objLightboxImage);
	
		var objHoverNav = document.createElement('div');
		objHoverNav.setAttribute('id',this.getID('hoverNav'));
		objImageContainer.appendChild(objHoverNav);
	
		var objPrevLinkImg = document.createElement('a');
		objPrevLinkImg.setAttribute('id',this.getID('prevLinkImg'));
		objPrevLinkImg.setAttribute('href','javascript:void(0);');
		objHoverNav.appendChild(objPrevLinkImg);
		Event.observe(objPrevLinkImg,'click',this.showPrev.bindAsEventListener(this));
		
		var objNextLinkImg = document.createElement('a');
		objNextLinkImg.setAttribute('id',this.getID('nextLinkImg'));
		objNextLinkImg.setAttribute('href','javascript:void(0);');
		objHoverNav.appendChild(objNextLinkImg);
		Event.observe(objNextLinkImg,'click',this.showNext.bindAsEventListener(this));
	
		var objLoading = document.createElement('div');
		objLoading.setAttribute('id',this.getID('loading'));
		objImageContainer.appendChild(objLoading);
	
		var objLoadingLink = document.createElement('a');
		objLoadingLink.setAttribute('id',this.getID('loadingLink'));
		objLoadingLink.setAttribute('href','javascript:void(0);');
		objLoadingLink.innerHTML = this.options.get('strings').loadingMsg;
		objLoading.appendChild(objLoadingLink);
		Event.observe(objLoadingLink,'click',this.end.bindAsEventListener(this));
		
		if(this.options.get('imageDataLocation') != 'north'){
			objLightbox.appendChild(objImageDataContainer);
		}
		*/
		if(this.options.get('initImage') != ''){
			this.start($(this.options.get('initImage')));
		}
	},
	
	//
	//	updateImageList()
	//	Loops through specific tags within 'container' looking for 
	// 'lightbox' references and applies onclick events to them.
	//
	updateImageList: function(){
		var el, els, rel;
		for(var i=0; i < this.refTags.length; i++){
			els = this.container.getElementsByTagName(this.refTags[i]);
			for(var j=0; j < els.length; j++){
				el = els[j];
				rel = String(el.getAttribute('rel'));
				if (el.getAttribute('href') && (rel.toLowerCase().match(this.relAttribute))){
					el.onclick = function(){Lightbox.start(this); return false;}
				}
			}
		}
	},
		
	//
	//	start()
	//	Display overlay and lightbox. If image is part of a set, add siblings to imageArray.
	//
	start: function(imageLink) {	

		this.hideBadObjects();

		// stretch overlay to fill page and fade in
		var pageSize = this.getPageSize();
		$(this.getID('overlay')).setStyle({height:pageSize.pageHeight+'px'});
		new Effect.Appear(this.getID('overlay'), { duration: this.overlayDuration, from: 0, to: this.overlayOpacity });

		this.imageArray = [];
		this.groupName = null;
		
		var rel = imageLink.getAttribute('rel');
		var imageTitle = '';
		
		// if image is NOT part of a group..
		if(rel == this.relAttribute){
			// add single image to imageArray
			imageTitle = imageLink.getAttribute('title') ? imageLink.getAttribute('title') : '';
			this.imageArray.push({'link':imageLink.getAttribute('href'), 'title':imageTitle});			
			this.startImage = 0;
		} else {
			// if image is part of a group..
			var els = this.container.getElementsByTagName(imageLink.tagName);
			// loop through anchors, find other images in group, and add them to imageArray
			for (var i=0; i<els.length; i++){
				var el = els[i];
				if (el.getAttribute('href') && (el.getAttribute('rel') == rel)){
					imageTitle = el.getAttribute('title') ? el.getAttribute('title') : '';
					this.imageArray.push({'link':el.getAttribute('href'),'title':imageTitle});
					if(el == imageLink){
						this.startImage = this.imageArray.length-1;
					}
				}
			}
			// get group name
			this.groupName = rel.substring(this.relAttribute.length+1,rel.length-1);
		}

		// calculate top offset for the lightbox and display 
		var pageScroll = this.getPageScroll();
		var lightboxTop = pageScroll.y + (pageSize.winHeight / 15);

		$(this.getID('lightbox')).setStyle({top:lightboxTop+'px'}).show();
		this.changeImage(this.startImage);
	},

	//
	//	changeImage()
	//	Hide most elements and preload image in preparation for resizing image container.
	//
	changeImage: function(imageNum){	
		this.activeImage = imageNum;

		this.disableKeyboardNav();
		this.pauseSlideShow();

		// hide elements during transition
		$(this.getID('loading')).show();
		$(this.getID('lightboxImage')).hide();
//		$(this.getID('hoverNav')).hide();
		$(this.getID('imageDataContainer')).hide();
		$(this.getID('numberDisplay')).hide();
//		$(this.getID('detailsNav')).hide();
		
		var imgPreloader = new Image();
		
		// once image is preloaded, resize image container
		imgPreloader.onload=function(){
			$(Lightbox.getID('lightboxImage')).src = imgPreloader.src;
			Lightbox.resizeImageContainer(imgPreloader.width,imgPreloader.height);
		}
		imgPreloader.src = this.imageArray[this.activeImage].link;
		
		if(this.options.get('googleAnalytics')){
			urchinTracker(this.imageArray[this.activeImage].link);
		}
	},

	//
	//	resizeImageContainer()
	//
	resizeImageContainer: function(imgWidth,imgHeight) {
		imgWidth = Math.max(imgWidth,150);
		// get current height and width
		var cDims = $(this.getID('outerImageContainer')).getDimensions();

		// scalars based on change from old to new
		var xScale = ((imgWidth  + (this.options.get('borderSize') * 2)) / cDims.width) * 100;
		var yScale = ((imgHeight  + (this.options.get('borderSize') * 2)) / cDims.height) * 100;

		// calculate size difference between new and old image, and resize if necessary
		var wDiff = (cDims.width - this.options.get('borderSize') * 2) - imgWidth;
		var hDiff = (cDims.height - this.options.get('borderSize') * 2) - imgHeight;

		if(!( hDiff == 0)){ new Effect.Scale(this.getID('outerImageContainer'), yScale, {scaleX: false, duration: this.resizeDuration, queue: 'front'}); }
		if(!( wDiff == 0)){ new Effect.Scale(this.getID('outerImageContainer'), xScale, {scaleY: false, delay: this.resizeDuration, duration: this.resizeDuration}); }

		// if new and old image are same size and no scaling transition is necessary, 
		// do a quick pause to prevent image flicker.
		if((hDiff == 0) && (wDiff == 0)){
			if(navigator.appVersion.indexOf('MSIE')!=-1){ this.pause(250); } else { this.pause(100);} 
		}

//		$(this.getID('prevLinkImg')).setStyle({height:imgHeight+'px'});
//		$(this.getID('nextLinkImg')).setStyle({height:imgHeight+'px'});
		$(this.getID('imageDataContainer')).setStyle({width:(imgWidth+(this.options.get('borderSize') * 2))+'px'});

		this.showImage();
	},
	
	//
	//	showImage()
	//	Display image and begin preloading neighbors.
	//
	showImage: function(){
		$(this.getID('loading')).hide();
		new Effect.Appear(this.getID('lightboxImage'), { duration: 0.5, queue: 'end', afterFinish: function(){	Lightbox.updateDetails(); } });
		this.preloadNeighborImages();
	},

	//
	//	updateDetails()
	//	Display caption, image number, and bottom nav.
	//
	updateDetails: function() {
		$(this.getID('caption')).show();
		$(this.getID('caption')).update(this.imageArray[this.activeImage].title);
		
		// if image is part of set display 'Image x of y' 
		if(this.imageArray.length > 1){
			var num_display = this.options.get('strings').numDisplayPrefix + ' ' + eval(this.activeImage + 1) + ' ' + this.options.get('strings').numDisplaySeparator + ' ' + this.imageArray.length;
			if(this.options.get('showGroupName') && this.groupName != ''){
				num_display += ' '+this.options.get('strings').numDisplaySeparator+' '+this.groupName;
			}
			$(this.getID('numberDisplay')).update(num_display).show();
			if(!this.enableSlideshow){
				$(this.getID('slideShowControl')).hide();
			}
//			$(this.getID('detailsNav')).show();
		}
		
		new Effect.Parallel(
			[ new Effect.SlideDown( this.getID('imageDataContainer'), { sync: true }), 
			  new Effect.Appear(this.getID('imageDataContainer'), { sync: true }) ], 
			{ duration:.65, afterFinish: function() { Lightbox.updateNav();} } 
		);
	},
	
	//
	//	updateNav()
	//	Display appropriate previous and next hover navigation.
	//
	updateNav: function() {
		if(this.imageArray.length > 1){
//			$(this.getID('hoverNav')).show();
			if(this.enableSlideshow){
				if(this.playSlides){
					this.startSlideShow();
				} else {
					this.stopSlideShow();
				}
			}
		}
		this.enableKeyboardNav();
	},
	//
	//	startSlideShow()
	//	Starts the slide show
	//
	startSlideShow: function(){
		this.playSlides = true;
		this.slideShowTimer = new PeriodicalExecuter(function(pe){ Lightbox.showNext(); pe.stop(); },this.options.get('slideTime'));
		var e=$(this.getID('slideShowControl'));
		if (e.innerHTML != this.options.get('strings').stopSlideshow)
			$(this.getID('slideShowControl')).update(this.options.get('strings').stopSlideshow);
	},
	
	//
	//	stopSlideShow()
	//	Stops the slide show
	//
	stopSlideShow: function(){
		this.playSlides = false;
		if(this.slideShowTimer){
			this.slideShowTimer.stop();
		}
		var e=$(this.getID('slideShowControl'));
		if (e.innerHTML != this.options.get('strings').startSlideshow)
			$(this.getID('slideShowControl')).update(this.options.get('strings').startSlideshow);
	},

	//
	//	stopSlideShow()
	//	Stops the slide show
	//
	toggleSlideShow: function(){
		if(this.playSlides){
			this.stopSlideShow();
		}else{
			this.startSlideShow();
		}
	},

	//
	//	pauseSlideShow()
	//	Pauses the slide show (doesn't change the value of this.playSlides)
	//
	pauseSlideShow: function(){
		if(this.slideShowTimer){
			this.slideShowTimer.stop();
		}
	},
	
	//
	//	showNext()
	//	Display the next image in a group
	//
	showNext : function(){
		if(this.imageArray.length > 1){
			if(!this.options.get('loop') && ((this.activeImage == this.imageArray.length - 1 && this.startImage == 0) || (this.activeImage+1 == this.startImage))){
				return this.end();
			}
			if(this.activeImage == this.imageArray.length - 1){
				this.changeImage(0);
			}else{
				this.changeImage(this.activeImage+1);
			}
		}
	},

	//
	//	showPrev()
	//	Display the next image in a group
	//
	showPrev : function(){
		if(this.imageArray.length > 1){
			if(this.activeImage == 0){
				this.changeImage(this.imageArray.length - 1);
			}else{
				this.changeImage(this.activeImage-1);
			}
		}
	},
	
	//
	//	showFirst()
	//	Display the first image in a group
	//
	showFirst : function(){
		if(this.imageArray.length > 1){
			this.changeImage(0);
		}
	},

	//
	//	showFirst()
	//	Display the first image in a group
	//
	showLast : function(){
		if(this.imageArray.length > 1){
			this.changeImage(this.imageArray.length - 1);
		}
	},

	//
	//	enableKeyboardNav()
	//
	enableKeyboardNav: function() {
		document.onkeydown = this.keyboardAction; 
	},

	//
	//	disableKeyboardNav()
	//
	disableKeyboardNav: function() {
		document.onkeydown = '';
	},

	//
	//	keyboardAction()
	//
	keyboardAction: function(e) {
		if (e == null) { // ie
			keycode = event.keyCode;
		} else { // mozilla
			keycode = e.which;
		}

		key = String.fromCharCode(keycode).toLowerCase();
		
		if(key == 'x' || key == 'o' || key == 'c'){ // close lightbox
			Lightbox.end();
		} else if(key == 'p' || key == '%'){ // display previous image
			Lightbox.showPrev();
		} else if(key == 'n' || key =='\''){ // display next image
			Lightbox.showNext();
		} else if(key == 'f'){ // display first image
			Lightbox.showFirst();
		} else if(key == 'l'){ // display last image
			Lightbox.showLast();
		} else if(key == 's'){ // toggle slideshow
			if(Lightbox.imageArray.length > 0 && Lightbox.options.enableSlideshow){
				Lightbox.toggleSlideShow();
			}
		}
	},

	//
	//	preloadNeighborImages()
	//	Preload previous and next images.
	//
	preloadNeighborImages: function(){
		var nextImageID = this.imageArray.length - 1 == this.activeImage ? 0 : this.activeImage + 1;
		nextImage = new Image();
		nextImage.src = this.imageArray[nextImageID].link

		var prevImageID = this.activeImage == 0 ? this.imageArray.length - 1 : this.activeImage - 1;
		prevImage = new Image();
		prevImage.src = this.imageArray[prevImageID].link;
	},

	//
	//	end()
	//
	end: function() {
		this.disableKeyboardNav();
		this.pauseSlideShow();
		$(this.getID('lightbox')).hide();
		new Effect.Fade(this.getID('overlay'), { duration:this.overlayDuration });
		this.showBadObjects();
	},
	
	//
	//	showBadObjects()
	//
	showBadObjects: function (){
		var els;
		var tags = Lightbox.badObjects;
		for(var i=0; i<tags.length; i++){
			els = document.getElementsByTagName(tags[i]);
			for(var j=0; j<els.length; j++){
				$(els[j]).setStyle({visibility:'visible'});
			}
		}
	},
	
	//
	//	hideBadObjects()
	//
	hideBadObjects: function (){
		var els;
		var tags = Lightbox.badObjects;
		for(var i=0; i<tags.length; i++){
			els = document.getElementsByTagName(tags[i]);
			for(var j=0; j<els.length; j++){
				$(els[j]).setStyle({visibility:'hidden'});
			}
		}
	},
		
	//
	// pause(numberMillis)
	// Pauses code execution for specified time. Uses busy code, not good.
	// Code from http://www.faqts.com/knowledge_base/view.phtml/aid/1602
	//
	pause: function(numberMillis) {
		var now = new Date();
		var exitTime = now.getTime() + numberMillis;
		while(true){
			now = new Date();
			if (now.getTime() > exitTime)
				return;
		}
	},

	//
	// getPageScroll()
	// Returns array with x,y page scroll values.
	// Core code from - quirksmode.org
	//
	getPageScroll: function(){
		var x,y;
		if (self.pageYOffset) {
			x = self.pageXOffset;
			y = self.pageYOffset;
		} else if (document.documentElement && document.documentElement.scrollTop){	 // Explorer 6 Strict
			x = document.documentElement.scrollLeft;
			y = document.documentElement.scrollTop;
		} else if (document.body) {// all other Explorers
			x = document.body.scrollLeft;
			y = document.body.scrollTop;
		}
		return {x:x,y:y};
	},

	//
	// getPageSize()
	// Returns array with page width, height and window width, height
	// Core code from - quirksmode.org
	// Edit for Firefox by pHaez
	//
	getPageSize: function(){
		var scrollX,scrollY,windowX,windowY,pageX,pageY;
		if (window.innerHeight && window.scrollMaxY) {	
			scrollX = document.body.scrollWidth;
			scrollY = window.innerHeight + window.scrollMaxY;
		} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
			scrollX = document.body.scrollWidth;
			scrollY = document.body.scrollHeight;
		} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
			scrollX = document.body.offsetWidth;
			scrollY = document.body.offsetHeight;
		}
		
		if (self.innerHeight) {	// all except Explorer
			windowX = self.innerWidth;
			windowY = self.innerHeight;
		} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
			windowX = document.documentElement.clientWidth;
			windowY = document.documentElement.clientHeight;
		} else if (document.body) { // other Explorers
			windowX = document.body.clientWidth;
			windowY = document.body.clientHeight;
		}	
		
		pageY = (scrollY < windowY) ? windowY : scrollY; // for small pages with total height less then height of the viewport
		pageX = (scrollX < windowX) ? windowX : scrollX; // for small pages with total width less then width of the viewport
	
		return {pageWidth:pageX,pageHeight:pageY,winWidth:windowX,winHeight:windowY};
	},

	//
	// getID()
	// Returns formatted Lightbox element ID
	//
	getID: function(id){
		return this.options.get('prefix')+id;
	}
}

// -----------------------------------------------------------------------------------

Event.observe(window,'load',function(){ Lightbox.initialize(); });/**
 * RUZEE.ShadedBorder 0.6.1
 * (c) 2006 Steffen Rusitschka
 *
 * RUZEE.ShadedBorder is freely distributable under the terms of an MIT-style license.
 * For details, see http://www.ruzee.com/
 *
 * Tweaked by Piotr.
 *
 * Called by the example page 'Simple.html', in a way like:
 *
 * var renderer = new ShaBoRenderer();
 * renderer.Init({ corner:8, shadow:16 });
 * renderer.RenderElement('my-border');
 * renderer.Dispose();
 * renderer = null;
 */

//-----------------------------------------------------------------------------------------
// Static
//-----------------------------------------------------------------------------------------

//
// Add our styles to the document
//
document.write('\
	<style type="text/css">\
  	.sb, .sbi, .sb *, .sbi * { position:relative; z-index:1; }\
  	* html .sb, * html .sbi { height:1%; }\
  	.sbi { display:inline-block; }\
  	.sb-inner { background:#ddd; }\
  	.sb-shadow { background:#000; }\
  	.sb-border { background:#bbb; }\
  	</style>\
');

//-----------------------------------------------------------------------------------------
// Object ShaBoRenderer
//-----------------------------------------------------------------------------------------

function ShaBoRenderer() {

    //-----------------------------------------------------------------------------------------
	// Public methods
    //-----------------------------------------------------------------------------------------

	this.Init = init;
	this.RenderElement = renderElement;
	this.RenderElements = renderElements;
	this.Dispose = dispose;

	//-----------------------------------------------------------------------------------------
	// Private member fields - String
    //-----------------------------------------------------------------------------------------

	// Shadow class name
	//
	var sclass;

	// Border class name
	//
	var bclass;

	// Inner class name
	//
	var iclass;

	// innerHTML strings
	//
	var tlInnerHTML;
	var trInnerHTML;
	var brInnerHTML;
	var blInnerHTML;
	var tsInnerHTML;
	var bsInnerHTML;
	var mwInnerHTML;

	//-----------------------------------------------------------------------------------------
	// Private member fields - integer
    //-----------------------------------------------------------------------------------------

  	// Shadow size (radius)
  	//
  	var sr;

	// Corder size (radius)
	//
	var r;

	// Border radius?
	//
	var bor;

	// Border width
	//
	var bow;

	// Border opacity
	//
	var boo;

	// Left width
	//
	var lw;

	// Right width
	//
	var rw;

	// Top height
	//
	var th;

	// Bottom height
	//
	var bh;

	// Center point x?
	//
	var cx;

	// Center point y?
	//
	var cy;

	// Center point shadow?
	//
	var cs;

	//-----------------------------------------------------------------------------------------
	// Private member fields - boolean
    //-----------------------------------------------------------------------------------------

	// Debug flag
	//
	var debug = false;

	// Boolean whether the user agent is IE.
	//
	var isie = /msie/i.test(navigator.userAgent) && !window.opera;

  	// Boolean whether the user agent is IE6.
  	//
  	var isie6 = isie && !window.XMLHttpRequest;

    //-----------------------------------------------------------------------------------------
	// Public initializing
    //-----------------------------------------------------------------------------------------

	// Initialize the borders
	// @param opts An array with options.
	// @return void
	//
	function init(opts) {
		//
		// (Re-)initialize member fields as per options passed
		//
	  	sr = opts.shadow || 0;
	  	r = opts.corner || 0;
	  	bor = 0;
	  	bow = opts.border || 0;
	  	boo = opts.borderOpacity || 1;
	  	lw = r > sr ? r : sr;
	  	rw = lw;
	  	th = lw;
	  	bh = lw;
	  	//
	  	if (bow > 0) {
	    	bor = r;
	    	r = r - bow;
	  	}
	    //
	  	cx = r != 0 && sr != 0 ? Math.round(lw / 3) : 0;
	  	cy = cx;
	  	cs = Math.round(cx / 2);
	  	//
	  	// The edges String - Defaults to "trlb" (Top Right Left Bottom)
	  	// Used to initialize th, bh, lw and rw
	  	//
		var edges = opts.edges || "trlb";
	  	//
	  	if (!/t/i.test(edges)) th = 0;
	  	if (!/b/i.test(edges)) bh = 0;
	  	if (!/l/i.test(edges)) lw = 0;
	  	if (!/r/i.test(edges)) rw = 0;
	  	//
	  	edges = null;

	  	// ------------------------------------------------------------------------------------
	  	// Start Style Classes Hack
		// ------------------------------------------------------------------------------------

		/*
			This is a small hack to allow for setting different pseudo class names than
			the default: sb-inner, sb-border and sb-shadow
			This is important since it allows for shaded border elements to contain
			other shaded border elements. Using the default pseudo class names for both,
			often (in GWT) results in the parent element's psuedo class name overriding the
			one of the element, and, thus, unpredicted behaviour.

			The following options may be added:

			innerClassName
			borderClassName
			shadowClassName

			The original code was:

		  	var iclass = r > 0 ? "sb-inner" : "sb-shadow";
		  	var sclass = "sb-shadow";
		  	var bclass = "sb-border";

	  	*/

		//
		// Style classes
		//
	  	sclass = (opts.shadowClassName ? opts.shadowClassName : "sb-shadow");
	  	bclass = (opts.borderClassName ? opts.borderClassName : "sb-border");
	  	iclass = r > 0 ? (opts.innerClassName ? opts.innerClassName : "sb-inner") : sclass;

	  	// ------------------------------------------------------------------------------------
	  	// End hack
	  	// ------------------------------------------------------------------------------------

	  	// ------------------------------------------------------------------------------------
	  	// Memory Leaks Notes
		//
		// Below shows the structure of the original code:
		//
		// corner(tl, true, true);
	  	// corner(tr, true, false);
	  	// corner(bl, false, true);
	  	// corner(br, false, false);
	  	// mid(mw);
	  	// tb(t, true);
	  	// tb(b, false);
	  	//
		// Running the code as above causes hugh memory leaks in IE.
		//
	  	// TESTED as follows with 'Drip':
	  	// @see http://www.outofhanwell.com/ieleak/index.php?title=Main_Page
	  	//
	  	// var s = corner(true, true);
	  	// if (true) return; // NO mem leak showing in Drip
	  	// tl.innerHTML = s;
	  	//
	  	// var s = corner(true, true);
	  	// /* if (true) return;*/
	  	// tl.innerHTML = s; // Mem leak in Drip after this statement
	  	//
	  	// On the 'Simple.html' page this setup causes approx. 396 leaks!
		//
		// @see: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/IETechCol/dnwebgen/ie_leak_patterns.asp
		// @see: http://ecmascript.stchur.com/blogcode/ie_innerhtml_memleak/leak.html
		// @see: http://jibbering.com/faq/faq_notes/closures.html#clMem
		// @see: http://tests.novemberborn.net/javascript/memory-leakage/memory-leakage.html
		// @see: http://blog.grimpoteuthis.org/2005/01/dhtml-leaks-like-sieve.html
		// @see: http://www.quirksmode.org/blog/archives/2005/02/javascript_memo.html
		//
		// The problem is that, in the functions as called, the passed element's innerHTML is set,
		// before the element has been added to the DOM. Actually, the element is never added, but
		// used for cloning. Still, setting the innerHTML like this causes the leaks.
		//
		// To avoid memory leaks we'll have to add the elements to the DOM first,
		// then set the innerHTML.
		//
		// @see: http://ecmascript.stchur.com/blogcode/ie_innerhtml_memleak/noleak.html
		// @see: http://tests.novemberborn.net/javascript/memory-leakage/event-cache.html
		//
		// A different approach has been made.
		//
		// - The elements, that are used for cloning, are created, and added to a hidden div container.
		// - innerHTML as required for the elements are created but left in class member fields
		// - Upon cloning the base elements in the render operation, the innerHTML is set just before
		//   the cloned element is added to the DOM.
		// - The dispose method will set the innerHTML member fields to null.
		// - The hidden div container is (for now) left, since removing it also causes a (small) memory
		//   leak. [TODO]

		// The hidden div that will contain the div's to be cloned
		//
	  	ensureDivContainer();
		//
	  	// An array used to style the div elements
	  	//
	  	var styles = { position: "absolute",
		  				left: "0",
		  				top: "0",
		  				width: lw + "px",
		  				height: th + "px",
		            	ie_fontSize: "1px",
		            	overflow: "hidden",
		            	margin: "0",
		            	padding: "0"
	            	};

	  	//
	  	// Initialize elements that are cloned - TODO: Check MemLeaks - DONE
	  	//
	  	// Top Left Element
	  	//
	  	ensureDiv("_shaboren_tl", styles, true);
		//
		// Re-adjust array
		//
	  	delete styles.left;
	  	styles.right = "0";
	  	styles.width = rw + "px";
	  	//
	  	// Top Right Element
	  	//
	  	ensureDiv("_shaboren_tr", styles, true);
		//
		// Readjust array
		//
	  	delete styles.top;
	  	styles.bottom = "0";
	  	styles.height = bh + "px";
	  	//
	  	// Bottom Right Element
	  	//
	  	ensureDiv("_shaboren_br", styles, true);
		//
		// Readjust array
		//
	  	delete styles.right;
	  	styles.left = "0";
	  	styles.width = lw + "px";
	  	//
	  	// Bottom Left Element
	  	//
	  	ensureDiv("_shaboren_bl", styles, true);
		//
	  	// T W Element
	  	//
	  	var tw = ensureDiv("_shaboren_tw",
  						{ position: "absolute",
  						width: "100%",
  						height: th + "px",
  						ie_fontSize: "1px",
  						top: "0",
  						left: "0",
  						overflow: "hidden",
  						margin: "0",
  						padding: "0"},
  						true);
	  	//
	  	// T Element
	  	//
	  	var t = ensureDiv("_shaboren_t",
	  					{ position: "relative",
  						height: th + "px",
  						ie_fontSize: "1px",
                  		margin: "0 "+ rw + "px 0 " + lw + "px",
                  		overflow: "hidden",
                  		padding: "0"},
                  		false);
	  	//
	  	if (tw.firstChild == null) {
	  		tw.appendChild(t);
	  	}
		//
	  	// B W Element
	  	//
	  	var bw = ensureDiv("_shaboren_bw",
	  					{ position: "absolute",
  						left: "0",
  						bottom: "0",
  						width: "100%",
  						height: bh + "px",
                 		ie_fontSize: "1px",
                 		overflow: "hidden",
                 		margin: "0",
                 		padding: "0" },
                 		true);
	    //
	  	// B Element
	  	//
	  	var b = ensureDiv("_shaboren_b",
	  					{ position: "relative",
  						height: bh + "px",
  						ie_fontSize: "1px",
                  		margin: "0 "+ rw + "px 0 " + lw + "px",
                  		overflow: "hidden",
                  		padding: "0" },
                  		false);
	    //
	  	if (bw.firstChild == null) {
	  		bw.appendChild(b);
	  	}
		//
	  	// M W Element
	  	//
	  	ensureDiv("_shaboren_mw",
	  					{ position: "absolute",
  						top: (-bh) + "px",
  						left: "0",
  						width: "100%",
  						height: "100%",
                   		overflow: "hidden",
                   		ie_fontSize: "1px",
                   		padding: "0",
                   		margin: "0" },
                   		true);
		//
		styles = null;
		//
		// Create innerHTML
		//
	  	tlInnerHTML = corner(true, true);
	  	trInnerHTML = corner(true, false);
	  	blInnerHTML = corner(false, true);
	  	brInnerHTML = corner(false, false);
	  	mwInnerHTML = mid();
	  	tsInnerHTML = tb(true);
	  	bsInnerHTML = tb(false);
		//
	  	// TESTED with Drip: No leaks after the above
		//
		tw = null;
		t = null;
		bw = null;
		b = null;
	}

	//-----------------------------------------------------------------------------------------
	// Public rendering
    //-----------------------------------------------------------------------------------------

	// Renders the border for passed element.
	// @param elementId The element object or element id string.
	// @return void
	//
	function renderElement(element) {
		doRender(element);
	}

	// Renders the borders of elements within passed array.
	// @param elementArray The array with element objects or element id strings.
	// @return void
	//
	function renderElements(elementArray) {
		if (elementArray.length != undefined) {
    		for (var i = 0; i < elementArray.length; ++i) {
    			doRender(elementArray[i]);
    		}
  		}
	}

	//-----------------------------------------------------------------------------------------
	// Private rendering
    //-----------------------------------------------------------------------------------------

	// Renders the border for passed element id.
	// @param elementId The element id to render for.
	// @return void
	//
	function doRender(element) {
		if (debug) {
			if (typeof element.outerHTML !== 'undefined') {
				// IE
				alert("Render for \n" + element.outerHTML);
			}
			else {
				alert("Render for \n" + element.innerHTML);
			}
		}
		var el;
		if (typeof element == 'string') {
			el = document.getElementById(element);
			if (el == undefined) {
				if (debug) {
					alert("Element not found: " + element);
				}
				return;
			}
		}
		else {
			el = element;
		}
		//
      	// Changed by Piotr - Do not add the style name if it is already present
      	// ORG code: el.className += (" sb");
  		//
  		if (el.className.indexOf(" sb") == -1) {
    		el.className += (" sb");
  		}
		//
  		// Apply style
  		//
  		applyStyle(el, { position:"relative", background:"transparent" });
  		//
  		// Remove 'any former' generated children
  		// For instance on a second time rendering
  		//
  		var node = el.firstChild;
  		var nextNode;
  		while (node) {
    		nextNode = node.nextSibling;
    		if (node.nodeType == 1 && node.className == 'sb-gen') {
      			el.removeChild(node);
      		}
    		node = nextNode;
  		}
  		nextNode = null;
		node = null;
		//
		// Clone elements and set innerHTML
		//
  		var iel = el.firstChild;
		//
		// Fields required for IE
		//
  		var twc = createClone("_shaboren_tw"); // child = t
  		var mwc = createClone("_shaboren_mw");
  		var bwc = createClone("_shaboren_bw"); // child = b
		//
		var tl = createClone("_shaboren_tl");
		el.insertBefore(tl, iel);
		tl.innerHTML = tlInnerHTML;
		//
		var tr = createClone("_shaboren_tr");
		el.insertBefore(tr, iel);
		tr.innerHTML = trInnerHTML;
		//
		var bl = createClone("_shaboren_bl");
		el.insertBefore(bl, iel);
		bl.innerHTML = blInnerHTML;
		//
		var br = createClone("_shaboren_br");
		el.insertBefore(br, iel);
		br.innerHTML = brInnerHTML;
		//

		el.insertBefore(twc, iel);
  		twc.firstChild.innerHTML = tsInnerHTML;


		el.insertBefore(mwc, iel);
  		mwc.innerHTML = mwInnerHTML;



		el.insertBefore(bwc, iel);
  		bwc.firstChild.innerHTML = bsInnerHTML;

  		tl = null;
		tr = null;
		br = null;
		bl = null;

  		//
  		// IE6 mouse and IE resize handling
  		//

  		if (isie6) {
    		el.onmouseover = function() {
    			//
    			// Piotr, note: 'this' is the element that has this function ;-)
    			//
    			this.className += " hover";
    		}
    		el.onmouseout = function() {
    			this.className = this.className.replace(/ hover/,"");
    		}
  		}

  		if (isie) {
  			//
    		function resize() {
      			twc.style.width = bwc.style.width = mwc.style.width = el.offsetWidth + "px";
      			mwc.firstChild.style.height = el.offsetHeight + "px";
    		}
    		el.onresize = resize;
    		resize();
  		}
  		//
  		// We cannot set the values to null, since they are used
  		// within the resize handler above
  		//
  		//iel = null;
  		//twc = null;
  		//bwc = null;
  		//mwc = null;
  		//el = null;

	}

	//-----------------------------------------------------------------------------------------
	// Public dispose
    //-----------------------------------------------------------------------------------------

	// Disposes member field objects within this object.
	// @return void
	//
	function dispose() {
		tlInnerHTML = trInnerHTML = brInnerHTML = blInnerHTML = tsInnerHTML = bsInnerHTML = mwInnerHTML = null;
		sclass = bclass = iclass = null;
		removeDivContainer(); // Note: Function removeDivContainer is disabled until the small Mem leak solved
	}

    //-----------------------------------------------------------------------------------------
	// Private utilities
    //-----------------------------------------------------------------------------------------

	// Creates a clone of an element that has passed id
	// @param id The id
	// @return The cloned element
	//
	function createClone(id) {
		var element = document.getElementById(id);
		if (element != null) {
			var clone = element.cloneNode(true);
			clone.removeAttribute("id");
			if (clone.firstChild) {
				clone.firstChild.removeAttribute("id");
			}
			return clone;
		}
		return null;
	}

	// Deletes a node, by deleting all it's children and their children and theirs... ;-)
	// @param node The node.
  	// @return void
  	//
	function deleteNode(node) {
		if (node) {
			//
 	    	deleteChildren(node);
	        if (typeof node.outerHTML !== 'undefined') {
	        	node.outerHTML = ''; //prevent pseudo-leak in IE
	        }
	        else {
	        	if (node.parentNode) {
	            	node.parentNode.removeChild(node);
	            }
	            delete node; //clean up just to be sure
	       }
		}
	}

	// Deletes a node's children', by deleting all it's children and their children and theirs... ;-)
	// @param node The node.
  	// @return void
  	//
	function deleteChildren(node) {
		if (node) {
			for (var i = node.childNodes.length - 1; i >= 0; i--) {
				var childNode = node.childNodes[i];
  				if (childNode.hasChildNodes()) {
          			deleteChildren(childNode);
          		}
  				if (typeof childNode.outerHTML !== 'undefined') {
          			childNode.outerHTML = ''; //prevent pseudo-leak in IE
          		}
          		else {
	          		node.removeChild(childNode);
          		}
  				delete childNode; //clean up just to be sure
	       	}
		}
	}

	// Ensures a hidden div container.
  	// @return The hidden div container.
  	//
	function ensureDivContainer() {
		var cont = document.getElementById("__ShaBoRendererDivContainer");
		if (cont == null) {
			cont = document.createElement("div");
			cont.setAttribute("id", "__ShaBoRendererDivContainer");
		  	document.body.appendChild(cont);
		  	cont.style["position"] = "absolute";
		  	cont.style["left"] = "-9999px";
		  	cont.style["display"] = "none";
		}
		return cont;
	}

	// Gets the hidden div container.
	// Null if not created.
  	// @return The hidden div container.
  	//
  	function getDivContainer() {
		return document.getElementById("__ShaBoRendererDivContainer");
	}

	// Remove the hidden div container.
	// THIS FUNCTION IS DISABLED UNTIL THE SMALL MEM LEAK THAT IS CAUSED IS RESOLVED
	// This isn't a hugh problem since the container only contains a small amount of nodes.
  	// @return void
  	//
	function removeDivContainer() {
		/*
		var cont = getDivContainer();
		if (cont != undefined) {
			//
			// Causes small memory leak: document.body.removeChild(cont);
			// Also causes small memory leak: deleteNode(cont);
			//
		}
		*/
	}

	// Ensures a DIV with passed id exists within the hidden div container.
	// Assumes the hidden div container is available.
	// Styles the div with passed styles.
	// Assumes the passed style names are alwyas the same.
	// @param id The div's id.
  	// @param stylesArray an array with styles.
  	// @param doAdd Whether to add the element if created.
  	// @return The created DIV element
  	//
  	function ensureDiv(id, stylesArray, doAdd) {
  		var element = document.getElementById(id);
  		if (element == null) {
  			return createDiv(id, stylesArray, doAdd);
  		}
  		//
  		// No need to remove styles first, the style names
  		// are assumed to be always the same
  		//
  		applyStyle(element, stylesArray);
    	return element;
  	}

	// Creates a DIV with passed id in the hidden div container.
	// Assumes the hidden div container is available.
	// Styles the div with passed styles.
	// Assumes the passed style names are alwyas the same.
	// @param id The div's id.
  	// @param stylesArray an array with styles.
  	// @param doAdd Whether to add the element if created.
  	// @return The created DIV element
  	//
  	function createDiv(id, stylesArray, doAdd) {
    	var element = document.createElement("div");
    	element.setAttribute("id", id);
    	element.className = "sb-gen";
    	applyStyle(element, stylesArray);
    	if (doAdd) {
	    	var cont = getDivContainer();
    		cont.appendChild(element);
    	}
    	return element;
  	}

  	// Styles the passed element with passed styles array.
  	// param element The element.
  	// param stylesArray An array with styles.
  	// @return void
  	//
  	function applyStyle(element, stylesArray) {
    	for (name in stylesArray) {
      		if (/ie_/.test(name)) {
        		if (isie) {
        			element.style[name.substr(3)] = stylesArray[name];
        		}
      		}
      		else {
      			element.style[name] = stylesArray[name];
      		}
    	}
  	}

  	// Creates an opacity string.
  	// param value integer The requested opacity.
  	// @return The opacity string
  	//
  	function createOpacityString(value) {
    	if (value > 0.99999) {
    		return "";
    	}
    	value = value < 0 ? 0 : value;
    	return isie ? " filter:alpha(opacity=" + (value * 100) + ");" : " opacity:" + value + ';';
  	}

  	// Create the corners inner htnl.
  	// @param isTop boolean Whether top.
  	// @param isLeft boolean Whether left.
  	// String The innerHTML for an element.
  	//
  	function corner(isTop, isLeft) {
    	// Arrays
    	//
    	var dsb = [];
    	var dsi = [];
    	var dss = [];

    	// ints
    	//
    	var w = isLeft ? lw : rw;
    	var h = isTop ? th : bh;
    	var s = isTop ? cs : -cs;

    	// ints - const values
    	//
    	var xd = isLeft ? -1 : 1;
   		var yd = isTop ? 1 : -1;

    	// This value is changed as per loop
    	//
    	var xp = isLeft ? (w - 1) : 0;

    	for (var x = 0; x < w; ++x) {

      		// This value is changed as per loop
    		//
      		var yp = isTop ? 0 : h - 1;

      		var finished = false;

      		for (var y = h - 1 ; y >= 0 && !finished; --y) {

        		var div = '<div style="position:absolute; top:' + yp + 'px; left:' + xp + 'px; ' +
                  	'width:1px; height:1px; overflow:hidden; margin:0; padding:0;';

        		var xc = x - cx;
        		var yc = y - cy - s;
        		var d = Math.sqrt(xc * xc + yc * yc);
        		var doShadow = false;

        		if (r > 0) {
        			//
          			// draw border
          			//
          			if (xc < 0 && yc < bor && yc >= r || yc < 0 && xc < bor && xc >= r) {
            			dsb.push(div + createOpacityString(boo) + '" class="' + bclass + '"></div>');
          			}
          			else if (d < bor && d >= r - 1 && xc >= 0 && yc >= 0) {
            			var dd = div;
            			if (d >= bor - 1) {
              				dd += createOpacityString((bor - d) * boo);
              				doShadow = true;
            			}
            			else {
            				dd += createOpacityString(boo);
            			}
            			dsb.push(dd + '" class="' + bclass + '"></div>');
          			}

          			//
          			// draw inner
          			//
          			var dd = div + ' z-index:2;' + (isTop ? 'background-position:0 -' + (r - yc - 1) + 'px;' : 'background-image:none;');
			        var doFinish = false;

          			if (xc < 0 && yc < r || yc < 0 && xc < r) {
            			doFinish = true;
          			}
          			else if (d < r && xc >= 0 && yc >= 0) {
            			if (d >= r - 1) {
              				dd += createOpacityString(r - d);
              				doShadow = true;
              				dsi.push(dd + '" class="' + iclass + '"></div>');
            			}
            			else {
              				doFinish = true;
            			}
          			}
          			else {
          				doShadow = true;
          			}

          			//
          			// Finish
          			//
          			if (doFinish) {
            			if (!isTop) {
            				dd = dd.replace(/top\:\d+px/, "top:0px");
            			}
            			dd = dd.replace(/height\:1px/, "height:" + (y + 1) + "px");
            			dsi.push(dd + '" class="' + iclass + '"></div>');
            			finished = true;
          			}

        		} // if r > 0
        		else {
        			doShadow = true;
        		}

        		//
        		// draw shadow
        		//
        		if (sr > 0 && doShadow) {
          			d = Math.sqrt(x * x + y * y);
          			if (d < sr) {
            			dss.push(div + ' z-index:0; ' + createOpacityString(1 - (d / sr)) + '" class="' + sclass + '"></div>');
          			}
        		}
        		yp += yd;

      		} // for var y loop

      	xp += xd;

    	} // for var x loop

    	var iHTML = dss.concat(dsb.concat(dsi)).join('');
    	dsb = null;
    	dsi = null;
    	dss = null;
    	return iHTML;
  	}

	// Creates the middle element innerHTML (?)
  	// @return String The innerHTML for an element.
  	//
  	function mid() {

		// Array
		//
		var ds = [];

	    ds.push('<div style="position:relative; top:' + (th + bh) + 'px; height:2048px; ' +
	    		' margin:0 ' + (rw - r - cx) + 'px 0 ' + (lw - r - cx) + 'px; ' +
	            ' padding:0; overflow:hidden;' +
	            ' background-position:0 ' + (th > 0 ? -(r + cy + cs) : '0') + 'px;"' +
	            ' class="' + iclass + '"></div>');

	    var dd = '<div style="position:absolute; width:1px;' +
	        	' top:' + (th + bh) + 'px; height:2048px; padding:0; margin:0;';

	    if (sr > 0) {

	    	for (var x = 0; x < lw - r - cx; ++x) {
	        	ds.push(dd + ' left:' + x + 'px;' + createOpacityString((x + 1.0) / lw) +
	            '" class="' + sclass + '"></div>');
	      	}

	      	for (var x = 0; x < rw - r - cx; ++x) {
	        	ds.push(dd + ' right:' + x + 'px;' + createOpacityString((x + 1.0) / rw) +
	            '" class="' + sclass + '"></div>');
	      	}
	    }

	    if (bow > 0) {
	      	var su = ' width:' + bow + 'px;' + createOpacityString(boo) + '" class="' + bclass + '"></div>';
	      	ds.push(dd + ' left:' + (lw - bor - cx) + 'px;' + su);
	      	ds.push(dd + ' right:' + (rw - bor - cx) + 'px;' + su);
	    }

	    var iHTML = ds.join('');
	    ds = null;
	    return iHTML;
	}

	// Creates the top bottom innerHTML
  	// @param isTop Whether top.
  	// @return String The innerHTML for an element.
  	//
  	function tb(isTop) {

	    // Array
	    //
	    var ds = [];

	    // int
	    //
	    var h = isTop ? th : bh;

	    var dd = '<div style="height:1px; overflow:hidden; position:absolute; margin:0; padding:0;' +
	    	    ' width:100%; left:0px; ';

	    // int
	    //
	    var s = isTop ? cs : -cs;

	    for (var y = 0; y < h - s - cy - r; ++y) {
	      	if (sr > 0) {
	      		ds.push(dd + (isTop ? 'top:' : 'bottom:') + y + 'px;' + createOpacityString((y + 1) * 1.0 / h) +
	          	'" class="' + sclass + '"></div>');
	        }
	    }

	    if (y >= bow) {
	      ds.push(dd + (isTop ? 'top:' : 'bottom:') + (y - bow) + 'px;' + createOpacityString(boo) +
	          ' height:' + bow + 'px;" class="' + bclass + '"></div>');
	    }

	    ds.push(dd + (isTop ? 'background-position-y:0; top:' :
	        'background-image:none; bottom:') + y + 'px;' +
	        ' height:' + (r + cy + s) + 'px;" class="' + iclass + '"></div>');

	    var iHTML = ds.join('');
	    ds = null;
	    return iHTML;
  	}

} // End ShaBoRenderer
//  Prototip 1.2.6.1 - 30-03-2008
//  Copyright (c) 2008 Nick Stakenburg (http://www.nickstakenburg.com)
//
//  Licensed under a Creative Commons Attribution-Noncommercial-No Derivative Works 3.0 Unported License
//  http://creativecommons.org/licenses/by-nc-nd/3.0/

//  More information on this project:
//  http://www.nickstakenburg.com/projects/prototip/

var Prototip = {
  Version: '1.2.6.1'
};

var Tips = {
  options: {
    className: 'default',      // default class for all tips
	closeButtons: false,       // true | false
	zIndex: 6000               // raise if required
  }
};

eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('1s.1X(1d,{3m:"1.6.0.2",3l:"1.8.1",2k:c(){5.1N("29");i.1K();l.S(21,"1Z",5.1Z)},1N:c(A){b((36 21[A]=="33")||(5.26(21[A].2U)<5.26(5["2b"+A]))){2P("2N 3G "+A+" >= "+5["2b"+A]);}},26:c(A){f B=A.3x(/2F.*|\\./g,"");B=3q(B+"0".3n(4-B.1F));z A.3i("2F")>-1?B-1:B},1o:c(A){b(!29.2q.2n){A=A.2m(c(E,D){f C=1s.35(5)?5:5.h,B=D.32;b(B!=C&&!$A(C.2d("*")).2X(B)){E(D)}})}z A},1Z:c(){i.2c()}});1s.1X(i,{s:[],O:[],1K:c(){5.1O=5.W},1e:(c(A){z{10:(A?"1m":"10"),Y:(A?"1l":"Y"),1m:(A?"1m":"10"),1l:(A?"1l":"Y")}})(29.2q.2n),X:(c(B){f A=o 3F("3B ([\\\\d.]+)").3v(B);z A?(3u(A[1])<7):v})(3r.3p),2B:c(A){5.s.25(A)},1b:c(A){f B=5.s.3k(c(C){z C.h==$(A)});b(B){B.2x();b(B.U){B.e.1b();b(i.X){B.P.1b()}}5.s=5.s.2v(B)}},2c:c(){5.s.2t(c(A){5.1b(A.h)}.1h(5))},20:c(B){b(B.1R){z}b(5.O.1F==0){5.1O=5.9.W;1D(f A=0;A<5.s.1F;A++){5.s[A].e.2p.W=5.9.W}}B.2p.W=5.1O++;1D(f A=0;A<5.s.1F;A++){5.s[A].e.1R=v}B.1R=1S},2l:c(A){5.1A(A);5.O.25(A)},1A:c(A){5.O=5.O.2v(A)}});i.1K();f 3c=3b.39({1K:c(A,B){5.h=$(A);i.1b(5.h);5.1Y=B;f D=(1p[2]&&1p[2].1v);f C=(1p[2]&&1p[2].n=="1G");5.9=1s.1X({q:i.9.q,m:i.9.31,1L:!C?0.2:v,1r:0.3,u:v,17:v,18:"1l",1v:v,27:D?{x:0,y:0}:{x:16,y:16},13:D?1S:v,n:"1x",j:5.h,1f:v,1w:D?v:1S},1p[2]||{});5.j=$(5.9.j);5.2a();b(5.9.u){1d.1N("2O");5.12={1u:"2M",2L:1,28:5.e.2K()}}i.2B(5);5.2J()},2a:c(){5.e=o l("11",{q:"1t"}).r({2I:"1M",W:i.9.W});5.e.2K();b(i.X){5.P=o l("3E",{q:"P",3D:"3A:v;",3z:0}).r({2I:"1M",W:i.9.W-1,3w:0})}5.R=o l("11",{q:"1Y"}).p(5.1Y);5.R.p(o l("11").r({2H:"2G"}));b(5.9.m||(5.9.18.h&&5.9.18.h=="m")){5.m=o l("a",{3t:"#",q:"3s"})}},2E:c(){b(i.X){$(1I.2D).p(5.P)}f D="e";b(5.9.u){D="1H";5.e.p(5[D]=o l("11",{q:D}))}5[D].p(5.U=o l("11",{q:"U "+5.9.q}));b(5.9.1f||5.9.m){5.U.p(5.1q=o l("11",{q:"1q"}).p(5.1f=o l("11",{q:"1f"}).3o(5.9.1f||" ")))}5.U.p(5.R);$(1I.2D).p(5.e);f A=(5.9.u)?[5.e,5.1H]:[5.e];b(i.X){A.25(5.P)}f C=5.e.2A();A.1j("r",{T:C+"1k"});b(5.1q){5.e.r({2z:"24"}).N();5.1q.r({T:5.1q.2A()+"1k"});5.e.k().r({2z:"O"})}b(5.m){5.1f.p({t:5.m}).p(o l("11").r({2H:"2G"}))}f B=5.e.3j();A.1j("r",{T:C+"1k",15:B+"1k"});5[5.9.u?D:"U"].k()},2J:c(){5.23=5.22.Z(5);5.2w=5.k.Z(5);b(5.9.13&&5.9.n=="1x"){5.9.n="10"}b(5.9.n==5.9.18){5.1a=5.2u.Z(5);5.h.S(5.9.n,5.1a)}f C={h:5.1a?[]:[5.h],j:5.1a?[]:[5.j],R:5.1a?[]:[5.e],m:[],1M:[]};f A=5.9.18.h;5.1P=A||(!5.9.18?"1M":"h");5.14=C[5.1P];b(!5.14&&A&&1s.3h(A)){5.14=5.R.2d(A)}f D={1m:"10",1l:"Y"};$w("N k").2t(c(H){f G=H.3g();f F=(5.9[H+"2s"].1Q||5.9[H+"2s"]);5[H+"2r"]=F;b(["1m","1l","10","Y"].3f(F)){5[H+"2r"]=(i.1e[F]||F);5["1Q"+G]=1d.1o(5["1Q"+G])}}.1h(5));b(!5.1a){5.h.S(5.9.n,5.23)}b(5.14){5.14.1j("S",5.3e,5.2w)}b(!5.9.13&&5.9.n=="1G"){5.1y=5.1u.Z(5);5.h.S("1x",5.1y)}5.2o=5.k.2m(c(F,E){E.3d();F(E)}).Z(5);b(5.m){5.m.S("1G",5.2o)}b(5.9.n!="1G"&&(5.1P!="h")){5.1B=1d.1o(c(){5.1n("N")}).Z(5);5.h.S(i.1e.Y,5.1B)}f B=[5.h,5.e];5.1U=1d.1o(c(){i.20(5.e);5.1W()}).Z(5);5.1V=1d.1o(5.17).Z(5);B.1j("S",i.1e.10,5.1U);B.1j("S",i.1e.Y,5.1V)},2x:c(){b(5.9.n==5.9.18){5.h.Q(5.9.n,5.1a)}1C{5.h.Q(5.9.n,5.23);b(5.14){5.14.1j("Q")}}b(5.1y){5.h.Q("1x",5.1y)}b(5.m){5.m.Q()}b(5.1B){5.h.Q("Y",5.1B)}5.e.Q();5.h.Q(i.1e.10,5.1U);5.h.Q(i.1e.Y,5.1V)},22:c(A){b(!5.U){5.2E()}5.1u(A);b(5.e.O()){z}5.1n("N");5.3a=5.N.1h(5).1L(5.9.1L)},1n:c(A){b(5[A+"2j"]){38(5[A+"2j"])}},N:c(){b(5.e.O()&&5.9.u!="37"){z}b(i.X){5.P.N()}i.2l(5.e);5.e.N();b(!5.9.u){5.U.N();5.h.1E("1t:2i")}1C{b(5.1g){1i.2h.2g(5.12.28).1b(5.1g)}5.1g=1i[1i.2f[5.9.u][0]](5.1H,{1r:5.9.1r,12:5.12,2y:l.1E.1h(5,5.h,"1t:2i")})}},17:c(A){b(!5.9.17){z}5.1W();5.34=5.k.1h(5).1L(5.9.17)},1W:c(){b(5.9.17){5.1n("17")}},k:c(){5.1n("N");b(!5.e.O()){z}b(!5.9.u){b(i.X){5.P.k()}5.U.k();5.e.k();i.1A(5.e);5.h.1E("1t:24")}1C{b(5.1g){1i.2h.2g(5.12.28).1b(5.1g)}5.1g=1i[1i.2f[5.9.u][1]](5.1H,{1r:5.9.1r,12:5.12,2y:c(){b(i.X){5.P.k()}5.e.k();i.1A(5.e);5.h.1E("1t:24")}.1h(5)})}},2u:c(A){b(5.e&&5.e.O()){5.k(A)}1C{5.22(A)}},1u:c(A){i.20(5.e);f E={V:5.9.27.x,t:5.9.27.y};f F=1z.1J(5.j);f B=5.e.1T();f I={V:(5.9.13)?F[0]:2C.30(A),t:(5.9.13)?F[1]:2C.2Z(A)};I.V+=E.V;I.t+=E.t;b(5.9.1v){f K={j:5.j.1T(),R:B};f L={j:1z.1J(5.j),R:1z.1J(5.j)};1D(f H 2e L){2Y(5.9.1v[H]){19"2W":L[H][0]+=K[H].T;1c;19"2V":L[H][0]+=(K[H].T/2);1c;19"3y":L[H][0]+=K[H].T;L[H][1]+=(K[H].15/2);1c;19"2T":L[H][1]+=K[H].15;1c;19"2S":L[H][0]+=K[H].T;L[H][1]+=K[H].15;1c;19"2R":L[H][0]+=(K[H].T/2);L[H][1]+=K[H].15;1c;19"3C":L[H][1]+=(K[H].15/2);1c}}I.V+=-1*(L.R[0]-L.j[0]);I.t+=-1*(L.R[1]-L.j[1])}b(!5.9.13&&5.h!==5.j){f C=1z.1J(5.h);I.V+=-1*(C[0]-F[0]);I.t+=-1*(C[1]-F[1])}b(!5.9.13&&5.9.1w){f J=1I.1w.2Q(),G=1I.1w.1T(),D={V:"T",t:"15"};1D(f H 2e D){b((I[H]+B[D[H]]-J[H])>G[D[H]]){I[H]=I[H]-B[D[H]]-2*E[H]}}}f M={V:I.V+"1k",t:I.t+"1k"};5.e.r(M);b(i.X){5.P.r(M)}}});1d.2k();',62,229,'|||||this||||options||if|function||wrapper|var||element|Tips|target|hide|Element|closeButton|showOn|new|insert|className|setStyle|tips|top|effect|false||||return||||||||||||||show|visible|iframeShim|stopObserving|tip|observe|width|tooltip|left|zIndex|fixIE|mouseout|bindAsEventListener|mouseover|div|queue|fixed|hideTargets|height||hideAfter|hideOn|case|eventToggle|remove|break|Prototip|useEvent|title|activeEffect|bind|Effect|invoke|px|mouseleave|mouseenter|clearTimer|capture|arguments|toolbar|duration|Object|prototip|position|hook|viewport|mousemove|eventPosition|Position|removeVisible|eventCheckDelay|else|for|fire|length|click|effectWrapper|document|cumulativeOffset|initialize|delay|none|require|zIndexTop|hideElement|event|highest|true|getDimensions|activityEnter|activityLeave|cancelHideAfter|extend|content|unload|raise|window|showDelayed|eventShow|hidden|push|convertVersionString|offset|scope|Prototype|setup|REQUIRED_|removeAll|select|in|PAIRS|get|Queues|shown|Timer|start|addVisibile|wrap|IE|buttonEvent|style|Browser|Action|On|each|toggle|without|eventHide|deactivate|afterFinish|visibility|getWidth|add|Event|body|build|_|both|clear|display|activate|identify|limit|end|Lightview|Scriptaculous|throw|getScrollOffsets|bottomMiddle|bottomRight|bottomLeft|Version|topMiddle|topRight|member|switch|pointerY|pointerX|closeButtons|relatedTarget|undefined|hideAfterTimer|isElement|typeof|appear|clearTimeout|create|showTimer|Class|Tip|stop|hideAction|include|capitalize|isString|indexOf|getHeight|find|REQUIRED_Scriptaculous|REQUIRED_Prototype|times|update|userAgent|parseInt|navigator|close|href|parseFloat|exec|opacity|replace|rightMiddle|frameBorder|javascript|MSIE|leftMiddle|src|iframe|RegExp|requires'.split('|'),0,{}));/*=:project
  scalable Inman Flash Replacement (sIFR) version 3, revision 419

  =:file
    Copyright: 2006 Mark Wubben.
    Author: Mark Wubben, <http://novemberborn.net/>

  =:history
    * IFR: Shaun Inman
    * sIFR 1: Mike Davidson, Shaun Inman and Tomas Jogin
    * sIFR 2: Mike Davidson, Shaun Inman, Tomas Jogin and Mark Wubben

  =:license
    This software is licensed and provided under the CC-GNU LGPL.
    See <http://creativecommons.org/licenses/LGPL/2.1/>    
*/

var sIFR=new function(){var O=this;var E={ACTIVE:"sIFR-active",REPLACED:"sIFR-replaced",IGNORE:"sIFR-ignore",ALTERNATE:"sIFR-alternate",CLASS:"sIFR-class",LAYOUT:"sIFR-layout",FLASH:"sIFR-flash",FIX_FOCUS:"sIFR-fixfocus",DUMMY:"sIFR-dummy"};E.IGNORE_CLASSES=[E.REPLACED,E.IGNORE,E.ALTERNATE];this.MIN_FONT_SIZE=6;this.MAX_FONT_SIZE=126;this.FLASH_PADDING_BOTTOM=5;this.VERSION="419";this.isActive=false;this.isEnabled=true;this.fixHover=true;this.autoInitialize=true;this.setPrefetchCookie=true;this.cookiePath="/";this.domains=[];this.forceWidth=true;this.fitExactly=false;this.forceTextTransform=true;this.useDomLoaded=true;this.useStyleCheck=false;this.hasFlashClassSet=false;this.repaintOnResize=true;this.replacements=[];var L=0;var R=false;function Y(){}function D(c){function d(e){return e.toLocaleUpperCase()}this.normalize=function(e){return e.replace(/\n|\r|\xA0/g,D.SINGLE_WHITESPACE).replace(/\s+/g,D.SINGLE_WHITESPACE)};this.textTransform=function(e,f){switch(e){case"uppercase":return f.toLocaleUpperCase();case"lowercase":return f.toLocaleLowerCase();case"capitalize":return f.replace(/^\w|\s\w/g,d)}return f};this.toHexString=function(e){if(e.charAt(0)!="#"||e.length!=4&&e.length!=7){return e}e=e.substring(1);return"0x"+(e.length==3?e.replace(/(.)(.)(.)/,"$1$1$2$2$3$3"):e)};this.toJson=function(g,f){var e="";switch(typeof (g)){case"string":e='"'+f(g)+'"';break;case"number":case"boolean":e=g.toString();break;case"object":e=[];for(var h in g){if(g[h]==Object.prototype[h]){continue}e.push('"'+h+'":'+this.toJson(g[h]))}e="{"+e.join(",")+"}";break}return e};this.convertCssArg=function(e){if(!e){return{}}if(typeof (e)=="object"){if(e.constructor==Array){e=e.join("")}else{return e}}var l={};var m=e.split("}");for(var h=0;h<m.length;h++){var k=m[h].match(/([^\s{]+)\s*\{(.+)\s*;?\s*/);if(!k||k.length!=3){continue}if(!l[k[1]]){l[k[1]]={}}var g=k[2].split(";");for(var f=0;f<g.length;f++){var n=g[f].match(/\s*([^:\s]+)\s*\:\s*([^;]+)/);if(!n||n.length!=3){continue}l[k[1]][n[1]]=n[2].replace(/\s+$/,"")}}return l};this.extractFromCss=function(g,f,i,e){var h=null;if(g&&g[f]&&g[f][i]){h=g[f][i];if(e){delete g[f][i]}}return h};this.cssToString=function(f){var g=[];for(var e in f){var j=f[e];if(j==Object.prototype[e]){continue}g.push(e,"{");for(var i in j){if(j[i]==Object.prototype[i]){continue}var h=j[i];if(D.UNIT_REMOVAL_PROPERTIES[i]){h=parseInt(h,10)}g.push(i,":",h,";")}g.push("}")}return g.join("")};this.escape=function(e){return escape(e).replace(/\+/g,"%2B")};this.encodeVars=function(e){return e.join("&").replace(/%/g,"%25")};this.copyProperties=function(g,f){for(var e in g){if(f[e]===undefined){f[e]=g[e]}}return f};this.domain=function(){var f="";try{f=document.domain}catch(g){}return f};this.domainMatches=function(h,g){if(g=="*"||g==h){return true}var f=g.lastIndexOf("*");if(f>-1){g=g.substr(f+1);var e=h.lastIndexOf(g);if(e>-1&&(e+g.length)==h.length){return true}}return false};this.uriEncode=function(e){return encodeURI(decodeURIComponent(e))};this.delay=function(f,h,g){var e=Array.prototype.slice.call(arguments,3);setTimeout(function(){h.apply(g,e)},f)}}D.UNIT_REMOVAL_PROPERTIES={leading:true,"margin-left":true,"margin-right":true,"text-indent":true};D.SINGLE_WHITESPACE=" ";function U(e){var d=this;function c(g,j,h){var k=d.getStyleAsInt(g,j,e.ua.ie);if(k==0){k=g[h];for(var f=3;f<arguments.length;f++){k-=d.getStyleAsInt(g,arguments[f],true)}}return k}this.getBody=function(){return document.getElementsByTagName("body")[0]||null};this.querySelectorAll=function(f){return window.parseSelector(f)};this.addClass=function(f,g){if(g){g.className=((g.className||"")==""?"":g.className+" ")+f}};this.removeClass=function(f,g){if(g){g.className=g.className.replace(new RegExp("(^|\\s)"+f+"(\\s|$)"),"").replace(/^\s+|(\s)\s+/g,"$1")}};this.hasClass=function(f,g){return new RegExp("(^|\\s)"+f+"(\\s|$)").test(g.className)};this.hasOneOfClassses=function(h,g){for(var f=0;f<h.length;f++){if(this.hasClass(h[f],g)){return true}}return false};this.ancestorHasClass=function(g,f){g=g.parentNode;while(g&&g.nodeType==1){if(this.hasClass(f,g)){return true}g=g.parentNode}return false};this.create=function(f,g){var h=document.createElementNS?document.createElementNS(U.XHTML_NS,f):document.createElement(f);if(g){h.className=g}return h};this.getComputedStyle=function(h,i){var f;if(document.defaultView&&document.defaultView.getComputedStyle){var g=document.defaultView.getComputedStyle(h,null);f=g?g[i]:null}else{if(h.currentStyle){f=h.currentStyle[i]}}return f||""};this.getStyleAsInt=function(g,i,f){var h=this.getComputedStyle(g,i);if(f&&!/px$/.test(h)){return 0}return parseInt(h)||0};this.getWidthFromStyle=function(f){return c(f,"width","offsetWidth","paddingRight","paddingLeft","borderRightWidth","borderLeftWidth")};this.getHeightFromStyle=function(f){return c(f,"height","offsetHeight","paddingTop","paddingBottom","borderTopWidth","borderBottomWidth")};this.getDimensions=function(j){var h=j.offsetWidth;var f=j.offsetHeight;if(h==0||f==0){for(var g=0;g<j.childNodes.length;g++){var k=j.childNodes[g];if(k.nodeType!=1){continue}h=Math.max(h,k.offsetWidth);f=Math.max(f,k.offsetHeight)}}return{width:h,height:f}};this.getViewport=function(){return{width:window.innerWidth||document.documentElement.clientWidth||this.getBody().clientWidth,height:window.innerHeight||document.documentElement.clientHeight||this.getBody().clientHeight}};this.blurElement=function(g){try{g.blur();return }catch(h){}var f=this.create("input");f.style.width="0px";f.style.height="0px";g.parentNode.appendChild(f);f.focus();f.blur();f.parentNode.removeChild(f)}}U.XHTML_NS="http://www.w3.org/1999/xhtml";function H(r){var g=navigator.userAgent.toLowerCase();var q=(navigator.product||"").toLowerCase();var h=navigator.platform.toLowerCase();this.parseVersion=H.parseVersion;this.macintosh=/^mac/.test(h);this.windows=/^win/.test(h);this.quicktime=false;this.opera=/opera/.test(g);this.konqueror=/konqueror/.test(q);this.ie=false/*@cc_on||true@*/;this.ieSupported=this.ie&&!/ppc|smartphone|iemobile|msie\s5\.5/.test(g)/*@cc_on&&@_jscript_version>=5.5@*/;this.ieWin=this.ie&&this.windows/*@cc_on&&@_jscript_version>=5.1@*/;this.windows=this.windows&&(!this.ie||this.ieWin);this.ieMac=this.ie&&this.macintosh/*@cc_on&&@_jscript_version<5.1@*/;this.macintosh=this.macintosh&&(!this.ie||this.ieMac);this.safari=/safari/.test(g);this.webkit=!this.konqueror&&/applewebkit/.test(g);this.khtml=this.webkit||this.konqueror;this.gecko=!this.webkit&&q=="gecko";this.ieVersion=this.ie&&/.*msie\s(\d\.\d)/.exec(g)?this.parseVersion(RegExp.$1):"0";this.operaVersion=this.opera&&/.*opera(\s|\/)(\d+\.\d+)/.exec(g)?this.parseVersion(RegExp.$2):"0";this.webkitVersion=this.webkit&&/.*applewebkit\/(\d+).*/.exec(g)?this.parseVersion(RegExp.$1):"0";this.geckoVersion=this.gecko&&/.*rv:\s*([^\)]+)\)\s+gecko/.exec(g)?this.parseVersion(RegExp.$1):"0";this.konquerorVersion=this.konqueror&&/.*konqueror\/([\d\.]+).*/.exec(g)?this.parseVersion(RegExp.$1):"0";this.flashVersion=0;if(this.ieWin){var l;var o=false;try{l=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7")}catch(m){try{l=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");this.flashVersion=this.parseVersion("6");l.AllowScriptAccess="always"}catch(m){o=this.flashVersion==this.parseVersion("6")}if(!o){try{l=new ActiveXObject("ShockwaveFlash.ShockwaveFlash")}catch(m){}}}if(!o&&l){this.flashVersion=this.parseVersion((l.GetVariable("$version")||"").replace(/^\D+(\d+)\D+(\d+)\D+(\d+).*/g,"$1.$2.$3"))}}else{if(navigator.plugins&&navigator.plugins["Shockwave Flash"]){var n=navigator.plugins["Shockwave Flash"].description.replace(/^.*\s+(\S+\s+\S+$)/,"$1");var p=n.replace(/^\D*(\d+\.\d+).*$/,"$1");if(/r/.test(n)){p+=n.replace(/^.*r(\d*).*$/,".$1")}else{if(/d/.test(n)){p+=".0"}}this.flashVersion=this.parseVersion(p);var j=false;for(var k=0,c=this.flashVersion>=H.MIN_FLASH_VERSION;c&&k<navigator.mimeTypes.length;k++){var f=navigator.mimeTypes[k];if(f.type!="application/x-shockwave-flash"){continue}if(f.enabledPlugin){j=true;if(f.enabledPlugin.description.toLowerCase().indexOf("quicktime")>-1){c=false;this.quicktime=true}}}if(this.quicktime||!j){this.flashVersion=this.parseVersion("0")}}}this.flash=this.flashVersion>=H.MIN_FLASH_VERSION;this.transparencySupport=this.macintosh||this.windows;this.computedStyleSupport=this.ie||!!document.defaultView.getComputedStyle;this.fixFocus=this.gecko&&this.windows;this.nativeDomLoaded=this.gecko||this.webkit&&this.webkitVersion>=this.parseVersion("525")||this.konqueror&&this.konquerorMajor>this.parseVersion("03")||this.opera;this.mustCheckStyle=this.khtml||this.opera;this.forcePageLoad=this.webkit&&this.webkitVersion<this.parseVersion("523");this.properDocument=typeof (document.location)=="object";this.supported=this.flash&&this.properDocument&&(!this.ie||this.ieSupported)&&this.computedStyleSupport&&(!this.opera||this.operaVersion>=this.parseVersion("9.50"))&&(!this.webkit||this.webkitVersion>=this.parseVersion("412"))&&(!this.gecko||this.geckoVersion>=this.parseVersion("1.8.0.12"))&&(!this.konqueror)}H.parseVersion=function(c){return c.replace(/(^|\D)(\d+)(?=\D|$)/g,function(f,e,g){f=e;for(var d=4-g.length;d>=0;d--){f+="0"}return f+g})};H.MIN_FLASH_VERSION=H.parseVersion("8");function F(c){this.fix=c.ua.ieWin&&window.location.hash!="";var d;this.cache=function(){d=document.title};function e(){document.title=d}this.restore=function(){if(this.fix){setTimeout(e,0)}}}function S(l){var e=null;function c(){try{if(l.ua.ie||document.readyState!="loaded"&&document.readyState!="complete"){document.documentElement.doScroll("left")}}catch(n){return setTimeout(c,10)}i()}function i(){if(l.useStyleCheck){h()}else{if(!l.ua.mustCheckStyle){d(null,true)}}}function h(){e=l.dom.create("div",E.DUMMY);l.dom.getBody().appendChild(e);m()}function m(){if(l.dom.getComputedStyle(e,"marginLeft")=="42px"){g()}else{setTimeout(m,10)}}function g(){if(e&&e.parentNode){e.parentNode.removeChild(e)}e=null;d(null,true)}function d(n,o){l.initialize(o);if(n&&n.type=="load"){if(document.removeEventListener){document.removeEventListener("DOMContentLoaded",d,false)}if(window.removeEventListener){window.removeEventListener("load",d,false)}}}function j(){l.prepareClearReferences();if(document.readyState=="interactive"){document.attachEvent("onstop",f);setTimeout(function(){document.detachEvent("onstop",f)},0)}}function f(){document.detachEvent("onstop",f);k()}function k(){l.clearReferences()}this.attach=function(){if(window.addEventListener){window.addEventListener("load",d,false)}else{window.attachEvent("onload",d)}if(!l.useDomLoaded||l.ua.forcePageLoad||l.ua.ie&&window.top!=window){return }if(l.ua.nativeDomLoaded){document.addEventListener("DOMContentLoaded",i,false)}else{if(l.ua.ie||l.ua.khtml){c()}}};this.attachUnload=function(){if(!l.ua.ie){return }window.attachEvent("onbeforeunload",j);window.attachEvent("onunload",k)}}var Q="sifrFetch";function N(c){var e=false;this.fetchMovies=function(f){if(c.setPrefetchCookie&&new RegExp(";?"+Q+"=true;?").test(document.cookie)){return }try{e=true;d(f)}catch(g){if(c.debug){throw g}}if(c.setPrefetchCookie){document.cookie=Q+"=true;path="+c.cookiePath}};this.clear=function(){if(!e){return }try{var f=document.getElementsByTagName("script");for(var g=f.length-1;g>=0;g--){var h=f[g];if(h.type=="sifr/prefetch"){h.parentNode.removeChild(h)}}}catch(j){}};function d(f){for(var g=0;g<f.length;g++){document.write('<script defer type="sifr/prefetch" src="'+f[g].src+'"><\/script>')}}}function b(e){var g=e.ua.ie;var f=g&&e.ua.flashVersion<e.ua.parseVersion("9.0.115");var d={};var c={};this.fixFlash=f;this.register=function(h){if(!g){return }var i=h.getAttribute("id");this.cleanup(i,false);c[i]=h;delete d[i];if(f){window[i]=h}};this.reset=function(){if(!g){return false}for(var j=0;j<e.replacements.length;j++){var h=e.replacements[j];var k=c[h.id];if(!d[h.id]&&(!k.parentNode||k.parentNode.nodeType==11)){h.resetMovie();d[h.id]=true}}return true};this.cleanup=function(l,h){var i=c[l];if(!i){return }for(var k in i){if(typeof (i[k])=="function"){i[k]=null}}c[l]=null;if(f){window[l]=null}if(i.parentNode){if(h&&i.parentNode.nodeType==1){var j=document.createElement("div");j.style.width=i.offsetWidth+"px";j.style.height=i.offsetHeight+"px";i.parentNode.replaceChild(j,i)}else{i.parentNode.removeChild(i)}}};this.prepareClearReferences=function(){if(!f){return }__flash_unloadHandler=function(){};__flash_savedUnloadHandler=function(){}};this.clearReferences=function(){if(f){var j=document.getElementsByTagName("object");for(var h=j.length-1;h>=0;h--){c[j[h].getAttribute("id")]=j[h]}}for(var k in c){if(Object.prototype[k]!=c[k]){this.cleanup(k,true)}}}}function K(d,g,f,c,e){this.sIFR=d;this.id=g;this.vars=f;this.movie=null;this.__forceWidth=c;this.__events=e;this.__resizing=0}K.prototype={getFlashElement:function(){return document.getElementById(this.id)},getAlternate:function(){return document.getElementById(this.id+"_alternate")},getAncestor:function(){var c=this.getFlashElement().parentNode;return !this.sIFR.dom.hasClass(E.FIX_FOCUS,c)?c:c.parentNode},available:function(){var c=this.getFlashElement();return c&&c.parentNode},call:function(c){var d=this.getFlashElement();return Function.prototype.apply.call(d[c],d,Array.prototype.slice.call(arguments,1))},attempt:function(){if(!this.available()){return false}try{this.call.apply(this,arguments)}catch(c){if(this.sIFR.debug){throw c}return false}return true},updateVars:function(c,e){for(var d=0;d<this.vars.length;d++){if(this.vars[d].split("=")[0]==c){this.vars[d]=c+"="+e;break}}var f=this.sIFR.util.encodeVars(this.vars);this.movie.injectVars(this.getFlashElement(),f);this.movie.injectVars(this.movie.html,f)},storeSize:function(c,d){this.movie.setSize(c,d);this.updateVars(c,d)},fireEvent:function(c){if(this.available()&&this.__events[c]){this.sIFR.util.delay(0,this.__events[c],this,this)}},resizeFlashElement:function(c,d,e){if(!this.available()){return }this.__resizing++;var f=this.getFlashElement();f.setAttribute("height",c);this.updateVars("renderheight",c);this.storeSize("height",c);if(d!==null){f.setAttribute("width",d);this.movie.setSize("width",d)}if(this.__events.onReplacement){this.sIFR.util.delay(0,this.__events.onReplacement,this,this);delete this.__events.onReplacement}if(e){this.sIFR.util.delay(0,function(){this.attempt("scaleMovie");this.__resizing--},this)}else{this.__resizing--}},blurFlashElement:function(){if(this.available()){this.sIFR.dom.blurElement(this.getFlashElement())}},resetMovie:function(){this.sIFR.util.delay(0,this.movie.reset,this.movie,this.getFlashElement(),this.getAlternate())},resizeAfterScale:function(){if(this.available()&&this.__resizing==0){this.sIFR.util.delay(0,this.resize,this)}},resize:function(){if(!this.available()){return }this.__resizing++;var g=this.getFlashElement();var f=g.offsetWidth;if(f==0){return }var e=g.getAttribute("width");var l=g.getAttribute("height");var m=this.getAncestor();var o=this.sIFR.dom.getHeightFromStyle(m);g.style.width="1px";g.style.height="1px";m.style.minHeight=o+"px";var c=this.getAlternate().childNodes;var n=[];for(var k=0;k<c.length;k++){var h=c[k].cloneNode(true);n.push(h);m.appendChild(h)}var d=this.sIFR.dom.getWidthFromStyle(m);for(var k=0;k<n.length;k++){m.removeChild(n[k])}g.style.width=g.style.height=m.style.minHeight="";g.setAttribute("width",this.__forceWidth?d:e);g.setAttribute("height",l);if(sIFR.ua.ie){g.style.display="none";var j=g.offsetHeight;g.style.display=""}if(d!=f){if(this.__forceWidth){this.storeSize("width",d)}this.attempt("resize",d)}this.__resizing--},replaceText:function(g,j){var d=this.sIFR.util.escape(g);if(!this.attempt("replaceText",d)){return false}this.updateVars("content",d);var f=this.getAlternate();if(j){while(f.firstChild){f.removeChild(f.firstChild)}for(var c=0;c<j.length;c++){f.appendChild(j[c])}}else{try{f.innerHTML=g}catch(h){}}return true},changeCSS:function(c){c=this.sIFR.util.escape(this.sIFR.util.cssToString(this.sIFR.util.convertCssArg(c)));this.updateVars("css",c);return this.attempt("changeCSS",c)},remove:function(){if(this.movie&&this.available()){this.movie.remove(this.getFlashElement(),this.id)}}};var X=new function(){this.create=function(p,n,j,i,f,e,g,o,l,h,m){var k=p.ua.ie?d:c;return new k(p,n,j,i,f,e,g,o,["flashvars",l,"wmode",h,"bgcolor",m,"allowScriptAccess","always","quality","best"])};function c(s,q,l,h,f,e,g,r,n){var m=s.dom.create("object",E.FLASH);var p=["type","application/x-shockwave-flash","id",f,"name",f,"data",e,"width",g,"height",r];for(var o=0;o<p.length;o+=2){m.setAttribute(p[o],p[o+1])}var j=m;if(h){j=W.create("div",E.FIX_FOCUS);j.appendChild(m)}for(var o=0;o<n.length;o+=2){if(n[o]=="name"){continue}var k=W.create("param");k.setAttribute("name",n[o]);k.setAttribute("value",n[o+1]);m.appendChild(k)}while(l.firstChild){l.removeChild(l.firstChild)}l.appendChild(j);this.html=j.cloneNode(true)}c.prototype={reset:function(e,f){e.parentNode.replaceChild(this.html.cloneNode(true),e)},remove:function(e,f){e.parentNode.removeChild(e)},setSize:function(e,f){this.html.setAttribute(e,f)},injectVars:function(e,g){var h=e.getElementsByTagName("param");for(var f=0;f<h.length;f++){if(h[f].getAttribute("name")=="flashvars"){h[f].setAttribute("value",g);break}}}};function d(p,n,j,h,f,e,g,o,k){this.dom=p.dom;this.broken=n;this.html='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" id="'+f+'" width="'+g+'" height="'+o+'" class="'+E.FLASH+'"><param name="movie" value="'+e+'"></param></object>';var m="";for(var l=0;l<k.length;l+=2){m+='<param name="'+k[l]+'" value="'+k[l+1]+'"></param>'}this.html=this.html.replace(/(<\/object>)/,m+"$1");j.innerHTML=this.html;this.broken.register(j.firstChild)}d.prototype={reset:function(f,g){g=g.cloneNode(true);var e=f.parentNode;e.innerHTML=this.html;this.broken.register(e.firstChild);e.appendChild(g)},remove:function(e,f){this.broken.cleanup(f)},setSize:function(e,f){this.html=this.html.replace(e=="height"?/(height)="\d+"/:/(width)="\d+"/,'$1="'+f+'"')},injectVars:function(e,f){if(e!=this.html){return }this.html=this.html.replace(/(flashvars(=|\"\svalue=)\")[^\"]+/,"$1"+f)}}};this.errors=new Y(O);var A=this.util=new D(O);var W=this.dom=new U(O);var T=this.ua=new H(O);var G={fragmentIdentifier:new F(O),pageLoad:new S(O),prefetch:new N(O),brokenFlashIE:new b(O)};this.__resetBrokenMovies=G.brokenFlashIE.reset;var J={kwargs:[],replaceAll:function(d){for(var c=0;c<this.kwargs.length;c++){O.replace(this.kwargs[c])}if(!d){this.kwargs=[]}}};this.activate=function(){if(!T.supported||!this.isEnabled||this.isActive||!C()||a()){return }G.prefetch.fetchMovies(arguments);this.isActive=true;this.setFlashClass();G.fragmentIdentifier.cache();G.pageLoad.attachUnload();if(!this.autoInitialize){return }G.pageLoad.attach()};this.setFlashClass=function(){if(this.hasFlashClassSet){return }W.addClass(E.ACTIVE,W.getBody()||document.documentElement);this.hasFlashClassSet=true};this.removeFlashClass=function(){if(!this.hasFlashClassSet){return }W.removeClass(E.ACTIVE,W.getBody());W.removeClass(E.ACTIVE,document.documentElement);this.hasFlashClassSet=false};this.initialize=function(c){if(!this.isActive||!this.isEnabled){return }if(R){if(!c){J.replaceAll(false)}return }R=true;J.replaceAll(c);if(O.repaintOnResize){if(window.addEventListener){window.addEventListener("resize",Z,false)}else{window.attachEvent("onresize",Z)}}G.prefetch.clear()};this.replace=function(w,t){if(!T.supported){return }if(t){w=A.copyProperties(w,t)}if(!R){return J.kwargs.push(w)}if(this.onReplacementStart){this.onReplacementStart(w)}var AL=w.elements||W.querySelectorAll(w.selector);if(AL.length==0){return }var v=M(w.src);var AQ=A.convertCssArg(w.css);var u=B(w.filters);var AM=w.forceSingleLine===true;var AR=w.preventWrap===true&&!AM;var p=AM||(w.fitExactly==null?this.fitExactly:w.fitExactly)===true;var AC=p||(w.forceWidth==null?this.forceWidth:w.forceWidth)===true;var r=w.ratios||[];var AD=w.pixelFont===true;var q=parseInt(w.tuneHeight)||0;var y=!!w.onRelease||!!w.onRollOver||!!w.onRollOut;if(p){A.extractFromCss(AQ,".sIFR-root","text-align",true)}var s=A.extractFromCss(AQ,".sIFR-root","font-size",true)||"0";var e=A.extractFromCss(AQ,".sIFR-root","background-color",true)||"#FFFFFF";var n=A.extractFromCss(AQ,".sIFR-root","kerning",true)||"";var AV=A.extractFromCss(AQ,".sIFR-root","opacity",true)||"100";var k=A.extractFromCss(AQ,".sIFR-root","cursor",true)||"default";var AO=parseInt(A.extractFromCss(AQ,".sIFR-root","leading"))||0;var AI=w.gridFitType||(A.extractFromCss(AQ,".sIFR-root","text-align")=="right")?"subpixel":"pixel";var h=this.forceTextTransform===false?"none":A.extractFromCss(AQ,".sIFR-root","text-transform",true)||"none";s=/^\d+(px)?$/.test(s)?parseInt(s):0;AV=parseFloat(AV)<1?100*parseFloat(AV):AV;var AB=w.modifyCss?"":A.cssToString(AQ);var AF=w.wmode||"";if(!AF){if(w.transparent){AF="transparent"}else{if(w.opaque){AF="opaque"}}}if(AF=="transparent"){if(!T.transparencySupport){AF="opaque"}else{e="transparent"}}for(var AU=0;AU<AL.length;AU++){var AE=AL[AU];if(W.hasOneOfClassses(E.IGNORE_CLASSES,AE)||W.ancestorHasClass(AE,E.ALTERNATE)){continue}var AN=W.getDimensions(AE);var f=AN.height;var c=AN.width;var z=W.getComputedStyle(AE,"display");if(!f||!c||!z||z=="none"){continue}c=W.getWidthFromStyle(AE);var m,AG;if(!s){var AK=I(AE);m=Math.min(this.MAX_FONT_SIZE,Math.max(this.MIN_FONT_SIZE,AK.fontSize));if(AD){m=Math.max(8,8*Math.round(m/8))}AG=AK.lines;if(isNaN(AG)||!isFinite(AG)||AG==0){AG=1}if(AG>1&&AO){f+=Math.round((AG-1)*AO)}}else{m=s;AG=1}var d=W.create("span",E.ALTERNATE);var AW=AE.cloneNode(true);AE.parentNode.appendChild(AW);for(var AT=0,AS=AW.childNodes.length;AT<AS;AT++){d.appendChild(AW.childNodes[AT].cloneNode(true))}if(w.modifyContent){w.modifyContent(AW,w.selector)}if(w.modifyCss){AB=w.modifyCss(AQ,AW,w.selector)}var o=P(AW,h,w.uriEncode);AW.parentNode.removeChild(AW);if(w.modifyContentString){o.text=w.modifyContentString(o.text,w.selector)}if(o.text==""){continue}f=Math.round(AG*m);var AJ=Math.round(AG*V(m,r)*m)+this.FLASH_PADDING_BOTTOM+q;var AA=AC?c:"100%";var AH="sIFR_replacement_"+L++;var AP=["id="+AH,"content="+A.escape(o.text),"width="+c,"height="+f,"renderheight="+AJ,"link="+A.escape(o.primaryLink.href||""),"target="+A.escape(o.primaryLink.target||""),"size="+m,"css="+A.escape(AB),"cursor="+k,"tunewidth="+(w.tuneWidth||0),"tuneheight="+q,"offsetleft="+(w.offsetLeft||""),"offsettop="+(w.offsetTop||""),"fitexactly="+p,"preventwrap="+AR,"forcesingleline="+AM,"antialiastype="+(w.antiAliasType||""),"thickness="+(w.thickness||""),"sharpness="+(w.sharpness||""),"kerning="+n,"gridfittype="+AI,"flashfilters="+u,"opacity="+AV,"blendmode="+(w.blendMode||""),"selectable="+(w.selectable==null||AF!=""&&!sIFR.ua.macintosh&&sIFR.ua.gecko&&sIFR.ua.geckoVersion>=sIFR.ua.parseVersion("1.9")?"true":w.selectable===true),"fixhover="+(this.fixHover===true),"events="+y,"delayrun="+G.brokenFlashIE.fixFlash,"version="+this.VERSION];var x=A.encodeVars(AP);var g=new K(O,AH,AP,AC,{onReplacement:w.onReplacement,onRollOver:w.onRollOver,onRollOut:w.onRollOut,onRelease:w.onRelease});g.movie=X.create(sIFR,G.brokenFlashIE,AE,T.fixFocus&&w.fixFocus,AH,v,AA,AJ,x,AF,e);this.replacements.push(g);this.replacements[AH]=g;if(w.selector){if(!this.replacements[w.selector]){this.replacements[w.selector]=[g]}else{this.replacements[w.selector].push(g)}}d.setAttribute("id",AH+"_alternate");AE.appendChild(d);W.addClass(E.REPLACED,AE)}G.fragmentIdentifier.restore()};this.getReplacementByFlashElement=function(d){for(var c=0;c<O.replacements.length;c++){if(O.replacements[c].id==d.getAttribute("id")){return O.replacements[c]}}};this.redraw=function(){for(var c=0;c<O.replacements.length;c++){O.replacements[c].resetMovie()}};this.prepareClearReferences=function(){G.brokenFlashIE.prepareClearReferences()};this.clearReferences=function(){G.brokenFlashIE.clearReferences();G=null;J=null;delete O.replacements};function C(){if(O.domains.length==0){return true}var d=A.domain();for(var c=0;c<O.domains.length;c++){if(A.domainMatches(d,O.domains[c])){return true}}return false}function a(){if(document.location.protocol=="file:"){if(O.debug){O.errors.fire("isFile")}return true}return false}function M(c){if(T.ie&&c.charAt(0)=="/"){c=window.location.toString().replace(/([^:]+)(:\/?\/?)([^\/]+).*/,"$1$2$3")+c}return c}function V(d,e){for(var c=0;c<e.length;c+=2){if(d<=e[c]){return e[c+1]}}return e[e.length-1]||1}function B(g){var e=[];for(var d in g){if(g[d]==Object.prototype[d]){continue}var c=g[d];d=[d.replace(/filter/i,"")+"Filter"];for(var f in c){if(c[f]==Object.prototype[f]){continue}d.push(f+":"+A.escape(A.toJson(c[f],A.toHexString)))}e.push(d.join(","))}return A.escape(e.join(";"))}function Z(d){var e=Z.viewport;var c=W.getViewport();if(e&&c.width==e.width&&c.height==e.height){return }Z.viewport=c;if(O.replacements.length==0){return }if(Z.timer){clearTimeout(Z.timer)}Z.timer=setTimeout(function(){delete Z.timer;for(var f=0;f<O.replacements.length;f++){O.replacements[f].resize()}},200)}function I(g){var h,d;if(!T.ie){h=W.getStyleAsInt(g,"lineHeight");d=Math.floor(W.getStyleAsInt(g,"height")/h)}else{if(T.ie){var h=W.getComputedStyle(g,"fontSize");if(h.indexOf("px")>0){h=parseInt(h)}else{var f=g.innerHTML;g.style.visibility="visible";g.style.overflow="visible";g.style.position="static";g.style.zoom="normal";g.style.writingMode="lr-tb";g.style.width=g.style.height="auto";g.style.maxWidth=g.style.maxHeight=g.style.styleFloat="none";var i=g;var c=g.currentStyle.hasLayout;if(c){g.innerHTML='<div class="'+E.LAYOUT+'">X<br>X<br>X</div>';i=g.firstChild}else{g.innerHTML="X<br>X<br>X"}var e=i.getClientRects();h=e[1].bottom-e[1].top;h=Math.ceil(h*0.8);if(c){g.innerHTML='<div class="'+E.LAYOUT+'">'+f+"</div>";i=g.firstChild}else{g.innerHTML=f}e=i.getClientRects();d=e.length;if(c){g.innerHTML=f}g.style.visibility=g.style.width=g.style.height=g.style.maxWidth=g.style.maxHeight=g.style.overflow=g.style.styleFloat=g.style.position=g.style.zoom=g.style.writingMode=""}}}return{fontSize:h,lines:d}}function P(c,g,s){s=s||A.uriEncode;var q=[],m=[];var k=null;var e=c.childNodes;var o=false,p=false;var j=0;while(j<e.length){var f=e[j];if(f.nodeType==3){var t=A.textTransform(g,A.normalize(f.nodeValue)).replace(/</g,"&lt;");if(o&&p){t=t.replace(/^\s+/,"")}m.push(t);o=/\s$/.test(t);p=false}if(f.nodeType==1&&!/^(style|script)$/i.test(f.nodeName)){var h=[];var r=f.nodeName.toLowerCase();var n=f.className||"";if(/\s+/.test(n)){if(n.indexOf(E.CLASS)>-1){n=n.match("(\\s|^)"+E.CLASS+"-([^\\s$]*)(\\s|$)")[2]}else{n=n.match(/^([^\s]+)/)[1]}}if(n!=""){h.push('class="'+n+'"')}if(r=="a"){var d=s(f.getAttribute("href")||"");var l=f.getAttribute("target")||"";h.push('href="'+d+'"','target="'+l+'"');if(!k){k={href:d,target:l}}}m.push("<"+r+(h.length>0?" ":"")+h.join(" ")+">");p=true;if(f.hasChildNodes()){q.push(j);j=0;e=f.childNodes;continue}else{if(!/^(br|img)$/i.test(f.nodeName)){m.push("</",f.nodeName.toLowerCase(),">")}}}if(q.length>0&&!f.nextSibling){do{j=q.pop();e=f.parentNode.parentNode.childNodes;f=e[j];if(f){m.push("</",f.nodeName.toLowerCase(),">")}}while(j==e.length-1&&q.length>0)}j++}return{text:m.join("").replace(/^\s+|\s+$|\s*(<br>)\s*/g,"$1"),primaryLink:k||{}}}};
var parseSelector=(function(){var B=/\s*,\s*/;var A=/\s*([\s>+~(),]|^|$)\s*/g;var L=/([\s>+~,]|[^(]\+|^)([#.:@])/g;var F=/(^|\))[^\s>+~]/g;var M=/(\)|^)/;var K=/[\s#.:>+~()@]|[^\s#.:>+~()@]+/g;function H(R,P){P=P||document.documentElement;var S=R.split(B),X=[];for(var U=0;U<S.length;U++){var N=[P],W=G(S[U]);for(var T=0;T<W.length;){var Q=W[T++],O=W[T++],V="";if(W[T]=="("){while(W[T++]!=")"&&T<W.length){V+=W[T]}V=V.slice(0,-1)}N=I(N,Q,O,V)}X=X.concat(N)}return X}function G(N){var O=N.replace(A,"$1").replace(L,"$1*$2").replace(F,D);return O.match(K)||[]}function D(N){return N.replace(M,"$1 ")}function I(N,P,Q,O){return(H.selectors[P])?H.selectors[P](N,Q,O):[]}var E={toArray:function(O){var N=[];for(var P=0;P<O.length;P++){N.push(O[P])}return N}};var C={isTag:function(O,N){return(N=="*")||(N.toLowerCase()==O.nodeName.toLowerCase())},previousSiblingElement:function(N){do{N=N.previousSibling}while(N&&N.nodeType!=1);return N},nextSiblingElement:function(N){do{N=N.nextSibling}while(N&&N.nodeType!=1);return N},hasClass:function(N,O){return(O.className||"").match("(^|\\s)"+N+"(\\s|$)")},getByTag:function(N,O){return O.getElementsByTagName(N)}};var J={"#":function(N,P){for(var O=0;O<N.length;O++){if(N[O].getAttribute("id")==P){return[N[O]]}}return[]}," ":function(O,Q){var N=[];for(var P=0;P<O.length;P++){N=N.concat(E.toArray(C.getByTag(Q,O[P])))}return N},">":function(O,R){var N=[];for(var Q=0,S;Q<O.length;Q++){S=O[Q];for(var P=0,T;P<S.childNodes.length;P++){T=S.childNodes[P];if(T.nodeType==1&&C.isTag(T,R)){N.push(T)}}}return N},".":function(O,Q){var N=[];for(var P=0,R;P<O.length;P++){R=O[P];if(C.hasClass([Q],R)){N.push(R)}}return N},":":function(N,P,O){return(H.pseudoClasses[P])?H.pseudoClasses[P](N,O):[]}};H.selectors=J;H.pseudoClasses={};H.util=E;H.dom=C;return H})();var fairplexNarrow = {
	src:'/flash/fairplex_narrow.swf'
}
sIFR.activate(fairplexNarrow);
<!--
Window.keepMultiModalWindow=false;
Windows.maxZIndex = 10;

var __dossier_id = 0;

function getScrollY() {
	var scrOfY = 0;
	if(typeof(window.pageYOffset)=='number') { // Netscape compliant
		scrOfY = window.pageYOffset;
	}
	else if(document.body&&(document.body.scrollTop)) {// DOM compliant
		scrOfY = document.body.scrollTop;
	}
	else if(document.documentElement&&(document.documentElement.scrollTop)) {//IE6 standards compliant mode
		scrOfY = document.documentElement.scrollTop;
	}
	return scrOfY;
}

win=false;
function popup_virtuel(page,titre,largeur,hauteur) {
	popup_virtuel_modal(page,titre,largeur,hauteur,false);
}
function popup_virtuel_modal(page,titre,largeur,hauteur,modal) {
	haut = getScrollY()+300;
	if (win) {
		try {
			win.setTitle(titre);
			win.setURL(page);
			win.show(modal);
			win.setSize(largeur, hauteur);
			win.setLocation(haut, 500);
		} catch(e) {
			return false;
		}
	}
	else {
		win = new Window ("modification", {
			className: "dialog",
			title: titre, 
			top:haut, left:500, width:largeur, height:hauteur, 
			showEffect: Element.show,
			hideEffect: Element.hide,
			resizable: false,
			maximizable: false,
			url: page
		});
		win.show(modal);
	}
}

FieldsetImages = Class.create({
	element: false,
	content: false,
	cpt: 1,
  initialize: function(id, imgs) {
  	this.element = $(id);
		this.element.insert({top:'<div class="fieldset_images_toolbar"><a href="#" class="ajouter">Ajouter une image</a></div><div id="'+id+'_content"></div>'});
  	this.content = $(id+'_content');
		imgs.each(function(img){
			this._create(img);
		}, this);
		$(id).select('a.ajouter').each(function(elt){
			$(elt).observe('click',this.add.bindAsEventListener(this));
		}, this);
		
	},
	_create: function(img){
		var newid = this.cpt++;
		this.content.insert({bottom:'<div class="frm_img_preview" id="fsi_container_'+newid+'"><input name="image['+newid+']" id="fsi_image_'+newid+'" type="hidden" value="'+img+'"><img src="/index.php?_l_=upload/preview&amp;ressource='+img+'&amp;maxwidth=180&amp;maxheight=180"/><a href="#" onclick="" class="picto_supprimer"></a></div>'});
		$('fsi_container_'+newid).select('img').first().observe('click',this.edit.bind(this,'fsi_container_'+newid));
		$('fsi_container_'+newid).select('a').first().observe('click',this.remove.bind(this,'fsi_container_'+newid));
	},
	add: function() {
	  Scarabe.Uploader.open({title:'Nouvelle image',preview:true,onDone:this._create.bind(this)});
	},
	remove: function(id) {
		$(id).remove();
	},
	edit: function(id) {
	  Scarabe.Uploader.open({title:'Changer l\'image',preview:true,//'
	  	onDone:function (sid){
	  		$(id).select('img').first().replace('<img src="/index.php?_l_=upload/preview&amp;ressource='+sid+'&amp;maxwidth=180&amp;maxheight=180"/>');
	  		$(id).select('input[type=hidden]').first().value = sid;
	  	}});
	}
});


BlocManager = Class.create({
	target_bloc:{},
	target_tpl:'',
	current_bloc:0,
	mode: 'edit',
  initialize: function(options) {
    this.options = {
    };
    Object.extend(this.options, options || { });
  },
  open_window: function(options, content, modal){
  	var opts = {
  		title: '&nbsp;', 
  		minimizable:false, 
  		maximizable: true,
  		top:20, 
  		left:70,
  		height:600, 
  		width:900, 
			resizable: true, 
			closable:true, 
			hideEffect:Element.hide, 
			showEffect:Element.show,
			recenterAuto:false
  	};
    Object.extend(opts, options || { });
		var win = new Window(opts);
		Element.update(win.getContent(),content);
		win.setDestroyOnClose(false);
		win.setStatusBar('&nbsp;');
		win.showCenter(modal);  	
  },
  request: function(options){
  	var opts = {
  		method: 'post',
			evalScripts: true, 
			encoding:'ISO-8859-1'
  	};
    Object.extend(opts, options || { });
		return new Ajax.Request( '/index.php', opts);
  },
  updater: function(id, options){
  	var opts = {
  		method: 'post',
			evalScripts: true, 
			encoding:'ISO-8859-1'
  	};
    Object.extend(opts, options || { });
		return new Ajax.Updater( id, '/index.php', opts);
  },
  get_bloc_position: function(zone,id){
  	var blocs = $$('#'+zone+' .dbbloc');
  	var pos = blocs.size();
  	for(var i=0; i<pos;i++){
  		if (blocs[i].id == '_cms_'+id)
  			return i; 
  	}
  	return pos;
  },
  
  update_admin_bloc: function(p,cap, tpl,ord){
		var pars = '_l_=admin/select_bloc&zone='+this.target_bloc.zone+'&page='+this.target_bloc.page+'&p='+p+'&capacity='+cap+'&template='+tpl+'&ordre='+ord+'&dossier_id='+__dossier_id;
  	this.updater('win_bloc_manager_content',{
			parameters: pars
  	});
  },
	admin_blocs: function(page,zone,id){
		this.target_bloc.page = page;
		this.target_bloc.zone = zone;
		this.target_bloc.position = this.get_bloc_position(zone,id);
		
		if (id>0){
			this.target_bloc.id = id;
			this.current_bloc = id;
			this.mode = 'edit';
		}
		else {
			this.current_bloc = 0;
			this.mode = 'add';
		}
		var pars = '_l_=admin/select_bloc&zone='+zone+'&page='+page+'&id='+id+'&dossier_id=0';
		var bloc_man = this;
		this.request({
			parameters: pars,
			onComplete: function(request){
				bloc_man.open_window({id:'win_bloc_manager', title: 'Choisir un bloc'}, request.responseText, true);
			}
		});
	},
	select_bloc: function(id){
		this.display_bloc(id,'blocs_manager_detail');
		gally_style.curry($('blocs_manager_detail')).defer();
		this.current_bloc = id;
	},
	valider_bloc: function(id){
			var bloc_man = this;
			var pars = {
				_l_:'admin/set_page_bloc',
				mode:'edition',
				page: this.target_bloc.page,
				position: this.target_bloc.position,
				zone: this.target_bloc.zone,
				id: id,
				oldid: this.target_bloc.id
			}
			this.request({
				parameters: pars,
				onComplete: function(request){
					window.location.reload( true );
			}});
	},
	start_select_template: function(){
		Element.show('select_template');
		Element.hide('blocs_manager_actions');
	},
	stop_select_template: function(){
		Element.hide('select_template');
		Element.show('blocs_manager_actions');
	},
	select_template: function(template, preview,tplname){
		this.update_liste_blocs(template)	;
		Element.update('selected_template', 
			'<a href="#" onclick="bloc_manager.start_select_template();return false;"><img src="/images/blocs/'+preview+'"/><span>'+tplname+'</span></a>');
		this.stop_select_template();
		this.target_tpl = template;
	},
	start_select_theme: function(){
		Element.show('select_theme');
	},
	stop_select_theme: function(){
		Element.hide('select_theme');
	},
	select_theme: function(theme){
		$('theme_hid').value = theme;
		Element.update('selected_theme', 
			'<a href="#" onclick="bloc_manager.start_select_theme();return false;" title="'+theme+'"><img src="/images/blocs/'+theme+'.jpg"/></a>');
		this.stop_select_theme();
	},
	supprimer_bloc: function(){
		var bloc_man = this;
		if (this.current_bloc){
			var id = this.current_bloc;
			var pars = '_l_=admin/delete_bloc&id='+id;
			var myAjax = new Ajax.Request( '/index.php', { method: 'post', parameters: pars, encoding:'ISO-8859-1',
				onComplete: function(request){
					if ($('_cms_'+id))
						Element.remove('_cms_'+id);
					Element.remove('_ed_'+id);
					bloc_man.update_liste_blocs(bloc_man.target_tpl);
			}});
		}
	},
	
	add_bloc: function(tpl, dossier_id){
		var pars = '_l_=admin/add_bloc&template='+tpl+'&dossier_id='+dossier_id;;
		var bloc_man = this;
		this.request({
			parameters: pars,
			onComplete: function(request){
				bloc_man.open_window({id:'win_edit_bloc', title: 'Nouveau bloc'}, request.responseText, true);
		}});
	},
	
	edit_bloc: function(id, dossier_id){
		var bloc_man = this;
		var tpl = this.target_tpl;
		var pars = '_l_=admin/edit_bloc&id='+id+'&dossier_id='+dossier_id;
		var myAjax = new Ajax.Request( '/index.php', { method: 'post', parameters: pars,
					evalScripts: true, encoding:'ISO-8859-1',
			onComplete: function(request){
				bloc_man.open_window({id:'win_edit_bloc', title: 'Edition du bloc',onShow:function(){
					Windows.getWindow('win_edit_bloc').updateHeight();
				}
					}, request.responseText, true);
		}});
	},
	save_edit_bloc: function(frm, id){
		var bloc_man = this;
		var pars = '_l_=admin/save_bloc&idpfx=_ed_&'+Form.serialize(frm);
		this.request({
			parameters: pars,
			onComplete: function(request){
				bloc_man.update_liste_blocs(bloc_man.target_tpl);
				Element.update('blocs_manager_detail', request.responseText);
				gally_style.curry($('blocs_manager_detail')).defer();
		}});
		var win = Windows.getWindow('win_edit_bloc');
		win.close();
	},
	save_add_bloc: function(frm){
		var bloc_man = this;
		var pars = '_l_=admin/save_bloc&idpfx=_ed_&'+Form.serialize(frm);
		this.request({
			parameters: pars,
			onComplete: function(request){
				bloc_man.update_liste_blocs(bloc_man.target_tpl);
				Element.update('blocs_manager_detail', request.responseText);
				gally_style.curry($('blocs_manager_detail')).defer();
		}});
		var win = Windows.getWindow('win_edit_bloc');
		win.close();
	},
	
	retire_bloc: function(page,zone,id){
		var pars = '_l_=admin/retire_bloc&id='+id+'&zone='+zone+'&page='+page;
		var myAjax = new Ajax.Request( '/index.php', { method: 'post', parameters: pars, encoding:'ISO-8859-1',
			onComplete: function(request){
				Element.remove('_cms_'+id);
		}});
	},
	update_liste_blocs: function(template){
		var pars = '_l_=admin/liste_blocs&template='+template;
		var bloc_man = this;
		var myAjax = new Ajax.Request( '/index.php', { method: 'post', parameters: pars,
					evalScripts: true, encoding:'ISO-8859-1',
			onComplete: function(request){
				Element.update('blocs_manager_liste', request.responseText);
		}});
	},
	display_bloc: function(id,tgt){
		var pars = '_l_=admin/display_bloc&idpfx=_ed_&id='+id;
		var myAjax = new Ajax.Request( '/index.php', { method: 'post', parameters: pars,
					evalScripts: true, encoding:'ISO-8859-1',
			onComplete: function(request){
				Element.update(tgt,request.responseText);
		}});
	},
	dump_bloc: function(id){
		var bloc_man = this;
		var pars = '_l_=admin/dump_bloc&id='+id;
		var myAjax = new Ajax.Request( '/index.php', { method: 'post', parameters: pars, encoding:'ISO-8859-1',
			onComplete: function(request){
				bloc_man.open_window({title: 'Dump'}, request.responseText, false);

		}});
	},
	switch_edit_img: function(imgid){
		var fldset = 'fldset_'+imgid;
		var preview = 'preview_'+imgid;
		if (Element.visible(fldset)){
			var img = $$('#fldset_'+imgid+' .image_preview img')[0];
			var tgt = $$('#preview_'+imgid+' img')[0];
			tgt.src = img.src;
			$('ed_lst_img_'+imgid).removeClassName('ed_lst_img_wide');
		}
		else {
			$('ed_lst_img_'+imgid).addClassName('ed_lst_img_wide');
		}
		Element.toggle(fldset);
		Element.toggle(preview);
	},
	diapo_add_img: function(tgt){
    var tpl = TrimPath.parseTemplate($('___tpl_diapo_img').value);
    var context = {
    	img_id: 'jsgen'+(Scarabe.seq++)
    }
		$(tgt).insert({bottom:tpl.process(context)});
		Sortable.destroy(tgt);
		Sortable.create(tgt,{
			tag:'div',
			handle:'picto_deplacer_lvl2', 
			onUpdate: function () { $(tgt+"_ord").value = Sortable.serialize(tgt) },
			constraint:false
		});		
		$(tgt+"_ord").value = Sortable.serialize(tgt);
	},
	update: function(pars){
		this.request({
			parameters: pars,
			encoding: 'UTF-8',
			onComplete: function(request){
				eval(request.responseText);
			}
		});
	}
});
var bloc_manager = new BlocManager();


var Scarabe = {
	seq:0,
	progress: function(id){
		$(id).innerHTML = '<div id="boxLoad"><img src="images/loading.gif"/><span>loading</span></div>';
	},
	alert: function(msg){
		window.alert(msg);
	},
	execute: function(pars){
		var myAjax = new Ajax.Request( '/index.php', { method: 'post', parameters: pars, 
			onComplete: function(request){
				var win_msg = $('win_msg');
				if (win_msg){
					win_msg.update(request.responseText);
				}
		}});
	},
	admin_articles: function(cat_id){
		var t = this;
			var pars = '_l_=admin/admin_articles&id='+cat_id;
			var myAjax = new Ajax.Updater(
				'adm_art', 
				'/index.php', 
				{
					method: 'post', 
					parameters: pars,
					encoding:'ISO-8859-1',
					evalScripts: true,
					onComplete: t.apply_style.curry($('adm_art'))

				});
	},
	apply_style: function(elt){
//		gally_style.delay(0.02,elt);
		gally_style.curry(elt).defer();
	},
	supprimer_article: function(cat_id, id){
		var x = this;
		if (confirm('Vous allez supprimer un article!')){
			new Ajax.Request( '/index.php', { method: 'post', parameters: {_l_:'admin/supprimer_article',id:id}, encoding:'ISO-8859-1',
				onComplete: function(request){
					x.admin_articles(cat_id);
			}});
		}
	},
	supprimer_categorie: function(id){
		var x = this;
		if (confirm('Vous allez supprimer une catégorie!')){
			new Ajax.Request( '/index.php', { method: 'post', parameters: {_l_:'admin/supprimer_categorie',id:id}, encoding:'ISO-8859-1',
				onComplete: function(request){
					Element.remove('categorie_lvl2_'+id);
					Element.update('adm_art','');
			}});
		}
	},
	open_win: function(pars, opts){
		var x = this;
		
		var winopts = Object.extend({
		      className:         "dialog",
		      blurClassName:     null,
		      minWidth:          100, 
		      minHeight:         20,
		      resizable:         true,
		      closable:          true,
		      minimizable:       true,
		      maximizable:       true,
		      draggable:         true,
		      userData:          null,
		      showEffect:        Element.show,
		      hideEffect:        Element.hide,
		      showEffectOptions: {},
		      hideEffectOptions: {},
		      effectOptions:     null,
		      parent:            document.body,
		      title:             "&nbsp;",
		      onload:            Prototype.emptyFunction,
		      width:             200,
		      height:            300,
		      opacity:           1,
		      recenterAuto:      true,
		      wiredDrag:         false,
		      closeCallback:     null,
		      destroyOnClose:    false,
		      gridX:             1, 
		      gridY:             1      
		    }, opts || {});		
		new Ajax.Request( '/index.php', { method: 'get', parameters: pars, encoding:'ISO-8859-1',
			onComplete: function(request){
				var win = new Window(winopts);
				Element.update(win.getContent(), request.responseText);
				win.setDestroyOnClose(true);
				win.setStatusBar("&nbsp;");
				win.showCenter(true);
				gally_style.curry(win.getContent()).defer();
			}
		});
	}	
}

Scarabe.Uploader = {
	messages: {
		aucun_chargement:"No upload.",
		chargement_en_cours:"Uploading...",
		chargement_termine:"Upload complete.",
		info_transfere:'Transfered: ',
		info_poids:'Total transfered: ',
		info_poids_total:'Total size: ',
		veuillez_patienter:"Uploading. Please wait until upload is complete."
	},
	field: '',
	cgi: false,
	ul: {},
	in_progress: 0,
	updater: {},
	sid: false,
	onDone: function(hid){},
	url_uploader: "/index.php",
	winid:'window_id_upload',
	cpt:1,
	win:{},
	options:{},
	open: function(options){
		if (options.onDone){
			this.onDone = options.onDone
		}
		this.options = options;
		this.field = options.field;
		var pars = '_l_=upload/form&name='+options.field;
		var myAjax = new Ajax.Request( this.url_uploader, { method: 'post', parameters: pars,
			onComplete: function(request){Scarabe.Uploader.showForm(options.title,request)} });
	},
	showForm: function(title, originalRequest){
		this.win = new Window(this.winid, {title: title, minimizable:false, maximizable: false,
                                              top:70, left:70, width:350, height:200,
                                              resizable: false, closable:false, hideEffect:Element.hide, showEffect:Element.show})
		this.win.getContent().innerHTML= originalRequest.responseText;
		this.win.setDestroyOnClose(false);
		this.win.setStatusBar(this.messages.aucun_chargement);
		this.win.showCenter(true);
	},
	beginUpload: function(ul,sid) {
		if ( this.in_progress == 0 ){
			this.sid = sid + this.cpt;
			this.cpt++;
			if (!this.cgi){
				this.cgi = ul.form.action;
			}
			ul.form.action = this.cgi+'?sid='+this.sid;
			ul.form.submit();
			this.ul = ul;
			this.in_progress = 1;
			var pb = $(ul.name + "_progress");
			Element.show(pb.parentNode);
			this.win.setStatusBar(this.messages.chargement_en_cours);
			Scarabe.Uploader.updater = new Ajax.PeriodicalUpdater({update:Prototype.emptyFunction},Scarabe.Uploader.url_uploader,{'decay': 2,'frequency' : 0.5,'method': 'post','parameters': '_l_=upload/progress&sid=' + this.sid,'onComplete':Prototype.emptyFunction,'onSuccess' : function(request){Scarabe.Uploader.updateProgress(ul,request)},'onFailure':function(request){Scarabe.Uploader.updateFailure(pb,request)}})
		}
	},
	updateProgress: function(ul,req) {
		var pb = $(ul.name + "_progress");
		var info = req.responseText.split(',');
		var percent = parseInt(info[0]);
		var done_size = info[1];
		var total_size = info[2];
		
//		if ( this.sid != info[3] ){
//			alert('mismatch sid');
//		}
		if (this.in_progress == 0){
				Scarabe.Uploader.updater.stop();
				this.updater.stop();
		}

		if (this.in_progress == 1 && this.sid == info[3]) {
			if(!percent) percent = 0;
			pb.style.width = percent + "%";
			$('file2upload_info').innerHTML = this.messages.info_transfere+percent+'%<br>'+this.messages.info_poids+done_size+'<br>'+this.messages.info_poids_total+total_size;//+'<br>sid='+this.sid+'<br>serversid='+info[3];
			if(percent >= 100) {
				Scarabe.Uploader.updater.stop();
				Scarabe.Uploader.updater.onTimerEvent=Prototype.emptyFunction;
				this.win.setStatusBar(this.messages.chargement_termine);
				var inp_id = pb.id.replace("_progress","");
				if(this.sid) {
					var inp = $(inp_id+'_sid');
					if(inp) {
						inp.value = this.sid;
					}
					if (this.options.preview){
						this.HTMLPreview('file2upload_preview', this.sid);
					}
				}
				Element.hide(pb.parentNode);
				this.in_progress = 0;
			}
		}
	},
	HTMLPreview: function(elt, sid){
		Element.update(elt, '<div><span></span><img src="/index.php?_l_=upload/preview&sid='+sid+'"/></div>');
	},
	endProgress: function(val){
		this.sid = false;
		var field = $(this.field);
		if (field){
			field.value = val;
		}
		if (this.onDone){
			this.onDone(val);
		}
		this.win.hide();
	},
	updateFailure: function(pb,req) {
		var mes = req.responseText;
		pb.style.width=0;
		alert(mes);
		this.in_progress = 0;
	},
	cancelUpload: function(){
		this.in_progress = 0;
		this.win.hide();
	},
	submitUpload: function(hidid) {
		if(this.in_progress > 0) {
			alert(this.messages.veuillez_patienter);
		} else {
			var val = $F(hidid);
			this.endProgress(val);
		}
	}
};
		
Scarabe.Form = {
	clearfield: function(id, defval){
		if ($(id) && $F(id) == defval){
			$(id).value = '';
		}
	},
	submit: function(frm,action) {
		frm = $(frm);
		if ( $(frm.name+'_qf_default') ){
			$(frm.name+'_qf_default').value = frm.name+':'+action;
		}
		else {
			new Insertion.Top(frm, '<input id="'+frm.name+'_qf_default" type="hidden" name="'+action+'" value="1"/>');
		}
		frm.submit();
	},
	submit_: function (){
		tinyMCE.triggerSave(true,true);
//		document.forms["editarticleform"].submit();
	},
	edithtml: function (id, w, h){
		if (typeof(w) == "undefined"){
			w = 600;
		}
		if (typeof(h) == "undefined"){
			h = 480;
		}
		win = Windows.getWindow('IDWIN');
		
		if (!win){
			win = new Window('IDWIN', {title: '&nbsp;', minimizable:false, maximizable: false, url: '/tinymce.php', 'class':'dialog', top:70, left:70, width:600, height:400, resizable: true, closable:true, showEffect: Element.show, hideEffect: Element.hide});
		}
		else {
				win.editor.execCommand('mceSetContent', false, $F(id));
		}
		win.html_field = $(id);
		win.showCenter(true);
	},
	sethtml: function(id,value){
		var win = Windows.getWindow('IDWIN');
		$('_'+id.id).innerHTML = value;
		$(id).value = value;
		win.hide();
	}
};


Scarabe.Service = {
	url: '/index.php',
	popup_cpt: 1,
	
	ask: function(req, onComplete){

		var params = 'type='+req.type+'&source='+req.source;
		for(var i=0; i<req.param.length; i++){
			var parm = req.param[i];
			params += '&param['+i+'][name]='+parm['name']+'&param['+i+'][value]='+parm['value']+'&';
		}
		var myAjax = new Ajax.Request( '/dump_req.php', { method: 'post', parameters: params,
		onComplete: onComplete});

	},
	submit: function(id, frm, action){
		frm = $(frm);
		if ( $(frm.name+'_qf_default') ){
			$(frm.name+'_qf_default').value = frm.name+':'+action;
		}
		else {
			new Insertion.Top(frm, '<input id="'+frm.name+'_qf_default" type="hidden" name="'+action+'" value="1"/>');
		}
		var pars = Form.serialize(frm);
		var myAjax = new Ajax.Updater(
			id, 
			this.url, 
			{
				method: 'post', 
				parameters: pars,
				evalScripts: true
			});
	},
	update: function(id, pars){
		$(id).startWaiting('bigWaiting');
		var myAjax = new Ajax.Updater(
			id, 
			this.url, 
			{
				method: 'get', 
				parameters: pars,
				evalScripts: true,
				onSuccess: function(){ $(id).stopWaiting();}
			});
	},
	ajax_popup: function(query, options){
		var myAjax = new Ajax.Request( this.url, { method: 'post', parameters: query,
			onComplete: function(originalRequest){
				Scarabe.Service.open_popup(originalRequest.responseText, options)
			}
		});
	},
	open_popup: function(content, options){
		winid = 'win_popup_'+this.popup_cpt++;
		win = new Window(winid, options)
		win.getContent().innerHTML= content;
		win.setDestroyOnClose(true);
		win.setStatusBar('&nbsp;');
		win.showCenter();
	}
	
}

function isIe6(){
	var browser=navigator.appName;
	var b_version=navigator.appVersion;
	var version=parseFloat(b_version);
	return browser=="Microsoft Internet Explorer" && !window.XMLHttpRequest;
}



function my$$(expr,e){
		return (Object.isUndefined($(e))) ? $$(expr) : $(e).select(expr);
}

function gally_style(e){
	// Les bordures
	if (!isIe6()){
		
		var classes = [
			{classe: 'arrondi_bas', border:{ corner:8, shadow:0, edges:"blr" }},
			{classe: 'arrondi_haut', border:{ corner:8, shadow:0, edges:"tlr" }},
			{classe: 'arrondi_gauche', border:{ corner:8, shadow:0, edges:"tbl" }}, 
			{classe: 'arrondi_haut_gauche', border:{ corner:8, shadow:0, edges:"tl" }},
			{classe: 'arrondi_bas_gauche', border:{ corner:8, shadow:0, edges:"bl" }},
			{classe: 'arrondi_haut_droite', border:{ corner:8, shadow:0, edges:"tr" }},
			{classe: 'arrondi_bas_droite', border:{ corner:8, shadow:0, edges:"br" }} /*,
		{classe: 'arrondi', border:{ corner:8, shadow:0 }} */
		];
		classes.each(function(b){
			/*
			var myBorder = RUZEE.ShadedBorder.create(b.border);
			my$$('.'+b.classe,e).each(function(elt){
				elt.innerHTML = '<p>'+elt.innerHTML+'</p>';
				myBorder.render(elt);
			});
			*/
			var renderer = new ShaBoRenderer();
			renderer.Init(b.border);
			my$$('.'+b.classe,e).each(function(elt){
			elt.innerHTML = '<p>'+elt.innerHTML+'</p>';
				renderer.RenderElement(elt);
			});
			renderer.Dispose();
			renderer = null;
		});
	
		// Les titres flash
		classes = [
			{classe:'theme_1', color:"#c9d6a3"},
			{classe:'theme_2', color:"#ffffff"},
			{classe:'theme_3', color:"#e5e811"},
			{classe:'theme_4', color:"#ffffff"},
			{classe:'theme_5', color:"#ffffff"},
			{classe:'theme_6', color:"#006b54"},
			{classe:'theme_7', color:"#86712E"},
			{classe:'theme_8', color:"#C38D1C"},
			{classe:'theme_9', color:"#C38D1C"},
			{classe:'theme_10', color:"#86712E"},
			{classe:'theme_11', color:"#ffffff"},
			{classe:'theme_12', color:"#ffffff"}
		];
		
		classes.each(function(c){
			my$$('.'+c.classe+' .titre_bloc_coldroite',e).each(function(elt){
				elt.addClassName('sifr_'+c.classe);
			});
			sIFR.replace(fairplexNarrow, {
				selector: '.sifr_'+c.classe,
				css: {
					'.sIFR-root': {
						'font-size':'14px',
						'font-weight':'normal',
						'letter-spacing':'0.5',
						'color': c.color
					},
					'a': {
						'color': c.color,
						'font-weight':'normal',
						'text-decoration': 'none'
					}
				},
				wmode: 'transparent'
			}); 
		});
		sIFR.replace(fairplexNarrow, {
			selector: '.bloc_coldroite_titre_texte .titre_bloc_coldroite, .titre_image_petit',
			css: {
				'.sIFR-root': {
					'font-size':'14px',
					'font-weight':'normal',
					'letter-spacing':'0.5',
					'color': '#ffffff'
				},
				'a': {
					'color': '#ffffff',
					'font-weight':'normal',
					'letter-spacing':'0.5',
					'text-decoration': 'none'
				}
			},
			wmode: 'transparent'
		}); 
		sIFR.replace(fairplexNarrow, {
			selector: '.bloc_coldroite_cartouche_soustitre1, .titre_billet',
			css: {
				'.sIFR-root': {
					'font-size':'14px',
					'font-weight':'normal',
					'letter-spacing':'0.5',
					'color': '#006b54'
				},
				'a': {
					'color': '#006b54',
					'font-weight':'normal',
					'letter-spacing':'0.5',
					'text-decoration': 'none'
				}
			},
			wmode: 'transparent'
		}); 
		
		sIFR.replace(fairplexNarrow, {
			selector: 'h1',
			css: {
				'.sIFR-root': {
					'font-size':'22px',
					'color': '#99e5b2',
					'font-weight':'bold'
				}
			},
			offsetTop : '3px',
			wmode: 'transparent'
		});
		sIFR.replace(fairplexNarrow, {
			selector: '.menuitem_lvl1',
			css: {
				'.sIFR-root': {
					'text-align': 'center',
					'text-transform': 'uppercase',
					'font-size':'15px',
					'letter-spacing':'0.5',
					'color': '#77bba2'
				}
			},
			wmode: 'transparent'
		});
			sIFR.replace(fairplexNarrow, {
			selector: '.titre_bdhome',
			css: {
				'.sIFR-root': {
					'font-size':'14px',
					'color': '#026644',
					'letter-spacing':'0.5',
					'font-weight':'normal'
				}
			},
			wmode: 'transparent'
		});
	}

	// Les rollover image
	my$$('.petit_bloc, .lien_bloc',e).each(function(elt){
		elt.observe('mouseover', function(){
			elt.addClassName('rollover');
		});
		elt.observe('mouseout', function(){
			elt.removeClassName('rollover');
		});
	});
	// photo_legende
	my$$('.photo_legende',e).each(function(elt){
		elt.insert({after:'<div class="legende">'+elt.title+'</div>'});
	});
	// Les marges
	my$$('img[align="right"]',e).each(function(elt){
		elt.style.marginLeft='8px';
		elt.style.marginRight='0';
	});
	my$$('img[align="left"]',e).each(function(elt){
		elt.style.marginLeft='0';
		elt.style.marginRight='8px';
	});
	if (!isIe6()){
		// les pictos
		var classes = [
			'ajouter','modifier','supprimer','contenu','precedent','suivant','publier','depublier','visible','invisible',
			{classe: 'valider_normal', picto:'valider'},
			{classe: 'deplacer_lvl2', picto:'deplacer'}
		];
		classes.each(function(b){
			var picto = (typeof b == 'object') ? b.picto : b;
			var classe = (typeof b == 'object') ? b.classe : b;
			var elts = my$$('.picto_'+classe,e);
			elts.each(function(elt){
				elt.observe('mouseover', elt.setStyle.curry({backgroundImage:'url(/images/picto_'+picto+'_.png)'}));
				elt.observe('mouseout', elt.setStyle.curry({backgroundImage:'url(/images/picto_'+picto+'.png)'}));
			});
		});
	}
	// Les formulaires dyn
	var frms = my$$('form.ajax',e);
	frms.each(function(frm){
		frm.getInputs('submit').each(function(b){
			b.onclick=function(evt){
				bloc_manager.request({
					parameters: frm.serialize(),
					encoding: 'UTF-8',
					onComplete: function(request){
						eval(request.responseText);
					}
				});
				return false;
			}
		});
	});	
/*	my$$('img',e).each(function(img){
		var imgName = img.src.toUpperCase()
		if (imgName.substring(imgName.length-3, imgName.length) == "PNG") {
			var imgID = (img.id) ? "id='" + img.id + "' " : ""
			var imgClass = (img.className) ? "class='" + img.className + "' " : ""
			var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "
			var imgStyle = "display:inline-block;" + img.style.cssText 
			if (img.align == "left") imgStyle = "float:left;" + imgStyle
			if (img.align == "right") imgStyle = "float:right;" + imgStyle
			var strNewHTML = "<span " + imgID + imgClass + imgTitle
			+ " style=\"" + "font-size:1px;" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
			+ "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
			+ "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>" 
			img.outerHTML = strNewHTML
		}//if		
	});*/
}

FastInit.addOnLoad(gally_style);


