var moz = Prototype.Browser.Gecko
var ie = Prototype.Browser.IE
var mac = navigator.userAgent.toLowerCase().indexOf("mac") > -1

/*--------------------------------------------------------------------------*/
function exception(exeption){
	var er = function(){}
	
	if(Prototype.Browser.IE){
		er.url = document.location.href
		er.line = (exeption.number || 0)
	}
	else{
		er.url = exeption.fileName
		er.line = (exeption.lineNumber || 0)
	}
	er.message = exeption.message
	return er
}

ErrorHandler = {
	dialogOpen: false,
	errors: [],
	timeoutId: null,
	dialogUrl: null,
	reportUrl: null,
	hideDialog: true,
	jobDescription: '',
	
	start: function(reportUrl, dialogUrl){
		if(reportUrl) ErrorHandler.reportUrl = reportUrl
		if(dialogUrl) ErrorHandler.dialogUrl = dialogUrl
		
		window.onerror = ErrorHandler.fire
	},
	
	dialog: function(message, url, line, onClose){
		Interface.dialog('/error.php', ['sid'], {width: 450, height: 400, dialogVars: {message: message, url: url, line: line}, onClose: onClose})
	},
	throwError: function(er, message){
		var url, line
		er = exception(er)
		
		ErrorHandler.fire(er.message + ', job: ' + message, er.url, er.line)
		
		throw(er)
	},
	fire: function(message, url, line){
		if(message.match(/800a025e/)) return true
		if(!ErrorHandler.reportUrl) return false
		
		if(!ErrorHandler.hideDialog && ErrorHandler.dialogUrl && !ErrorHandler.dialogOpen && Cookie.accept() && !Cookie.get('hideErrorTracker')){
			ErrorHandler.dialogOpen = true
			
			clearTimeout(ErrorHandler.timeoutId)
			ErrorHandler.timeoutId = null
			
			ErrorHandler.dialog(message, url, line, function(ret){
				ErrorHandler.dialogOpen = false
				if(ret && ret['stopBotheringMe']) Cookie.set('hideErrorTracker', 1, 7)
				ErrorHandler.track(message, url, line, ret && ret['comment'] ? ret['comment'] : '')
				ErrorHandler.send()
			})
		}
		else ErrorHandler.track(message, url, line)
		return false
	},
	track: function(message, url, line, comment){
		message =  ErrorHandler.jobDescription ? message + ' (job: '+ErrorHandler.jobDescription+'' : message
		ErrorHandler.errors.push({message: message, url: url, line: line, comment: comment})
		
		if(ErrorHandler.timeoutId) clearTimeout(ErrorHandler.timeoutId)
		ErrorHandler.timeoutId = setTimeout(function(){ErrorHandler.timeoutId = null; ErrorHandler.send()}, 1000)
	},
	send: function(){
		if(!ErrorHandler.reportUrl || !ErrorHandler.errors.length) return false
		if(ErrorHandler.timeoutId) clearTimeout(ErrorHandler.timeoutId)
		ErrorHandler.timeoutId = null
		
		var pars = []
		if($('sid')) pars.push('sid='+$F('sid'))
		else return null
		
		pars.push('script='+escape(ErrorHandler.errors[0]['url']))
		
		$A(ErrorHandler.errors).each(function(er){
			pars.push('message[]='+escape(er['message']))
			pars.push('line[]='+escape(er['line']))
			pars.push('comment[]='+(er['comment'] ? escape(er['comment']) : ''))
		})
		
		ErrorHandler.errors = []
		
		new Ajax.Request(ErrorHandler.reportUrl, {method: 'post', parameters: pars.join('&')})
	},
	startJob: function(description, noDialog){
		if(noDialog) ErrorHandler.hideDialog = true
		ErrorHandler.jobDescription = description
	},
	endJob: function(){
		ErrorHandler.hideDialog = false
		ErrorHandler.jobDescription = ''
	}
}
//ErrorHandler.start(self.ErrorHandlerReportUrl, self.ErrorHandlerDialogUrl)

function hasClassName(el, name){
	var func = function(el, name){
		return !el || !name || !el.className ? false : el.className == name ? true : el.className.indexOf(' ') > -1 && el.className.split(/ +/).indexOf(name) > -1 ? true : false
	}
	
	if(typeof name == 'string') return func(el, name)
	else if(name.length){
		var found = false
		$A(name).each(function(n){
			if(func(el, n)) found = true
		})
		return found
	}
}

function grS(){
	return Document.getAssetsBaseUrl()
}

Object.extend(Element, {
	ancestor: function(el, tagName){
		tagName = tagName.toUpperCase()
		if(el.parentElement){
			while(el && el.parentElement){
				if(el.parentElement.tagName.toUpperCase() == tagName) return el.parentElement
				el = el.parentElement
			}
		}
		else if(el.parentNode){
			while(el && el.parentNode && el.parentNode.tagName){
				if(el.parentNode.tagName.toUpperCase() == tagName) return el.parentNode
				el = el.parentNode
			}
		}
	}
})
Object.extend(Event, {
	wheel: function(event){
		var delta = 0
		if(!event) event = window.event
		if(event.wheelDelta){
			delta = event.wheelDelta / 120
			if(window.opera) delta = -delta
		}
		else if(event.detail) delta = -event.detail / 3
		return Math.round(delta); //Safari Round
	}
})
function $RF(el, radioGroup) {
    if($(el).type && $(el).type.toLowerCase() == 'radio'){
        var radioGroup = $(el).name
        var el = $(el).form
    }
	else if ($(el).tagName.toLowerCase() != 'form') return false

    var checked = $(el).getInputs('radio', radioGroup).find(
        function(re){return re.checked}
    )
    return (checked) ? $F(checked) : null
}

function show(){
	var el
	var show = function(el){
		if(!el) return
		el = $(el)
		if(!el) return
		
		if(hasClassName(el, 'displayNone')) el.removeClassName('displayNone')
		el.show()
	}
	
	for(i = 0; i < arguments.length; i++){
		var arg = arguments[i]
		if(typeof arg != 'string' && arg.length){
			$A(arg).each(function(el){show(el)})
		}
		else show(arguments[i])
	}
}

document.getViewport = function(){
	var viewport = document.viewport.getDimensions()
	if(Prototype.Browser.IE){
		viewport.width = document.body.clientWidth
		viewport.height = document.body.clientHeight
	}
	return viewport
}

////////////////////////////////////////
////////////////////////////////////////
Object.extend(document, {
	init: function(parentElement){
		if(!parentElement) return false
		
		ErrorHandler.startJob('document.init('+parentElement+')', true)
		
		parentElement = $(parentElement)
		
		if(parentElement == document){
			if(document.body.getAttribute('scroll') == 'no') $(document.body).setStyle({overflow: 'hidden'})
		}
		
		var _buttons = [], _tabGroups = [], _groupHeadings = [], _calendars = [], _dradInterfaces = []
		var _lists = [], _trees = [], _editors = [], _topics = [], _buttonScrollers = [], _scrollers = []
		
		$A(parentElement.getElementsByTagName('*')).each(function(el){
			if(!el.attributes) return
			if(hasClassName(el, ['link', 'button'])){
				_buttons.push(el)
			}
			if(el.tagName == 'TABLE' && hasClassName(el, 'tabGroup')){
				_tabGroups.push(el)
			}
			if(hasClassName(el, 'groupHeadingTbody')) _groupHeadings.push(el)
			if(el.tagName == 'INPUT' && el.attributes.getNamedItem('calendar')){
				_calendars.push(el)
			}
			if(hasClassName(el, 'menuHolder')) Document.initMenuHolder(el)
			if(hasClassName(el, 'list')){
				_lists.push(el)
				el.setAttribute('focusable', 1)
			}
			if(hasClassName(el, 'listNav') && el.getAttribute('list')){
				Lists.navCells[el.getAttribute('list').toLowerCase()] = $(el)
			}
			if(hasClassName(el, 'tree')){
				_trees.push(el)
				el.setAttribute('focusable', 1)
			}
			if(hasClassName(el, ['dashBoardTopic', 'editorTopic'])) _topics.push(el)
			if(hasClassName(el, 'dradInterface')) _dradInterfaces.push(el)
			if(hasClassName(el, 'tableFloat')){
				el = $(el)
				el.insert({before: '<table border=0 cellpadding=0 cellspacing=0 style="float: left; margin-bottom: 2px;"><tbody><tr><td></td></tr></tbody></table>'})
				$(el.previousSibling).down('td').insert({top: el})
				el.removeClassName('tableFloat')
			}
			if(el.getAttribute('tip')){
				if(Prototype.Browser.IE){
					el.setAttribute('title', el.getAttribute('tip').gsub('<br>', '\r'))
					el.removeAttribute('tip')
				}
				else{
					$(el).observe('mouseover', function(){Document.tipOpen(el)}).observe('mouseout', function(){Document.tipClose()})
				}
			}
			
			if(hasClassName(el, 'label')){
				el = $(el)
				var field = null
				if(el.getAttribute('for')){
					field = $(el.getAttribute('for')) || $$('*[name='+el.getAttribute('for')+']').first()
				}
				
				if(!field){
					field = el.previous()
					if(!field || field.type != 'radio') field = el.next()
					if(!field || (field.tagName != 'INPUT' && field.tagName != 'TEXTAREA' && field.tagName != 'SELECT')){
						field = el.previous()
					}
					if(!field || (field.tagName != 'INPUT' && field.tagName != 'TEXTAREA' && field.tagName != 'SELECT')){
						field = null
					}
				}
				
				if(field){
					Document.autoId(field)
					
					if(field.id && $(field.id) == field){
						el.wrap(new Element('label', {'for': field.id}).observe('click', function(e){
							if(field.disabled) return
							if(field.value && field.type == 'text') field.select()
							field.fire('1site1:onchange')
						}))
					}
					else{
						el.observe('click', function(e){
							if(field.disabled) return
							if(field.value && field.type == 'text') field.select()
							if(field.type == 'checkbox') field.checked = field.checked ? false : true
							else if(field.type == 'radio') field.checked = true
							if(field.onclick) field.onclick(e)
							field.fire('1site1:onchange')
							Event.stop(e)
						})
						el.setAttribute('labelInitiated', 1)
						el.observe('mousedown', function(e){
							if(!field.disabled) field.focus()
							Event.stop(e)
						})
					}
				}
				else el.observe('mousedown', function(e){Event.stop(e)})
			}
			
			// text input elements
			if(el.tagName == 'INPUT' && !el.getAttribute('type')) el.setAttribute('type', 'text')
			if(Prototype.Browser.IE && ((el.tagName == 'INPUT' && (el.getAttribute('type') == 'text' || el.getAttribute('type') == 'password')) || el.tagName == 'TEXTAREA')){
				el = $(el).addClassName('textInput')
				el.observe('focus', function(){el.addClassName('textInputFocus')})
				el.observe('blur', function(){el.removeClassName('textInputFocus')})
			}
			
			// onEnter function
			if(el.tagName == 'INPUT' && el.getAttribute('onEnter')){
				el = $(el)
				el.observe('keyup', function(e){if(e.keyCode != 13) el._value = el.value})
				el.observe('mouseup', function(e){el._value = el.value})
				
				el.observe('keydown', function(e){
					if(e.keyCode != 13) return
					setTimeout(function(){
						if(el.value == el._value){
							var action = (function(e){
								eval(el.getAttribute('onEnter'))
								el.blur()
							}).bind(el)
							action()
						}
						else el._value = el.value
					}, 50)
				})
			}
			if(hasClassName(el, 'spacer')){
				var el = $(el)
				var width = el.width || parseInt(el.getStyle('width'))
				if(width){
					el.insert({bottom: '<br /><img src="'+grS()+'/graphics/shim.gif" width='+width+' height=1 />'})
					el.removeClassName('spacer')
				}
			}
			if(hasClassName(el, 'noSelect')){
				$(el).observe('mousedown', function(e){Event.stop(e)})
			}
			if(hasClassName(el, 'relativeWrapper')){
				$(el).wrap(new Element('div').setStyle({position: 'relative'})).removeClassName('relativeWrapper')
			}
			if(el.attributes.getNamedItem('integerOnly')){
				$(el).observe('keypress', function(e){
					var c = (e.keyCode || e.charCode)
					if(!((c >= 48 && c <= 57 )	// Numbers
						|| (c >= 37 && c <= 40)	// Arrows
						|| c == 8				// Backspace
						|| c == 46				// Delete
						|| c == 9				// Tab
					)) Event.stop(e)
				})
			}
			
			/// read more
			if(hasClassName(el, 'readMore')){
				el = $(el)
				
				el.insert({before: '<table class="readMoreTitle" cellspacing=0 cellpadding=0 border=0><tr><td class=plusMinus><img src='+grS()+'/graphics/shim.gif></td><td class="content"></td></tr></table>'})
				var title = el.previous('table.readMoreTitle')
				el.observe('1site1:open', function(){
					title.addClassName('readMoreTitleOpen')
					el.addClassName('readMoreOpen')
					
					if(el.getAttribute('onOpen'))eval(el.getAttribute('onOpen'))
				})
				el.observe('1site1:close', function(){
					title.removeClassName('readMoreTitleOpen')
					el.removeClassName('readMoreOpen')
				})
				el.observe('1site1:toggle', function(e){
					if(el.hasClassName('readMoreOpen')) el.fire('1site1:close')
					else el.fire('1site1:open')
				})
				var onClick = function(e){
					el.fire('1site1:toggle')
				}
				title.observe('click', onClick).observe('doubleclick', onClick).down('td.content').insert(el.down('div'))
				
			}
			
			if(hasClassName(el, 'info') && el.getAttribute('icon')){
				var icon = el.getAttribute('icon')
				if(icon.indexOf('.') < 0) icon = grS()+'/icons/'+icon+'_16.png'
				$(el).setStyle({backgroundImage: 'url('+icon+')'})
			}
			
			if(hasClassName(el, 'figure') && Prototype.Browser.IE){
				el = $(el)
				var minHeight = el.getStyle('min-height')
				if(el.getHeight() < parseInt(minHeight)) el.setStyle({height: minHeight})
			}
			
			// color picker
			if(el.tagName == 'INPUT' && el.attributes.getNamedItem('colorPicker') && !el.getAttribute('loaded')){
				el.insert({after: '<span id=colorPickerSpan_'+el.name+' style="line-height: 17px; background-image: url('+grS()+'/graphics/colorpickBG.gif); background-color: #FFFFFF;" inputElName="'+el.name+'"><img src="'+grS()+'/graphics/colorpick.gif" width=18 height=17 align=absmiddle onClick="Document.colorPicker(event)"></span>'})
				if(el.type != 'hidden'){
					el.size = 8
					el.style.marginRight = '3px'
					Event.observe(el, 'focus', function(e){Event.element(e).select()})
					Event.observe(el, 'keyup', function(e){
						var el = Event.element(e || event)
						var v = el.value
						v = v.replace(/[^0-9a-f]/gi, '').substring(0, 6).toUpperCase()
						if(v.length == 6) Document.setColorPicker(el.name, '#'+v)
					})
					Event.observe(el, 'change', function(e){
						var el = Event.element(e || event)
						var v = el.value
						v = v.replace(/[^0-9a-f]/gi, '').substring(0, 6).toUpperCase()
						if(v.length != 6){
							if(v.length == 5) v = v.replace(/([0-9a-f]{4})([0-9a-f])/i, '$1$2$2')
							if(v.length == 4) v = v.replace(/([0-9a-f]{3})([0-9a-f])/i, '$1$2$2$2')
							if(v.length == 3) v = v.replace(/([0-9a-f])([0-9a-f])([0-9a-f])/i, '$1$1$2$2$3$3')
							else if(v.length == 2) v = v.replace(/([0-9a-f])([0-9a-f])/i, '$1$1$1$2$2$2')
							else if(v.length == 1) v = v+v+v+v+v+v
						}
						if(v) el.value = '#' + v
						else el.value = ''
						Document.setColorPicker(el.name, el.value)
						el.fire('1site1:onchange')
					})
				}
				if(el.value) Document.setColorPicker(el.name, el.value)
				
				el.setAttribute('loaded', 1)
			}
			
			// tabs in texarea elements
			if(el.tagName == 'TEXTAREA' && el.attributes.getNamedItem('allowTabs') && !el.getAttribute('tabEventLoaded')){
				$(el).observe('select', Document.textareaStoreCaret).observe('click', Document.textareaStoreCaret).observe('keyup', Document.textareaStoreCaret).observe('keydown', Document.textareaKeyDown).setAttribute('tabEventLoaded', 1)
			}
			
			if(el.attributes.getNamedItem('keepValue')){
				el = $(el)
				var value = Settings.getSetting('value:'+el.name)
				var form = null
				if(value){
					if(el.tagName == 'INPUT' && el.type == 'checkbox'){
						el.checked = value == 'true' ? true : (value == 'false' ? false : el.checked)
					}
					else if(el.tagName == 'INPUT' && el.type == 'radio'){
						form = el.up('form')
						for(var i = 0; i < form[el.name].length; i++){
							if(form[el.name][i].value == value) form[el.name][i].checked = true
						}
					}
					else if(el.tagName == 'SELECT' && value * 1 == value){
						el.selectedIndex = value
					}
					else if(el.tagName == 'INPUT' && typeof value == 'string'){
						el.value = value
					}
				}
				
				if(el.tagName == 'INPUT' && el.type == 'radio'){
					if(!form) form = el.up('form')
					var onChange = function(){
						for(var i = 0; i < form[el.name].length; i++){
							if(form[el.name][i].checked){
								Settings.setSetting('value:'+el.name, form[el.name][i].value)
							}
						}
					}
					for(var i = 0; i < form[el.name].length; i++){
						Event.observe(form[el.name][i], 'click', onChange)
						Event.observe(form[el.name][i], '1site1:onchange', onChange)
						form[el.name][i].removeAttribute('keepValue')
					}
				}
				else{
					var onChange = function(){
						if(el.type == 'text') Settings.setSetting('value:'+el.name, el.value)
						else if(el.type == 'select-one') Settings.setSetting('value:'+el.name, el.selectedIndex)
						else if(el.type == 'checkbox') Settings.setSetting('value:'+el.name, el.checked ? 'true' : 'false')
					}
					if(el.tagName == 'INPUT' && el.type == 'checkbox'){
						el.observe('click', onChange)
						el.observe('1site1:onchange', onChange)
					}
					else{
						el.observe('change', onChange)
						el.observe('1site1:onchange', onChange)
					}
				}
				
				el.removeAttribute('keepValue')
			}
			
			// set id attributes form elements
			if($A(['INPUT', 'TEXTAREA', 'SELECT']).indexOf(el.tagName) > -1){
				Document.setupFormElement(el)
				if(el.tagName != 'INPUT' || el.type != 'hidden') el.setAttribute('focusable', 1)
			}
			
			if(el.tagName == 'FORM' && hasClassName(el, 'site1InterfaceForm')){
				if(!el.id) el.id = el.name
				$(el).observe('submit', function(e){Event.stop(e)})
			}
			
			if(el.tagName == 'IFRAME' && !el.id && el.name) el.id = el.name
			
			if(el.attributes.getNamedItem('scroller')) el.className = el.className ? el.className + ' scroller' : 'scroller'
			if(hasClassName(el, 'scroller')) _scrollers.push(el)
			
			if(el.getAttribute('section') && !el.getAttribute('initiated')){
				var name = el.getAttribute('section')
				el.id = 'section_' + name
				if(el.getAttribute('onLoad')){
					onLoadCollection.add('var name = "'+name+'";' + el.getAttribute('onLoad'))
				}
				el.setAttribute('initiated', 1)
			}
			
			if(hasClassName(el, 'htmlEditor')) _editors.push(el)
			
		})
		$A(_dradInterfaces).each(function(el){initDradInterface(el)})
		$A(_topics).each(function(el, index){Document.initTopic(el)})
		$A(_buttons).each(function(el, index){Buttons.init(el, index)})
		$A(_tabGroups).each(function(el, index){TabGroups.init(el, index)})
		$A(_groupHeadings).each(function(el, index){GroupHeadings.init(el, index)})
		$A(_calendars).each(function(el, index){Calendars.init(el, index)})
		$A(_lists).each(function(el, index){Lists.init(el, index)})
		$A(_trees).each(function(el, index){Trees.init(el, index)})
		$A(_scrollers).each(function(el){Scrollers.init(el)})
		$A(_editors).each(function(el){TinyMceManager.init(el)})
		
		window.setTimeout('onLoadCollection.run()', 5)
		
		if(parentElement == document){
			Event.observe(document.body, 'mouseup', Lists.menuClose)
			Event.observe(window.document.body, 'click', Trees.menuClose)
			Event.observe(document, 'keydown', function(e){
				//Document.trace('event.keyCode: '+e.keyCode)
				Document.keyDown(e)
				var stop = false
				if(e.keyCode == 27 && Document.onEsc){
					Document.onEsc(e)
					Event.stop(e)
					return
				}
				if(!e.ctrlKey || e.keyCode == 17) return
				if(e.keyCode == 83 && Document.onCtrlS){ Document.onCtrlS(e); stop = true}
				else if(e.keyCode == 87 && Document.onCtrlW){ Document.onCtrlW(e); stop = true}
				else if(e.keyCode == 78 && Document.onCtrlN){ Document.onCtrlN(e); stop = true}
				
				if(stop) Event.stop(e)
			})
			
			if($('sid') && $F('sid')) Document.sid = $F('sid')
			if(!Document.sid) Document.sid = Document.getRequestVar('sid')
			if(!Document.sid) Document.sid = Cookie.get('sid')
			
			Event.observe(document, '1site1:resize', function(e){
				Scrollers.resize(false)
				InlineDialogs.onResize()
				Lists.menuClose(e)
				Trees.menuClose(e)
			})
			
			Document.focus()
		}
		
		ErrorHandler.endJob()
		
	}
})

Event.observe(window, 'resize', function(){
	if(window.rezizeTimerId) clearTimeout(window.rezizeTimerId)
	else setTimeout(function(){Element.fire(document, '1site1:resize')}, 50)
})

Event.observe(document, '1site1:domloaded', function(){
	if(hasClassName(this.body, 'site1Interface')) this.init(this)
})

document.domLoadedEvent = (function(){
	if(!this.domLoadedEventDone){
		this.domLoadedEventDone = true
		Element.fire(document, '1site1:domloaded')
	}
}).bind(document)

Event.observe(document, 'dom:loaded', document.domLoadedEvent)
if(Prototype.Browser.IE) Event.observe(window, 'load', document.domLoadedEvent)

InlineDialogs = {
	stack: [],
	settings: {defaultWidth: 600, defaultHeight: 500, baseZIndex: 20},
	
	open: function(script, parameters, options){
		var doc = InlineDialogs.getTopDocument()
		var dialog = new doc.InlineDialog(script, parameters, options, Document).setLevel(doc.InlineDialogs.stack.length)
		doc.InlineDialogs.stack.push(dialog)
		doc.InlineDialogs.setTransScreen()
		
		dialog.load()
	},
	
	transScreen: null,
	setTransScreen: function(){
		if(InlineDialogs.stack.length < 1){
			InlineDialogs.transScreen.hide()
		}
		else{
			var zIndex = InlineDialogs.stack[InlineDialogs.stack.length-1].div.getStyle('zIndex') - 1
			var div = InlineDialogs.transScreen
			if(!div){
				var div = InlineDialogs.transScreen = new Element('div', {'class': 'dialogTransScreen'})

				Element.insert(document.body, {bottom: div})
				InlineDialogs.transScreen.setOpacity(0.2)
				div.observe('click', function(e){Event.stop(e)})
				div.observe('mouseup', function(e){Event.stop(e)})
				div.observe('mousedown', function(e){Event.stop(e)})
				div.observe('dblclick', function(e){Event.stop(e)})
			}
			div.setStyle({zIndex: zIndex})
			InlineDialogs.transScreen.show()
		}
	},
	getTopDocument: function(){
		try{
			if(parent.InlineDialogs != InlineDialogs) return parent.InlineDialogs.getTopDocument()
			else return self
		}
		catch(e){
			return self
		}
	},
	getDialog: function(id){
		for(var i = 0 ; i < InlineDialogs.stack.length; i++){
			if(InlineDialogs.stack[i].id == id || (id == 'auto' && InlineDialogs.stack[i].outsideScope)){
				return InlineDialogs.stack[i]
			}
		}
		return InlineDialogs.stack[0]
	},
	onResize: function(){
		for(var i = 0 ; i < InlineDialogs.stack.length; i++){
			InlineDialogs.stack[i].setDimensions()
		}
	}
}

var InlineDialog = Class.create({
	returnScript: '',
	
	initialize: function(script, parameters, options, callerDocument){
		this.options = options
		this.id = Date.parse(new Date()).toString() + r()
		this.title = Document.decimalEncodeHtml((options.title || 'dialog window')).gsub('<', '&lt;').gsub('>', '&gt;')
		this.fade = options.fade
		this.script = script
		this.parameters = parameters
		this.fullScreen = this.options.fullScreen
		this.width = options.width
		this.height = options.height
		this.left = parseInt(options.left)
		this.top = parseInt(options.top)
		
		this.callerDocument = callerDocument
		
		this.div = new Element('div', {'class': this.fullScreen ? 'fullScreenDialog' : 'dialog', _1site1Dialog: 1})
		if(this.fade) this.div.setOpacity(.6)
		
		Element.insert(document.body, {bottom: this.div})
		
		var html = '<table class=table cellspacing=0 cellpadding=0 border=0><tr><td class=lt></td><td class=t><div class=titleCell></div><div class=buttonsCell><img src='+grS()+'/graphics/shim.gif button=resize><img src='+grS()+'/graphics/shim.gif button=fullScreen><img src='+grS()+'/graphics/shim.gif button=close></div></td><td class=rt></td></tr><tr><td class=l></td><td class=bodyCell></td><td class=r></td></tr><tr><td class=lb></td><td class=b></td><td class=rb></td></tr></table>';
		
		this.div.update(html)
		this.table = this.div.down('table')
		
		this.dragBar = this.div.down('td.t')
		var drag = (function(e){if(!this.fullScreen) this.drag(e)}).bind(this)
		this.dragBar.observe('mousedown', drag)
		
		this.table.select('td.rt', 'td.r', 'td.rb', 'td.b', 'td.lb', 'td.l', 'td.lt').each(function(el){
			el.observe('mousedown', drag)
		})
		
		this.titleCell = this.dragBar.down('.titleCell').update('loading '+this.title+'...')
		
		var toggleFullScreen = (function(e){
			Event.stop(e)
			if(this.fullScreen) this.fullScreen = false
			else this.fullScreen = true
			this.setDimensions()
		}).bind(this)
		
		this.dragBar.observe('dblclick', toggleFullScreen)
		this.titleCell.observe('dblclick', toggleFullScreen)
		
		this.buttonsCell = this.dragBar.down('.buttonsCell')
		this.buttonsCell.select('img').each(function(el){el.className = el.getAttribute('button')+'Button'})
		this.buttonsCell.observe('mouseover', function(e){
			var el = Event.findElement(e, 'img')
			if(el) el.addClassName(el.getAttribute('button')+'ButtonHover')
		})
		this.buttonsCell.observe('mouseout', function(e){
			var el = Event.findElement(e, 'img')
			if(el) el.removeClassName(el.getAttribute('button')+'ButtonHover')
		})
		this.buttonsCell.observe('mousedown', function(e){Event.stop(e)})
		this.buttonsCell.observe('click', (function(e){
			var el = Event.findElement(e, 'img')
			if(el){
				var button = el.getAttribute('button')
				if(button == 'close') this.close()
				else if(button == 'fullScreen'){
					this.fullScreen = true
					this.setDimensions()
				}
				else if(button == 'resize'){
					this.fullScreen = false
					this.setDimensions()
				}
			}
		}).bind(this))
		
		this.bodyCell = this.div.down('.bodyCell')
		
		// placing
		var viewport = document.getViewport()
		
		if(this.fullScreen){
			if(!this.width) this.width = '80%'
			if(!this.height) this.height = '80%'
		}
		else{
			if(!this.width) this.width = InlineDialogs.settings.defaultWidth
			if(!this.height) this.height = InlineDialogs.settings.defaultHeight
		}
		
		if(this.width.toString().indexOf('%') >= 0) this.width = viewport.width * parseInt(this.width) / 100
		else this.width = parseInt(this.width) + 30
		if(this.height.toString().indexOf('%') >= 0) this.height = viewport.height * parseInt(this.height) / 100
		else this.height = parseInt(this.height) + 40
		
		if(this.width < 200) this.width = 200
		if(this.height < 100) this.height = 100
		if(this.width > viewport.width - 10) this.width = viewport.width - 10
		if(this.height > viewport.height - 10) this.height = viewport.height - 10
		
		if(!this.left) this.left = viewport.width / 2 - this.width / 2
		if(!this.top) this.top = viewport.height / 2 - this.height / 2
		
		this.setDimensions()
		
		return this
	},
	
	setDimensions: function(){
		var viewport = document.getViewport()
		
		if(this.fullScreen){
			if(this.iframe) this.iframe.setStyle({height: '100%'})
			this.div.className = 'fullScreenDialog'
			
			var width = viewport.width
			var height = viewport.height
			this.div.setStyle({width: width+'px', height: height+'px', left: 0, top: 0})
		}
		else{
			if(this.iframe) this.iframe.setStyle({height: '100%'})
			this.div.className = 'dialog'
			
			if(this.width > viewport.width - 10) this.width = viewport.width - 10
			if(this.height > viewport.height - 10) this.height = viewport.height - 10
			
			if(this.left < this.width * -1 + 120) this.left = this.width * -1 + 120
			if(this.top < 0) this.top = 0
			if(this.left > viewport.width - 70) this.left = viewport.width - 70
			if(this.top > viewport.height - 30) this.top = viewport.height - 30
			
			this.div.setStyle({width: this.width+'px', height: this.height+'px', left: this.left+'px', top: this.top+'px'})
			
			if(this.iframe){
				var iframeHeight = this.bodyCell.getHeight()
				if(iframeHeight) this.iframe.setStyle({height: iframeHeight+'px'})
				else setTimeout((function(){
					var iframeHeight = this.bodyCell.getHeight()
					if(iframeHeight) this.iframe.setStyle({height: iframeHeight+'px'})
				}).bind(this), 200)
			}
		}
	},
	
	show: function(){
		this.div.show()
		return this
	},
	hide: function(){
		this.div.hide()
		return this
	},
	
	setLevel: function(level){
		this.level = level
		this.div.setStyle({zIndex: InlineDialogs.settings['baseZIndex'] + this.level * 2 + 1})
		return this
	},
	
	load: function(){
		this.onClose = this.options['onClose']
		this.dialogVars = this.options['dialogVars']
		this.returnScript = (this.options['returnScript'] || InlineDialogs.returnScript)
		
		var base = this.script.replace(/(^[htpsfile]+:\/\/[\w\.-]+(\:\d+)?\/)?.*/, '$1')
		
		var outsideScope = (base && document.location.href.indexOf(base) != 0)
		
		if(outsideScope){
			if(this.returnScript){
				if(!this.returnScript.match(/^https?\:/)){
					this.returnScript = document.location.protocol + '//' + document.location.hostname + (document.location.port && document.location.port != 80 ? ':'+document.location.port : '') + '/' + this.returnScript.replace(/^\//, '')
				}
				this.parameters.push('dialog-return-script='+escape(this.returnScript))
			}
			if(this.options.dialogVars.arguments){
				var json = JSON.encode(this.options.dialogVars.arguments)
				if(json) this.parameters.push('dialog-arguments='+escape(json))
			}
			if(InlineDialogs.getDialog('auto')) this.parameters.push('dialog-id='+this.id)
			else this.parameters.push('dialog-id=auto')
		}
		else this.parameters.push('dialog-id='+this.id)
		
		this.outsideScope = outsideScope
		
		var url = this.script + '?' + this.parameters.join('&')
		this.titleCell.setAttribute('title', url)
		
		this.iframe = new Element('iframe', {frameborder: 0, dialogLevel: this.level, src: url}).addClassName('fr')
		this.bodyCell.insert({top: this.iframe})
		
		this.iframe.setStyle({height: this.bodyCell.getHeight()+'px'})
		
		if(this.fade){
			this.faderId = setInterval((function(){
				var opacity = this.div.getOpacity()
				if(opacity >= 1) clearInterval(this.faderId)
				else this.div.setOpacity(opacity + .1)
			}).bind(this), 200)
		}
		
		//iframe.src = url
		this.iframe.observe('load', (function(e){
			this.table.setOpacity(1)
			// document title
			try{
				this.iframeDoc = (this.iframe.contentDocument || this.iframe.contentWindow.document)
				this.titleCell.update(this.iframeDoc.getElementsByTagName('TITLE')[0].innerHTML)
			}
			catch(e){
				this.titleCell.update(this.title)
			}
			
			// document icon
			if(0 && this.iframeDoc && !Prototype.Browser.IE){
				try{
					var icon = ''
					$A(this.iframeDoc.getElementsByTagName('LINK')).each(function(el){
						if(el.getAttribute('rel') && el.getAttribute('rel').toLowerCase() == 'shortcut icon'){
							icon = el.getAttribute('href')
						}
					})
					if(icon) this.titleCell.setStyle({backgroundImage: 'url('+icon+')', paddingLeft: '22px'})
				}
				catch(e){}
			}
		}).bind(this))
		return this
	},
	
	returnValue: null,
	close: function(){
		
		if(this.fade){
			this.faderId = setInterval((function(){
				var opacity = this.table.getOpacity()
				if(opacity <= 0){
					clearInterval(this.faderId)
					this.remove()
				}
				else this.table.setOpacity(opacity - .3)
			}).bind(this), 200)
		}
		else this.remove()
		
		if(this.callerDocument){
			try{this.callerDocument.focus()}
			catch(e){}
		}
		
	},
	
	remove: function(){
		this.div.hide()
		var div = this.div
		var remove = function(){
			try{
				div.descendants().invoke('stopObserving')
				div.descendants().reverse().each(function(el){el.remove()})
				div.stopObserving()
				Element.remove(div)
			}
			catch(e){}
		}
		setTimeout(function(){
			remove()
		}, 500)
		
		InlineDialogs.stack = $A(InlineDialogs.stack).without(this)
		InlineDialogs.setTransScreen()
		
		if(this.onClose) this.onClose(this.returnValue)
	},
	
	drag: function(e){
		Event.stop(e)
		
		this.dragging = false
		
		if(this.fullScreen) return false
		
		if(this.dragPrepared) return
		this.dragPrepared = true
		
		this.dragStartX = Event.pointerX(e), this.dragStartY = Event.pointerY(e)
		
		var srcEl = Event.findElement(e, 'td')
		var cursor = srcEl ? srcEl.getStyle('cursor') : null
		if(cursor == 'move' || !cursor) this.dir = 'move'
		else if(cursor.indexOf('-resize') > 0) this.dir = cursor.replace(/(\w+)\-resize/, '$1')
		else this.dir = 'move'
		
		// iframe cover lets mouse movement be picked up over iframe
		if(!this.iframeCover){
			this.iframeCover = new Element('div').setStyle({position: 'absolute', zIndex: this.div.getStyle('z-index') + 1})
			$(document.body).insert({bottom: this.iframeCover})
		}
		else this.iframeCover.show()
		
		var iframePos = this.iframe.cumulativeOffset()
		var iframeDim = this.iframe.getDimensions()
		this.iframeCover.setStyle({left: iframePos.left+'px', top: iframePos.top+'px', width: iframeDim.width+'px', height: iframeDim.height+'px'})
		
		Event.observe(document, 'mousemove', this.dragOnMouseMove.bind(this))
		Event.observe(this.dragBar, 'mouseup', this.dragStop.bind(this))
		Event.observe(this.dragBar, 'dblclick', this.dragStop.bind(this))
	},
	
	dragInit: function(e){
		InlineDialogs.transScreen.setOpacity(0)
		
		if(!this.dragger){
			this.dragger = new Element('div').setStyle({border: '1px solid #000', position: 'absolute', overflow: 'hidden', zIndex: this.div.getStyle('z-index') + 2}).setOpacity(0.3)
			$(document.body).insert({bottom: this.dragger})
		}
		else this.dragger.show()
		
		this.dragger.setStyle({cursor: this.dir == 'move' ? 'move' : this.dir+'-resize', backgroundColor: InlineDialogs.transScreen.getStyle('background-color')})
		InlineDialogs.transScreen.setStyle({cursor: this.dir == 'move' ? 'move' : this.dir+'-resize'})
		
		var dim = this.draggerDimensions = this.div.getDimensions()
		
		var x = Event.pointerX(e), y = Event.pointerY(e)
		var pos = this.dragStartPos = this.div.positionedOffset()
		
		this.dragger.setStyle({width: dim.width+'px', height: dim.height+'px', left: pos.left+'px', top: pos.top+'px'})
		
		this.div.hide()
		if(this.iframeCover) this.iframeCover.hide()
		
		this.dragging = true
		
		Event.stopObserving(this.dragBar, 'mouseup', this.dragStop.bind(this))
		Event.observe(document, 'mouseup', this.dragStop.bind(this))
		Event.observe(InlineDialogs.transScreen, 'mouseup', this.dragStop.bind(this))
		
		this.viewport = document.getViewport()

	},
	
	dragOnMouseMove: function(e){
		if(!this.dragPrepared) return 
		if(this.fullScreen) return false
		
		var x = Event.pointerX(e), y = Event.pointerY(e)
		
		if(!this.dragging){
			var moveX = x - this.dragStartX, moveY = y - this.dragStartY
			if(moveX > -2 && moveX < 2 && moveY > -2 && moveY < 2) return
		}
		
		if(!this.dragging) this.dragInit(e)
		
		if(this.dir == 'move'){
			var left = this.dragStartPos.left + (x - this.dragStartX)
			var top = this.dragStartPos.top + (y - this.dragStartY)
			if(top < 0) top = 0
			if(left < this.draggerDimensions.width * -1 + 120) left = this.draggerDimensions.width * -1 + 120
			if(top > this.viewport.height - 30) top = this.viewport.height - 30
			if(left > this.viewport.width - 70) left = this.viewport.width - 70
			
			this.dragger.setStyle({left: left+'px', top: top+'px'})
		}
		else{
			var width, height, left, top
			if(['e', 'se', 'ne'].indexOf(this.dir) >= 0){
				width = this.draggerDimensions.width + (x - this.dragStartX)
				if(width < 100) width = 100
				if(width + this.dragStartPos.left > this.viewport.width){
					width = this.viewport.width - this.dragStartPos.left
				}
			}
			if(['s', 'se', 'sw'].indexOf(this.dir) >= 0){
				height = this.draggerDimensions.height + (y - this.dragStartY)
				if(height < 100) height = 100
				if(height + this.dragStartPos.top > this.viewport.height){
					height = this.viewport.height - this.dragStartPos.top
				}
			}
			if(['w', 'nw', 'sw'].indexOf(this.dir) >= 0){
				left = this.dragStartPos.left + (x - this.dragStartX)
				width = this.draggerDimensions.width - (x - this.dragStartX)
				if(left < 0){
					width = this.draggerDimensions.width - (x - this.dragStartX) + left
					left = 0
				}
			}
			if(['nw', 'ne'].indexOf(this.dir) >= 0){
				top = this.dragStartPos.top + (y - this.dragStartY)
				height = this.draggerDimensions.height - (y - this.dragStartY)
				if(top < 0){
					height = this.draggerDimensions.height - (y - this.dragStartY) + top
					top = 0
				}
			}
			
			if(this.dir == 'ne') this.dragger.setStyle({width: width+'px', top: top+'px', height: height+'px'})
			else if(this.dir == 'e') this.dragger.setStyle({width: width+'px'})
			else if(this.dir == 'se') this.dragger.setStyle({width: width+'px', height: height+'px'})
			else if(this.dir == 's') this.dragger.setStyle({height: height+'px'})
			else if(this.dir == 'sw') this.dragger.setStyle({width: width+'px', left: left+'px', height: height+'px'})
			else if(this.dir == 'w') this.dragger.setStyle({left: left+'px', width: width+'px'})
			else if(this.dir == 'nw') this.dragger.setStyle({left: left+'px', width: width+'px', height: height+'px', top: top+'px'})
			
		}
	},
	
	dragStop: function(){
		Event.stopObserving(document, 'mousemove', this.dragOnMouseMove.bind(this))
		Event.stopObserving(document, 'mouseup', this.dragStop.bind(this))
		Event.stopObserving(InlineDialogs.transScreen, 'mouseup', this.dragStop.bind(this))
		
		this.dragging = this.dragPrepared = false
		
		if(this.dragger){
			if(!this.fullScreen){
				this.left = parseInt(this.dragger.getStyle('left'))
				this.top = parseInt(this.dragger.getStyle('top'))
				this.width = parseInt(this.dragger.getStyle('width'))
				this.height = parseInt(this.dragger.getStyle('height'))
				
				this.setDimensions()
				this.div.show()
			}
			this.dragger.hide()
		}
		
		if(this.iframeCover) this.iframeCover.hide()
		
		InlineDialogs.transScreen.setOpacity(0.2)
		InlineDialogs.transScreen.setStyle({cursor: 'not-allowed'})
	}
})

TinyMceManager = {
	textareas: [],
	editors: {},
	defaultBaseHref: '',
	
	init: function(el){
		el = $(el)
		el.up().addClassName('headingColor')
		
		var wrapper1 = new Element('div').addClassName('headingColor height100 width100')
		var wrapper2 = new Element('div').addClassName('height100').setStyle({visibility: 'hidden'})
		Element.wrap(el, wrapper1)
		Element.wrap(wrapper1, wrapper2)
		
		TinyMceManager.textareas.push(el)
		// get default gaseHref
		if(!el.getAttribute('baseHref')) el.setAttribute('baseHref', TinyMceManager.defaultBaseHref)
		
		
		onLoadCollection.add((function(){
			var baseHref = (el.getAttribute('baseHref') ? el.getAttribute('baseHref') + '/' : '')
			var styleSheets = $A((el.getAttribute('styleSheets') || '').split(','))
			$A(styleSheets).each(function(styleSheet, i){
				if(!styleSheet.match(/^https?\:/)) styleSheets[i] = baseHref+styleSheet.replace(/^\//, '')
			})
			styleSheets = styleSheets.join(',')
			
			var userStyles = $A((el.getAttribute('userStyles') || 'no styles available=-').split(';'))
			var styleFormats = []
			userStyles.each(function(s){
				var style = s.split('=')
				styleFormats.push({title: style[0], block: 'div', classes: style[1]})
			})
			styleFormats.push({title: 'selected text only'})
			userStyles.each(function(s){
				var style = s.split('=')
				styleFormats.push({title: style[0], inline: 'span', classes: style[1]})
			})
			
			var cont = el.value
			el.value = (cont || '<div><br mce_bogus="1" /></div>')
			
			var plugins, theme_advanced_buttons1, theme_advanced_buttons2, theme_advanced_buttons3
			
			var textOnly = el.hasClassName('htmlEditorTextOnly')
			
			if(textOnly){
				plugins = "contextmenu,paste,table,advhr,searchreplace,visualchars,nonbreaking,inlinepopups,linkautodetect"
				theme_advanced_buttons1 = "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,formatselect,fontselect,fontsizeselect"
				theme_advanced_buttons2 = "undo,redo,|,cut,copy,pastetext,pasteword,|,search,replace,|,bullist,numlist,outdent,indent,|,charmap,|,link,|,forecolor,backcolor,|,hr,|,image"
				theme_advanced_buttons3 = ""
				
			}
			else{
				plugins = "onesiteone,style,paste,table,advhr,searchreplace,visualchars,nonbreaking,inlinepopups,linkautodetect"
				theme_advanced_buttons1 = "bold,italic,underline,strikethrough,|,formatselect,styleselect,fontselect,fontsizeselect,|,removeformat"
				theme_advanced_buttons2 = "undo,redo,|,cut,copy,pastetext,pasteword,|,search,replace,|,bullist,numlist,outdent,indent,|,charmap,|,link,image,|,forecolor,backcolor"
				theme_advanced_buttons3 = "justifyleft,justifycenter,justifyright,justifyfull,|,anchor,|,table,row_props,cell_props,|,hr,|,jwplayer,youtube,googlevideo,media,|,cleanup,visualaid,code,|,help"
			}
			tinyMCE.init({
				mode: "exact",
				elements: el.id,
				editor_width: el.getAttribute('width'),
				add_form_submit_trigger: false,
				add_unload_trigger: false,
				document_base_url: baseHref,
				theme: "advanced",
				
				plugins: plugins,
				content_css: styleSheets,
				style_formats: styleFormats,
				forced_root_block: 'div',
				
				// Theme options
				theme_advanced_buttons1: theme_advanced_buttons1,
				theme_advanced_buttons2: theme_advanced_buttons2,
				theme_advanced_buttons3: theme_advanced_buttons3,
				
				//theme_advanced_styles: (el.getAttribute('userStyles') || 'no styles available=-'),
				theme_advanced_blockformats: 'div,p,address,pre,h1,h2,h3,h4,h5,h6',
				theme_advanced_toolbar_location: "top",
				theme_advanced_toolbar_align: "left",
				theme_advanced_statusbar_location: (textOnly ? 'none' : 'bottom'),
				theme_advanced_resizing: false,
				
				table_default_border: 1,
				table_default_cellpadding: 4,
				table_default_cellspacing: 0,
				table_default_width: '99%',
				
				//paste_remove_styles: true,
				paste_text_sticky: true,
				
				//cleanup: true,
				init_instance_callback: function(ed){
					// set editor dimensions
					var width = ed.getParam('editor_width', 500) * 1
					if(width < 1) width = 500
					
					var iframeContainer = $(ed.getContentAreaContainer())
					var iframe = iframeContainer.down('iframe').setStyle({width: width+'px', height: '100%'})
					var mceContainer = $(ed.getContainer()).setStyle({display: 'block', height: '100%'})
					
					var mceTable = mceContainer.down('table.mceLayout').setStyle({height: '100%', width: ''})
					mceTable.down('tr').next('tr').down('td').setStyle({height: '100%'})
					
					if(!textOnly) mceTable.down('td.mceStatusbar').setStyle({borderWidth: '0'})
					
					// set editor body style
					var bod = $(ed.getDoc().body)
					var style = {}
					$A(($(ed.id).getAttribute('bodyStyle') || '').replace(/[\n\t ]/g, '').split(';')).each(function(st){
						st = st.split(/:/)
						var key = st[0].toLowerCase().camelize()
						if(key && key != 'width') style[key] = st[1]
					})
					
					style.padding = style.paddingBottom = style.paddingTop = 0
					style.paddingRight = style.paddingLeft = '5px'
					style.margin = style.marginTop = style.marginRight = style.marginBottom = style.marginLeft = 0
					style.overflow = style.overflowX = style.overflowY = 'auto'
					
					$H(style).each(function(st){
						var style = {}; style[st[0]] = st[1]
						try{Element.setStyle(bod, style)} catch(e){}
					})
					
					wrapper2.setStyle({visibility: 'visible'})
					
					TinyMceManager.editors[ed.id] = ed
					// set content as default
					el.value = el.defaultValue = ed.getContent().gsub(ed.getParam('document_base_url', ''), '')
					
				}
			})
			
		}))
	},
	
	save: function(){
		$A(TinyMceManager.textareas).each((function(textarea){
			var ed = TinyMceManager.editors[textarea.id]
			if(!ed) return
			
			var html = ed.getContent().gsub(ed.getParam('document_base_url', ''), '')
			
			if(html == '&nbsp;' || html == '<div><br mce_bogus="1" /></div>') html = ''
			textarea.value = html
			
		}).bind(this))
	}
}

/*--------------------------------------------------------------------------*/
// window.yesNoCancel; window.yes; window.die; window.r
Object.extend(window, {
	yesNoCancel: function(str){
		return(Try.these(
			function(){
				execScript('ret = msgbox("'+str.replace(/[\n\r]/g, '\\n')+'",vbYesNoCancel)', "VBScript")
				if(ret == 6) return 1
				else if(ret == 7) return -1
				else return 0
			},
			function(){
				var ret = confirm(str)
				if(ret) return 1
				else return -1
			}
		))
	},
	yes: function(str){
		return(Try.these(
			function(){
				execScript('ret = msgbox("'+str.replace(/[\n\r]/g, '\\n')+'",vbYesNo)', "VBScript")
				return (ret == 6)
			},
			function(){
				return confirm(str)
			}
		))
	},
	die: function(msg){
		alert(msg)
		noValue.noAttribute = 1
	},
	r: function(){
		return Math.round(Math.random()*100000)
	},
	isFocusable: function(el){
		el = $(el)
		
		return (el && isVisible(el) && ((el.tagName == 'INPUT' && el.type != 'hidden') || el.tagName == 'TEXTAREA' || el.tagName == 'SELECT'))
	},
	isVisible: function(el){
		el = $(el)
		
		var visible = true
		var display
		var tmpEl = el
		while(tmpEl && visible){
			display = tmpEl && tmpEl.getStyle ? tmpEl.getStyle('display') : ''
			visible = display == 'none' ? false : true
			tmpEl = $(tmpEl.parentNode)
		}
		return visible
	}
})

/*--------------------------------------------------------------------------*/
// Form.Element.isDefault; Form.Element.setAsDefault; Form.Element.disable; Form.Element.enable
Object.extend(Form.Element, {
	isDefault: function(element){
		el = $(element)
		if(el.type == 'select-one' || el.type == 'select-multiple'){
			for(ii = 0; ii < el.options.length; ii++){
				if(el.options[ii].selected != el.options[ii].defaultSelected) return false
			}
		}// select one/multiple	
		if(el.type == 'checkbox' && el.checked != el.defaultChecked) return false
		if(el.type != 'radio' && el.type != 'select-one' && el.type != 'select-multiple' && el.value != el.defaultValue) return false
		if(el.type == 'radio' && el.checked != el.defaultChecked) return false
		return true
	},
	setAsDefault: function(element){
		el = $(element)
		if(el.type == 'select-one' || el.type == 'select-multiple'){
			for(i = 0; i < el.options.length; i++){
				el.options[i].defaultSelected = el.options[i].selected
			}
		}// select one/multiple	
		if(el.type == 'checkbox') el.defaultChecked = el.checked
		if(el.type != 'radio' && el.type != 'select-one' && el.type != 'select-multiple') el.defaultValue = el.value
		if(el.type == 'radio') el.defaultChecked = el.checked
	},
	disable: function(){
		var el = null
		for(i = 0; i < arguments.length; i++){
			el = $(arguments[i])
			if(el) el.disabled = true
		}
	},
	enable: function(){
		var el = null
		for(i = 0; i < arguments.length; i++){
			el = $(arguments[i])
			if(el) el.disabled = false
		}
	}
})
Object.extend(Form, {
	setAsDefault: function(form){
		Form.getElements(form).each(function(element){
			Form.Element.setAsDefault(element)
		})
	},
	isDefault: function(form){
		isDefault = true
		Form.getElements(form).each(function(element){
			if(!Form.Element.isDefault(element)) isDefault = false
		})
		return isDefault
	}
})

function clearSelection(){
	var sel
	if(document.selection && document.selection.empty){
		document.selection.empty()
	}
	else if(window.getSelection){
		sel = window.getSelection()
		if(sel && sel.removeAllRanges) sel.removeAllRanges()
	}
}

/*--------------------------------------------------------------------------*/
var myGlobalAjaxHandlers = {
	onComplete: function(){
		if(Ajax.activeRequestCount < 1){
			Document.hideContactIndicator()
			Document.hideIndicator()
		}
	},
	
	onFailure: function(){
		alert('Ajax error...')
	}
}
Ajax.Responders.register(myGlobalAjaxHandlers)

function isDigit(e){
	e = e || event
	var iCode = (e.keyCode || e.charCode)
	return (( iCode >= 48 && iCode <= 57 )		// Numbers
			|| (iCode >= 37 && iCode <= 40)		// Arrows
			|| iCode == 8		// Backspace
			|| iCode == 46		// Delete
		)
}

function encodeURIComponent(str){
	return escape(str).replace(/\+/g, '%2B')
}

function decodeURIComponent(str){
	return unescape(str.replace(/\+/, ' '))
}

onLoadCollection = {
	scripts: [],
	
	add: function(script){
		this.scripts[this.scripts.length] = script
	},
	run: function(){
		var script
		while(onLoadCollection.scripts.length){
			script = onLoadCollection.scripts.shift()
			try{
				if(typeof(script) == 'string') eval(script)
				else script()
			}
			catch(e){
				//ErrorHandler.throwError(e, script.toString())
			}
		}
	}
}

/*--------------------------------------------------------------------------*/
Trees = {
	all: {},
	get: function(treeName){return Trees.all[treeName]},
	
	init: function(div){
		if(div.getAttribute('initiated')) return false
		
		var name = div.getAttribute('tree')
		div.id = 'tree_'+name
		div.setAttribute('treeName', name)
		div.setAttribute('listId', 0)
		
		Event.observe(div, 'mousedown', Trees.onMouseDown)
		Event.observe(div, 'dblclick', Trees.onMouseDown)
		Event.observe(div, 'click', Trees.onClick)
		Event.observe(div, 'dblclick', Trees.onDblClick)
		
		Trees.all[name] = new Tree(name)
		
		if(div.getAttribute('onLoad')){
			var func = function(){
				var Tree = Trees.all[name]
				try{eval(div.getAttribute('onLoad'))}
				catch(e){ErrorHandler.throwError(e, div.getAttribute('onLoad'))}
			}
			onLoadCollection.add(func.bind(Trees.all[name]))
		}
		div.setAttribute('initiated', 1)
	},
	
	load: function(name, script, parameters){
		if(!Trees.all[name]) return false
		return Trees.all[name].load(script, parameters)
	},
	refresh: function(name){
		return Trees.all[name].refresh()
	},
	reload: function(name, script, parameters){
		if(!Trees.all[name]) return false
		return Trees.all[name].reload(script, parameters)
	},
	getAttribute: function(treeName, id, name){
		if(!id) id = Trees.all[treeName].selected.first()
		if(!id) return null
		return Trees.all[treeName].items[id].getAttribute(name)
	},
	getSelection: function(name){
		return Trees.all[name].selected
	},
	getItem: function(treeName, id){
		if(!Trees.all[treeName]) return null
		if(!id) id = Trees.all[treeName].selected.first()
		return Trees.all[treeName].getItem(id)
	},
	onMouseDown: function(e){
		Event.stop(e)
		var el = Event.element(e)
		var Item = Trees.getItemFromEvent(el)
		
		if(Item && (Item.selectOnToggle || !el.getAttribute('toggler'))){
			Trees.all[Item.treeName].onMouseDown(e, Item)
		}
	},
	onClick: function(e){
		var el = Event.element(e)
		var Item = Trees.getItemFromEvent(el)
		if(Item && (el.getAttribute('toggler') || Item.toggleOnClick)){
			Trees.all[Item.treeName].toggleList(Item.id)
		}
		else if(Item && Item.onClick){
			var func = function(){
				var Tree = Trees.all[Item.treeName]
				try{eval(Item.onClick)}
				catch(e){ErrorHandler.throwError(e, Item.onClick)}
			}
			func.apply(this)
		}
	},
	onDblClick: function(e){
		var el = Event.element(e)
		var Item = Trees.getItemFromEvent(el)
		if(!Item) return false
		if(el.getAttribute('toggler')) Trees.all[Item.treeName].toggleList(Item.id)
		else Trees.all[Item.treeName].onDblClick(Item)
	},
	getItemFromEvent: function(el){
		var treeName, listId, id
		treeName = listId = id = null
		var tmpEl = el
		while(tmpEl && tmpEl.getAttribute && (!treeName || listId == null || !id)){
			if(!treeName && tmpEl.getAttribute('treeName')) treeName = tmpEl.getAttribute('treeName')
			if(listId == null && tmpEl.attributes.getNamedItem('listId')){
				listId = tmpEl.getAttribute('listId')
			}
			if(!id && tmpEl.getAttribute('treeItemId')) id = tmpEl.getAttribute('treeItemId')
			tmpEl = tmpEl.parentNode
		}
		if(!treeName || !id || listId === null) return null
		return Trees.all[treeName].items[id]
	},
	
	menuOpen: function(e){
		Event.stop(e)
		var Item = Trees.getItemFromEvent(Event.element(e))
		if(!Item) return false
		var treeName = Item.treeName
		var tree = Trees.get(Item.treeName)
		var menu = tree.menu
		if(!menu) return false
		
		var x = Event.pointerX(e)
		var y = Event.pointerY(e)
		
		menu.setStyle({left: (x + document.body.scrollLeft + 2)+'px', top: y+'px', position: 'absolute', display: ''})
		
		if(menu.getAttribute('onOpen')){
			var func = (function(e, selection, name, tree, menu){
				eval(menu.getAttribute('onOpen'))
			}).bind(Trees.all[treeName])
			
			try{func(e, Trees.get(treeName).selected, treeName, Trees.get(treeName), menu)}
			catch(e){ErrorHandler.throwError(e, menu.getAttribute('onOpen'))}
		}
		
		var viewport = document.getViewport()
		
		if(menu.offsetTop + menu.getHeight() > viewport.height){
			menu.setStyle({top: (y + document.body.scrollTop - menu.getHeight()) + 'px'})
		}
		if(menu.offsetLeft + menu.getWidth() > viewport.width){
			menu.setStyle({left: (x + document.body.scrollLeft - menu.getWidth() - 2) + 'px'})
		}
		
	},
	menuClose: function(){
		$H(Trees.all).each(function(tree){
			if(tree[1].menu) tree[1].menu.hide()
		})
	},
	menuItemDown: function(e){
		Event.stop(e)
		var tr = Event.findElement(e, 'tr')
		var action = tr.getAttribute('action') || tr.down('td[action]').getAttribute('action')
		
		if(!action){
			Trees.menuClose()
			return
		}
		
		var menu = Event.findElement(e, 'table')
		var treeName = menu.getAttribute('treeName')
		Trees.menuClose()
		var code = 'var selection = Trees.all["'+treeName+'"].selected;\n'
			+ 'var name = "'+treeName+'";\n'
			+ 'var tree = Trees.all["'+treeName+'"];\n'
			+ 'var menu = $("treeMenu_'+treeName+'");\n'
			+ action
		try{eval(code)}
		catch(e){ErrorHandler.throwError(e, code)}
	}
	
}

var Tree = Class.create({
	items: {},
	lists: {},
	attr: {},
	
	initialize: function(name){
		this.treeName = name
		this.div = $('tree_'+name)
		var div = this.div
		this.prevClicked = 0
		this.selectOne = this.div.attributes.getNamedItem('selectOne') ? true : false
		this.settingScope = this.div.getAttribute('settingScope')
		this.saveSelection = this.div.getAttribute('noMemory') ? false : true
		
		if(this.div.attributes.getNamedItem('openedLists')){
			var openedLists = this.div.getAttribute('openedLists')
			this.openedLists = openedLists ? (openedLists.indexOf(',') < 0 ? [openedLists] : openedLists.split(/\s*\,\s*/)) : []
			if(this.saveSelection) Settings.setSetting('tree:'+this.treeName+':opened', this.openedLists, this.settingScope)
		}
		else{
			var openedLists = this.saveSelection ? Settings.getSetting('tree:'+this.treeName+':opened', this.settingScope) : null
			this.openedLists = openedLists && openedLists.toJSON ? openedLists : []
			
			if(this.div.getAttribute('openLists')){
				var openedLists = this.div.getAttribute('openLists')
				openedLists = openedLists.indexOf(',') >= 0 ? openedLists.split(/\s*\,\s*/) : [openedLists]
				for(var i=0; i<openedLists.length; i++){
					var listId = openedLists[i]
					if(this.openedLists.indexOf(listId) < 0) this.openedLists.push(listId)
				}
			}
		}
		
		if(this.div.attributes.getNamedItem('selected')){
			this.selected = this.div.getAttribute('selected')
			this.selected = this.selected ? (this.selected.indexOf(',') < 0 ? [this.selected] : this.selected.split(/\s*\,\s*/)) : []
			if(this.saveSelection) Settings.setSetting('tree:'+this.treeName+':selected', this.selected, this.settingScope)
		}
		else{
			var selected = this.saveSelection ? Settings.getSetting('tree:'+this.treeName+':selected', this.settingScope) : null
			this.selected = selected && selected.toJSON ? selected : []
		}
		
		var menu = this.menu = $$(['table[treeContextMenu="'+name+'"]']).first()
		if(menu){
			menu.setAttribute('treeName', this.treeName)
			menu.hide()
			
			$A(menu.select('tr')).each(function(row){
				try{
					if(row.select('td').length > 1){
						row.down('td').addClassName('iconCell')
						row.down('td', 1).addClassName('textCell')
					}
				}
				catch(e){}
				
				Event.observe(row, 'mouseover', function(e){row.addClassName('over')})
				Event.observe(row, 'mouseout', function(e){row.removeClassName('over')})
				Event.observe(row, 'mousedown', Trees.menuItemDown)
			})

			Event.observe(this.div, 'contextmenu', Trees.menuOpen)
		}
		
		new Insertion.Before(this.div, '<div id="tree_'+this.treeName+'_selector" class=displayNone></div>')
		
		var lists = []
		
		this.div.observe('my:keydown', (function(e){
			if(this.selected.length != 1) return
			var Item = this.getItem(this.selected[0])
			var gotoItem = null
			
			var keyCode = e.memo.keyCode
			//Document.trace('code: '+keyCode)
			
			if(keyCode == 40) gotoItem = Item.next()
			else if(keyCode == 38) gotoItem = Item.previous()
			else if(keyCode == 39){
				gotoItem = Item.next()
				if(!gotoItem || gotoItem.listId != Item.id){
					gotoItem = null
					if(Item.fertile) Item.openList()
				}
			}
			else if(keyCode == 37){
				if(Item.fertile && Item.open) Item.closeList()
				else if(Item.listId) gotoItem = this.getItem(Item.listId)
			}
			else if(keyCode == 13) this.onDblClick(Item)
			else if(keyCode == 46 || keyCode == 8){
				var onDelete = this.div.getAttribute('onDelete')
				if(onDelete) (function(e){var tree = this; eval(onDelete)}).apply(this)
			}
			else{
				gotoItem = this.lists[Item.listId].getItemBySearchChar(String.fromCharCode(keyCode))
			}
			
			if(gotoItem && gotoItem != Item){
				Item.deselect()
				gotoItem.select()
				
				if(this.div.hasClassName('scroller')) this.div.fire('1site1:showel', {el: gotoItem.getEl()})
				
				this.listOnChange()
				Event.stop(e.memo.event)
				return false
			}
			
		}).bind(this))
		
		return true
	},
	
	load: function(script, parameters, reload){
		parameters = Interface.buildQueryArray(parameters)
		
		var pars = parameters.join('&')

		var location
		if(script.match(/^https?\:/) || script.match(/^\//)) location = script
		else{
			location = document.location.pathname.replace(/[^\/]+$/, '') + script
			if(!location.match(/^\//)) location = '/' + location
		}
		var queryString = pars.replace(/(action|subAction|tmp\w+|r)=[^&]+&?/ig, '')
		
		this.script = location
		this.queryString = queryString
		this.location = location + '?' + queryString
		
		pars += '&lists[]=0'
		if(this.openedLists && this.openedLists.length){
			this.openedLists.each(function(listId){
				pars += '&lists[]='+encodeURIComponent(listId)
			})
		}
		
		var treeName = this.treeName
		
		if(!reload){
			$('tree_'+this.treeName).update('<div class="loadingIndicator">&nbsp;</div>')
		}
		else{
			this.lists = {}
			this.items = {}
		}
		
		this.loaded = true
		
		this.getXML(script, pars, function(transport){
			Trees.all[treeName].getResponse(transport)
			Trees.all[treeName].render(0)
			Trees.all[treeName].onLoad(transport)
			Trees.all[treeName].listOnChange()
			//if(this.div.hasClassName('scroller')) this.div.fire('1site1:showel', {el: gotoItem.getEl()})
		})
		return this
	},
	reload: function(script, parameters){
		this.load(script, parameters, true)
	},
	refresh: function(){
		var script = this.script
		var pars = this.queryString
		
		this.lists = {}
		this.items = {}
		
		pars += '&lists[]=0'
		if(this.openedLists && this.openedLists.length){
			this.openedLists.each(function(listId){
				pars += '&lists[]='+encodeURIComponent(listId)
			})
		}
		var treeName = this.treeName
		this.getXML(script, pars, function(transport){
			Trees.all[treeName].getResponse(transport)
			Trees.all[treeName].render(0)
			Trees.all[treeName].onLoad(transport)
			Trees.all[treeName].listOnChange()
		})
		return this
	},
	
	getXML: function(script, pars, onSuccess){
		Document.indicate('loading...', {delay: 1})
		var treeName = this.treeName
		var a = new Ajax.Request(
			script, 
			{
				method: 'get', 
				parameters: pars + '&holder-type=foldertree&r=' + r(),
				onSuccess: onSuccess,
				on403: function(transport){
					alert(transport.responseText)
					var location = transport.getHeader('X-GoTo')
					if(location && top.onSessionFailure) top.onSessionFailure(location)
					else if(location) top.location.replace(location)
				}
			}
		)
	},
	
	getResponse: function(transport){
		if(!transport.responseXML){
			//Document.trace('no response XML available in request')
			return false
		}
		var doc = transport.responseXML.documentElement
		if(!doc){
			alert('exeption: \n\n' + transport.responseText)
			return false
		}
		
		$A(doc.childNodes).each((function(el){
			if(el.tagName == 'list'){
				delete this.lists[el.getAttribute('listId')]
				this.lists[el.getAttribute('listId')] = new TreeList(this.treeName, el)
			}
		}).bind(this))
	},
	
	onLoad: function(transport){
		var doc = transport.responseXML.documentElement
		if(!doc) return false
		
		this.attr = {}
		for(var i = 0; i < doc.attributes.length; i++){
			this.attr[doc.attributes.item(i).name] = doc.attributes.item(i).value
		}
		
		if(this.getAttribute('js')){
			var func = (function(){eval(this.getAttribute('js'))}).bind(this)
			try{func()}
			catch(e){ErrorHandler.throwError(e, this.getAttribute('js'))}
		}
	},
	
	getAttribute: function(name){
		return this.attr[name]
	},
	
	addItem: function(Item){
		if(this.items[Item.id]) delete this.items[Item.id]
		this.items[Item.id] = Item
	},
	
	getItem: function(id){
		return this.items[id]
	},
	
	render: function(listId){
		if(!listId){
			var div = $('tree_'+this.treeName)
			$A($(div).descendants()).each(function(el){
				el.remove()
			})
			div.update(this.lists[0].render())
			div.onselectstart = function(){return false}
		}
		else{
			var content = this.lists[listId] ? this.lists[listId].render() : ''
			if(content){
				var div = $('tree_'+this.treeName+'_'+listId)
				$A($(div).descendants()).each(function(el){
					el.remove()
				})
				div.update(content)
				div.onselectstart = function(){return false}
				$A(div.getElementsByTagName('*')).each(function(el){
					el.onselectstart = function(){return false}
				})
			}
			else{
				var Item = Trees.all[this.treeName].items[listId]
				Item.fertile = false
				$A('tree_'+this.treeName+'_'+Item.listId+'_'+Item.id).update(Item.render())
			}
		}
	},
	
	toggleList: function(id){
		var currState = $('tree_'+this.treeName+'_'+id).getStyle('display') == 'none' ? 'closed' : 'open'
		if(currState == 'closed') this.openList(id)
		else this.closeList(id)
	},
	openList: function(id){
		var Item = this.items[id]
		if(Item) Item.openList()
	},
	closeList: function(id){
		var Item = this.items[id]
		if(Item) Item.closeList()
	},
	
	onMouseDown: function(e, Item){
		var shift = e.shiftKey
		var rightClick = (!Event.isLeftClick(e) || mac && e.ctrlKey)
		var ctrl = !mac && e.ctrlKey
		
		var changeCount = 0
		var treeName = this.treeName
		
		Document.setFocus(this.div)
		
		if(rightClick){
			if(!Item.selected){
				this.selected.each(function(id){
					if(id != Item.id && Trees.all[treeName].items[id]){
						changeCount += Trees.all[treeName].items[id].deselect()
					}
				})
				changeCount += Item.select()
				Trees.all[this.treeName].prevClicked = Item.id
			}
		}
		else if((!ctrl || this.selectOne) && (this.selectOne || !shift || !this.prevClicked) && !rightClick){
			this.selected.each(function(id){
				if(id != Item.id && Trees.all[treeName].items[id]){
					changeCount += Trees.all[treeName].items[id].deselect()
				}
			})
			changeCount += Item.select()
			Trees.all[this.treeName].prevClicked = Item.id
		}
		else if(shift){
			if(this.prevClicked){
				this.getRange(this.prevClicked, Item.id).each(function(id){
					changeCount += Trees.all[treeName].items[id].select()
				})
			}
		}
		else if(ctrl){
			if(this.selected.indexOf(Item.id) > -1) changeCount += Item.deselect()
			else changeCount += Item.select()
		}
		
		if(changeCount) this.listOnChange()
		
		if(this.div.onItemMouseDown && typeof(this.div.onItemMouseDown) == 'function'){
			var func = this.div.onItemMouseDown.bind(this)
			func(e)
		}
		else if(this.div.getAttribute('onItemMouseDown')){
			var func = function(e){
				var event = e
				var selection = this.selected
				var name = this.treeName
				var treeName = name
				var tree = this
				eval(this.div.getAttribute('onItemMouseDown'))
			}
			func.apply(this, [e])
		}
	},
	onDblClick: function(Item){
		var code = this.div.getAttribute('onItemDblClick')
		if(Item.fertile) this.toggleList(Item.id)
		if(code){
			var name = this.treeName
			var tree = this
			var id = Item.id
			var selection = Trees.all[name].selected
			
			var func = function(){
				eval(code)
			}
			try{func.apply(this)}
			catch(e){ErrorHandler.throwError(e, code)}
		}
	},
	
	select: function(selection){
		if(!selection) selection = []
		else if(typeof selection == 'string') selection = selection.split(/\,/)
		
		var changeCount = 0
		var treeName = this.treeName
		if(this.selected){
			this.selected.each(function(id){
				if(selection.indexOf(id) < 0 && Trees.all[treeName].items[id]){
					changeCount += Trees.all[treeName].items[id].deselect()
				}
			})
		}
		$A(selection).each(function(id){
			var Item = Trees.all[treeName].items[id]
			if(Item && !Item.selected) changeCount += Item.select()
		})
		
		if(changeCount) this.listOnChange()
		return this
	},
	deselect: function(items){
		if(!items) this.select()
		
		var changeCount = 0
		var treeName = this.treeName
		$A(items).each(function(id){
			var Item = Trees.all[treeName].items[id]
			if(!Item.selected) changeCount += Item.deselect()
		})
		
		if(changeCount) this.listOnChange()
		return this
	},
	
	listOnChange: function(){
		var treeName = this.treeName
		
		var html = '<select name="'+this.treeName+'[]" id="'+this.treeName+'[]" multiple>'
		this.selected.each(function(id){
			if(!Trees.all[treeName].items[id]){
				Trees.all[treeName].selected = $A(Trees.all[treeName].selected).without(id)
			}
			else html += '<option selected value="'+id+'" />'
		})
		html += '</select>'
		$('tree_'+this.treeName+'_selector').update(html)
		
		if(this.saveSelection){
			Settings.setSetting('tree:'+this.treeName+':selected', Trees.all[this.treeName].selected, this.settingScope)
		}
		
		if(this.div.getAttribute('onSelectionChange')){
			var func = function(){
				var selection = this.selected
				var name = this.treeName
				var treeName = name
				var tree = this
				eval(this.div.getAttribute('onSelectionChange'))
			}
			if(this.onSaveTimeoutId) clearTimeout(this.onSaveTimeoutId)
			this.onSaveTimeoutId = setTimeout((function(){
				try{func.apply(this)}
				catch(e){ErrorHandler.throwError(e, this.div.getAttribute('onSelectionChange'))}
			}).bind(this), 400)
		}
	},
	
	getRange: function(startId, endId){
		var startItem = this.items[startId]
		var endItem = this.items[endId]
		var range = []; var Item = startItem; var endFound = false; var id = 0
		
		while(Item && Item.id != endItem.id){
			Item = Item.next()
			if(!Item) break
			range[range.length] = Item.id
			if(Item.id == endId) endFound = true
		}
		if(!endFound){
			Item = startItem
			range = []
			while(Item && Item.id != endId){
				Item = Item.previous()
				if(!Item) break
				range[range.length] = Item.id
				if(Item.id == endId) endFound = true
			}
		}
		if(endFound) return $A(range)
		else return []
	},
	
	storeListState: function(id, state){
		var changed = false
		if(state == 'opened' && this.openedLists.indexOf(id) < 0){
			this.openedLists[this.openedLists.length] = id
			changed = true
		}
		else if(state == 'closed' && this.openedLists.indexOf(id) > -1){
			this.openedLists = $A(this.openedLists).without(id)
			changed = true
		}
		var treeName = this.treeName
		this.openedLists.each(function(id){
			if(!Trees.all[treeName].items[id]){
				Trees.all[treeName].openedLists = $A(Trees.all[treeName].openedLists).without(id)
			}
		})
		
		if(changed && this.saveSelection){
			Settings.setSetting('tree:'+this.treeName+':opened', this.openedLists, this.settingScope)
		}
	}
})

var TreeList = Class.create({
	initialize: function(treeName, dom){
		this.treeName = treeName
		this.listId = dom.getAttribute('listId')
		this.items = []
		this.idList = {}
		this.attr = []
		for(var i = 0; i < dom.attributes.length; i++){
			this.attr[dom.attributes.item(i).name] = dom.attributes.item(i).value
		}
		
		var el, index
		for(var i=0; i<dom.childNodes.length; i++){
			el = dom.childNodes[i]
			if(el.tagName == 'item'){
				index = this.items.length
				var Item = new TreeItem(this.treeName, this.listId, index, el)
				Trees.all[this.treeName].addItem(Item)
				this.items[index] = Item.id
				this.idList[Item.id] = index
			}
		}
	},
	
	getAttribute: function(name){
		if(name == 'treeName') return this.treeName
		if(name == 'listId') return this.listId
		else return this.attr[name]
	},
	
	render: function(){
		var html = ''
		var itemCount = this.items.length
		var treeName = this.treeName
		
		$A(this.items).each(function(id, index){
			var Item = Trees.all[treeName].items[id]
			Item.itemCount = itemCount
			Item.index = index
			html += Item.render()
		})
		return html
	},
	
	getItemBySearchChar: function(char){
		char = char.toLowerCase()
		var Item = null
		for(var i = 0; i < this.items.length; i++){
			if(Trees.all[this.treeName].items[this.items[i]].getCharKey() == char){
				Item = Trees.all[this.treeName].items[this.items[i]]
			}
		}
		return Item
	}
})

var TreeItem = Class.create({
	initialize: function(treeName, listId, index, el){
		this.treeName = treeName
		this.listId = listId
		this.index = index
		
		this.content = el.getAttribute('content')
		this.icon = el.getAttribute('icon')
		this.iconActive = el.getAttribute('iconActive')
		this.id = el.getAttribute('id')
		this.fertile = el.getAttribute('fertile')
		this.className = el.getAttribute('className')
		this.onClick = el.getAttribute('onClick')
		this.selectOnToggle = el.getAttribute('selectOnToggle')
		this.toggleOnClick = el.getAttribute('toggleOnClick')
		
		this.attr = []
		for(var i = 0; i < el.attributes.length; i++){
			this.attr[el.attributes.item(i).name] = el.attributes.item(i).value
		}
		
		if(this.fertile){
			if(!this.icon) this.icon = grS()+'/graphics/dtree/folder.png'
			else if(!this.iconActive) this.iconActive = this.icon
			if(!this.iconActive) this.iconActive = grS()+'/graphics/dtree/folderopen.png'
		}
		else{
			if(!this.icon) this.icon = grS()+'/graphics/dtree/page.gif'
		}
		
		this.selected = Trees.all[this.treeName].selected.indexOf(this.id) > -1
	},
	
	getAttribute: function(name){
		if(name == 'selected') return this.selected
		if(name == 'listId') return this.listId
		else return this.attr[name]
	},
	
	render: function(){
		var childList = Trees.all[this.treeName].lists[this.id]
		//if(childList) this.fertile = true
		
		this.open = this.fertile && Trees.all[this.treeName].openedLists.indexOf(this.id) > -1 ? true : false
		
		var idStr = 'tree_'+this.treeName+'_'+this.listId+'_'+this.id
		
		var title = this.getAttribute('title')
		
		var html = (this.className ? '<div class='+this.className+'>' : '')+'<div treeItemId="'+this.id+'" id="'+idStr+'" treeName="'+this.treeName+'" listId="'+this.listId+'" class="item'+(Trees.all[this.treeName].selected.indexOf(this.id) > -1 ? ' itemActive' : '')+(this.fertile ? ' fertile' : ' unfertile')+'"'+(title ? ' title="'+title+'"' : '')+'><table class=table cellspacing=0 cellpadding=0 border=0><tr>'
		
		// toggler
		html += '<td width=18 id="'+idStr+'_toggler" toggler=1 class="togglerCell'
		if(this.fertile){
			if(this.open) html += ' togglerCellOpened'
			else html += ' togglerCellClosed'
			html += '">'
		}
		else html += '">'
		html += '<img src="'+grS()+'/graphics/shim.gif" toggler=1 /></td>'
		
		// icon
		html += '<td class=iconCell width=18>'
		if(this.open && this.iconActive && childList){
			html += '<img id="'+idStr+'_icon" class="icon" src="'+this.iconActive+'">'
		}
		else html += '<img id="'+idStr+'_icon" src="'+this.icon+'" class="icon">'
		html += '</td>'
		
		// content
		html += '<td class=content width=100%>'+this.content+'</td>'
		html += '</tr></table></div>'+(this.className ? '</div>' : '')
		
		// child list
		if(this.fertile || childList){
			html += '<div listId="'+this.id+'" style="padding-left: 18px;'+(this.open && childList?'':' display: none;')+'" id="tree_'+this.treeName+'_'+this.id+'" isTreeList=1>'
			if(childList) html += childList.render()
			html += '</div>'
		}
		
		return html
	},
	
	setToggler: function(state){
		var toggler = this.getEl('toggler')
		if(state == 'opened'){
			if(toggler.hasClassName('togglerCellClosed')) toggler.removeClassName('togglerCellClosed')
			toggler.addClassName('togglerCellOpened')
		}
		else if(state == 'closed'){
			if(toggler.hasClassName('togglerCellOpened')) toggler.removeClassName('togglerCellOpened')
			toggler.addClassName('togglerCellClosed')
		}
	},
	
	openList: function(){
		if(!this.fertile) return false
		this.open = true
		if(this.noChildren){
			this.getEl('list').show()
			this.setToggler('opened')
			if(this.iconActive) this.getEl('icon').src = this.icon
			Trees.all[this.treeName].storeListState(this.id, 'opened')
			return true
		}
		
		if(Trees.all[this.treeName].lists[this.id]){
			this.getEl('list').show()
			this.setToggler('opened')
			if(this.iconActive) this.getEl('icon').src = this.iconActive
			Trees.all[this.treeName].storeListState(this.id, 'opened')
		}
		else{
			this.getEl('list').show().update('<div class="loadingIndicator">&nbsp;</div>')
			this.setToggler('opened')
			
			var treeName = this.treeName
			var id = this.id
			
			Trees.all[this.treeName].storeListState(this.id, 'opened')
			
			Trees.all[treeName].getXML(Trees.all[treeName].script, Trees.all[treeName].queryString + '&lists[]='+encodeURIComponent(id), function(transport){
				Trees.all[treeName].getResponse(transport)
				var Item = Trees.all[treeName].items[id]
				if(Trees.all[treeName].lists[id] && Trees.all[treeName].lists[id].items.length){
					Item.getEl('list').update(Trees.all[treeName].lists[id].render())
					Item.openList()
				}
				else{
					Trees.all[treeName].items[id].noChildren = true
					Item.setToggler('opened')
					Item.getEl('list').update('')
					if(Item.iconActive) Item.getEl('icon').src = Item.icon
				}
			})
		}
	},
	
	closeList: function(){
		if(!this.fertile) return false
		this.open = false
		if(this.noChildren){
			this.getEl('list').hide()
			this.setToggler('closed')
			Trees.all[this.treeName].storeListState(this.id, 'closed')
			return true
		}
		var table = this.getEl().down()
		if(this.iconActive) table.descendants('IMG')[1].src = this.icon
		this.getEl('list').hide()
		this.setToggler('closed')
		if(this.iconActive) this.getEl('icon').src = this.icon
		Trees.all[this.treeName].storeListState(this.id, 'closed')
	},
	
	select: function(){
		if(Trees.all[this.treeName].selected.indexOf(this.id) < 0){
			Trees.all[this.treeName].selected.push(this.id)
			if(this.getEl()) this.getEl().addClassName('itemActive')
			this.selected = true
			return 1
		}
		return 0
	},
	deselect: function(){
		if(Trees.all[this.treeName].selected.indexOf(this.id) > -1){
			Trees.all[this.treeName].selected = Trees.all[this.treeName].selected.without(this.id)
			if(this.getEl()) this.getEl().removeClassName('itemActive')
			this.selected = false
			return 1
		}
		return 0
	},
	
	getEl: function(type){
		if(type == 'toggler') return $('tree_'+this.treeName+'_'+this.listId+'_'+this.id+'_toggler')
		else if(type == 'icon') return $('tree_'+this.treeName+'_'+this.listId+'_'+this.id+'_icon')
		else if(type == 'list') return $('tree_'+this.treeName+'_'+this.id)
		else return $('tree_'+this.treeName+'_'+this.listId+'_'+this.id)
	},
	
	next: function(){
		var Item = null
		var div = this.getEl()
		while(div && !Item){
			if(div.getAttribute('treeItemId') && div.getAttribute('treeItemId') != this.id){
				Item = Trees.all[this.treeName].items[div.getAttribute('treeItemId')]
			}
			else if(div.getAttribute('isTreeList') && div.getStyle('display') != 'none'){
				div = (div.firstDescendant('DIV') || (div.next('DIV') || div.up('DIV').next('DIV') || null))
			}
			else{
				div = (div.next('DIV') || div.up('DIV').next('DIV') || null)
			}
		}
		return Item
	},
	previous: function(){
		var Item = null
		var div = this.getEl()
		while(div && !Item){
			if(div.getAttribute('treeItemId') && div.getAttribute('treeItemId') != this.id){
				Item = Trees.all[this.treeName].items[div.getAttribute('treeItemId')]
			}
			else if(div.getAttribute('isTreeList') && div.getStyle('display') != 'none'){
				div = (div.immediateDescendants().last() || (div.previous('DIV') || div.up('DIV').previous('DIV') || null))
			}
			else{
				div = (div.previous('DIV') || div.up('DIV').previous('DIV') || null)
			}
		}
		return Item
	},
	
	charKey: null,
	getCharKey: function(){
		if(this.charKey !== null) return this.charKey
		
		var div = this.getEl()
		if(!div) return false
		
		this.charKey = (div.innerText || div.textContent || '').strip().substring(0, 1).toLowerCase()
		return this.charKey
	}
})


/*--------------------------------------------------------------------------*/
Document = {
	getAssetsBaseUrl: function(){
		var url = Document.assetsBaseUrl
		return url ? url : ''
	},
	traceCell: null,
	trace: function(txt){
		if(!document.body){
			Event.observe(document, '1site1:domloaded', function(){
				Document.trace(txt)
			})
			return
		}
		
		if(!Document.traceCell){
			Document.traceCell = new Element('div').setStyle({position: 'absolute', backgroundColor: 'yellow', color: 'black', height: '400px', width: '250px', overflow: 'auto', zIndex: 2, padding: '3px'}).observe('dblclick', function(){Document.traceCell.hide().update('')})
			$(document.body).insert({top: Document.traceCell})
		}
		Document.traceCell.show().insert({top: new Element('p').setStyle({borderBottom: '1px dotted red'}).update(Document.decimalEncodeHtml(txt).gsub('<', '&lt;').gsub('>', '&gt;'))})
		
	},
	requestVars: null,
	getRequestVar: function(name){
		if(Document.requestVars) return Document.requestVars[name]
		
		var query = document.isPostSave ? parent.document.location.search : document.location.search
		Document.requestVars = Document.decodeQuery(query.replace(/^\?/, '').replace(/#.*$/, ''))
		
		return Document.requestVars[name]
	},
	decodeQuery: function(q){
		if(!q || typeof(q) != 'string') q = ''
		
		q = q.split(/&/)
		var query = {}
		$A(q).each(function(v){
			v = v.split(/=/)
			query[unescape(v[0])] = v[1] === undefined ? '' : unescape(v[1])
		})
		return query
	},
	encodeQuery: function(q){
		if(!q) return ''
		var query = []
		$H(q).each(function(v){query.push(escape(v[0])+'='+escape(v[1]))})
		return query.join('&')
	},
	tipOpen: function(el){
		var container = $('tipContainer')
		if(!container){
			el.insert({after: '<div id=tipContainer style="display: none; background-color: lightyellow; color: black; border: 1px solid black; padding: 1px; padding-right: 6px; padding-left: 4px; font-family: Arial; font-size: 12px; line-height: 15px;" nowrap></div>'})
			container = $('tipContainer')
			container.setStyle({position: 'absolute'}).show()
		}
		else{
			if($(el.nextSibling) != container) el.insert({after: container})
			container.show()
		}
		container.update(el.getAttribute('tip'))
		
		var pos = el.viewportOffset()
		var top = pos.top, left = pos.left
		top -= container.getHeight() + 4
		if(top < 0) top = pos.top + container.getHeight() + 4
		container.setStyle({left: left+'px', top: top+'px'})
	},
	tipClose: function(){
		if($('tipContainer')) $('tipContainer').hide()
	},
	getTop: function(){
		if(parent && parent.Document && parent.Document != Document) return parent.Document.getTop()
		else if(Interface.opener && Interface.opener.Document && Interface.opener.Document != Document){
			return Interface.opener.Document.getTop()
		}
		else return self
	},
	getFirstFocusElement: function(parentEl){
		parentEl = $(parentEl || document.body)
		var index = 0
		el = parentEl.getAttribute('focusable') ? parentEl : parentEl.down('*[focusable=1]', index)
		while(el){
			if(isVisible(el)) return el
			else el = parentEl.down('*[focusable=1]', ++index)
		}
		return null
	},
	setFocus: function(el){
		if(el && (!Document.focusEl || el != Document.focusEl)){
			if(el.setActive) el.setActive()
			else{
				try{el.focus()}catch(e){}
			}
		}
		if(Document.focusEl && isFocusable(Document.focusEl) && !isFocusable(el)){
			try{Document.focusEl.blur()}catch(e){}
		}
		
		Document.focusEl = $(el)
	},
	focus: function(parentEl){
		
		var el = Document.getFirstFocusElement(parentEl)
		
		var f = function(){
			var el = new Element('input').setStyle({position: 'absolute'})
			$(document.body).insert({top: el})
			el.focus()
			el.remove()
			document.body.focus()
		}
		
		try{
			if(el && isFocusable(el)) el.focus()
			else f()
		}
		catch(e){
			try{f()}
			catch(e){}
		}
	},
	
	keyDown: function(e){
		if(Document.focusEl) Document.focusEl.fire('my:keydown', {
			keyCode: e.keyCode, 
			shift: e.shiftKey, 
			ctrl: e.ctrlKey,
			event: e
		})
	},
	autoId: function(el){
		if(!el.id && el.name){
			if($(el.name)){
				el.id = el.name + '_' + $$(el.tagName+'[name='+el.name+']').indexOf(el)
			}
			else el.id = el.name
		}
	},
	setupFormElement: function(el){
		el = $(el)
		
		Document.autoId(el)
		
		if((el.type == 'text' || el.type == 'password') && !el.getAttribute('onEnter')){
			el = $(el)
			var f = el.up('form.site1InterfaceForm')
			if(!f) return
			el.observe('keyup', function(e){if(e.keyCode != 13) el._value = el.value})
			el.observe('mouseup', function(e){el._value = el.value})
			
			el.observe('keydown', function(e){
				if(e.keyCode != 13) return
				setTimeout(function(){
					if(el.value == el._value) Interface.save({f:f})
					else el._value = el.value
				}, 50)
			})
		}
		if(el.type == 'password'){
			Event.observe(el, 'click', function(e){el.focus();el.select()})
		}
		if(el.tagName == 'INPUT' && el.type == 'file' && Document.flashUploader.depositScript && el.hasClassName('flashUploader') && FlashDetect.installed && FlashDetect.major >= 8){
			//  && !Prototype.Browser.IE
			el = $(el)
			
			var width = el.getWidth()
			if(width < 200) width = 400
			
			el.hide()
			
			if(Prototype.Browser.IE){
				var flashvars = {}
				
				flashvars.elementName = el.name
				flashvars.onChange = 'parent.Document.flashUploader.onChange'
				//flashvars.onProgress = 'parent.Document.flashUploader.onProgress'
				flashvars.onComplete = 'parent.Document.flashUploader.onComplete'
				flashvars.onFailure = 'parent.Document.flashUploader.onFailure'
				flashvars.uploadScript = Document.flashUploader.depositScript
				flashvars.uploaderId = Document.sid
				
				var mult = el.attributes.getNamedItem('multipleFiles')
				if(!mult || mult.value == '0' || mult.value == 'false') mult = null
				if(mult) flashvars.multipleFiles = 1
				
				var src = '/javascript/flash.uploader/iframe.php?'
				src += 'src='+escape(Document.flashUploader.swf)
				src += '&flashvars='+escape($H(flashvars).toJSON())
				var iframe = new Element('iframe', {src: src, frameborder: 0, 'scroll': 'no'}).setStyle({width: width+'px', height: '26px'})
				
				el.insert({after: iframe})
				var realElement = iframe
				
				var getFlash = function(){return iframe.contentWindow.getFlash()}
			}
			else{
				var flashvars = []
				flashvars.push('elementName=' + el.name)
				flashvars.push('onChange=Document.flashUploader.onChange')
				//flashvars.push('onProgress=Document.flashUploader.onProgress')
				flashvars.push('onComplete=Document.flashUploader.onComplete')
				flashvars.push('onFailure=Document.flashUploader.onFailure')
				flashvars.push('uploadScript=' + Document.flashUploader.depositScript)
				flashvars.push('uploaderId='+Document.sid)
				
				var mult = el.attributes.getNamedItem('multipleFiles')
				if(!mult || mult.value == '0' || mult.value == 'false') mult = null
				if(mult) flashvars.push('multipleFiles=1')
				
				var embed = new Element('embed', {
					src: Document.flashUploader.swf,
					width: width,
					height: 26,
					quality: 'high',
					type: 'application/x-shockwave-flash',
					allowScriptAccess: 'always',
					wmode: 'transparent',
					menu: 'false',
					flashvars: flashvars.join('&'),
					bgcolor: 'black'
				})
				el.insert({after: embed})
				var realElement = embed
				
				var getFlash = function(){return embed}
			}
			
			
			var newEl = new Element('input', {type: 'hidden', name: el.name, id: el.name, flashUpload: 1})
			if(mult) newEl.setAttribute('multipleFiles', 1)
			
			newEl.myOnChange = el.getAttribute('myOnChange')
			newEl.getFlash = getFlash
			newEl.realElement = realElement
			newEl.uploadStatus = {completed: false, done: 0, files: [], size: 0, bitesDone: 0}
			
			el.insert({after: newEl})
			
			el.remove()
		}
		else if(el.tagName == 'INPUT' && el.type == 'file'){
			// flash file uploader not loaded
			if(el.getAttribute('myOnChange')){
				$(el).observe('change', (function(e){eval(el.getAttribute('myOnChange'))}).bind($(el)))
			}
		}
		try{el.observe('focus', function(){Document.setFocus(el)})}catch(e){}
	},
	
	setupFormElements: function(el){
		if(!el) el = Interface.f()
		if(el.tagName != 'FORM') return
		Form.getElements(el).each(function(el){Document.setupFormElement(el)})
	},
	
	textareaStoreCaret: function(e){
		var el = Event.element(e)
		if(document.selection) el.setAttribute('range', document.selection.createRange().duplicate())
	},
	textareaKeyDown: function(e){
		var el = Event.element(e)
		var range = el.getAttribute('range')
		if(e.keyCode == 9){// tab
			if(range) range.text = range.text.charAt(range.text.length - 1) == ' ' ? "\t" + ' ' : "\t"
			else el.value = "\t"
			Event.stop(e)
			return false
		}
		return true
	},
	
	decimalCodes: [
		{name: 'Latin-1 Supplement', codes: [161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255]},
		{name: 'Latin Extended', codes: [256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,273,274,275,276,277,278,279,280,281,282,283,284,285,286,287,288,289,290,291,292,293,294,295,296,297,298,299,300,301,302,303,304,305,306,307,308,309,310,311,312,313,314,315,316,317,318,319,320,321,322,323,324,325,326,327,328,329,330,331,332,333,334,335,336,337,338,339,340,341,342,343,344,345,346,347,348,349,350,351,352,353,354,355,356,357,358,359,360,361,362,363,364,365,366,367,368,369,370,371,372,373,374,375,376,377,378,379,380,381,382,383,402,506,507,508,509,510,511,7808,7809,7810,7811,7812,7813,7922,7923]},
		{name: 'Greek', codes: [900,901,902,903,904,905,906,908,910,911,912,913,914,915,916,917,918,919,920,921,922,923,924,925,926,927,928,929,931,932,933,934,935,936,937,938,939,940,941,942,943,944,945,946,947,948,949,950,951,952,953,954,955,956,957,958,959,960,961,962,963,964,965,966,967,968,969,970,971,972,973,974]},
		{name: 'Cyrillic', codes: [1025,1026,1027,1028,1029,1030,1031,1032,1033,1034,1035,1036,1038,1039,1040,1041,1042,1043,1044,1045,1046,1047,1048,1049,1050,1051,1052,1053,1054,1055,1056,1057,1058,1059,1060,1061,1062,1063,1064,1065,1066,1067,1068,1069,1070,1071,1072,1073,1074,1075,1076,1077,1078,1079,1080,1081,1082,1083,1084,1085,1086,1087,1088,1089,1090,1091,1092,1093,1094,1095,1096,1097,1098,1099,1100,1101,1102,1103,1105,1106,1107,1108,1109,1110,1111,1112,1113,1114,1115,1116,1118,1119,1168,1169]},
		{name: 'Other', codes: [710,711,713,728,729,730,731,732,733,8211,8212,8213,8215,8216,8217,8218,8219,8220,8221,8222,8224,8225,8226,8230,8240,8242,8243,8249,8250,8252,8254,8260,3819,8355,8356,8359,8364,8453,8467,8470,8482,8486,8494,8539,8540,8541,8542,8592,8593,8594,8595,8596,8597,8616,8706,8710,8719,8721,8722,8725,8729,8730,8734,8735,8745,8747,8776,8800,8801,8804,8805,8962,8976,8992,8993,9472,9474,9484,9488,9492,9496,9500,9508,9516,9524,9532,9552,9553,9554,9555,9556,9557,9558,9559,9560,9561,9562,9563,9564,9565,9566,9567,9568,9569,9570,9571,9572,9573,9574,9575,9576,9577,9578,9579,9580,9600,9604,9608,9612,9616,9617,9618,9619,9632,9633,9642,9643,9644,9650,9658,9660,9668,9674,9675,9679,9688,9689,9702,9786,9787,9788,9792,9794,9824,9827,9829,9830,9834,9835,61441,61442,64257,64258]}
	],
	
	decimalEncodeHtml: function(html){
		$A(Document.decimalCodes).each(function(group){
			$A(group['codes']).each(function(d){
				if(html.indexOf(String.fromCharCode(d)) >= 0){
					eval('html = html.replace(/'+String.fromCharCode(d)+'/g, "&#'+d+';");')
				}
			})
		})
		return html
	},
	
	colorPicker: function(e){
		var el = Event.findElement(e, 'SPAN')
		var changeMade = false
		var input = $(el.getAttribute('inputElName'))
		var hex = $F(input)
		if(hex) hex = hex.toString().toUpperCase()
		
		Interface.dialog('/editor/colorpicker/index.html', false, {width: 420, height: 400, dialogVars: hex, onClose: function(hex){
			if(!hex) return
			hex = hex.toString().toUpperCase()
			if(hex == 'transparant'){
				el.style.backgroundColor = '#FFFFFF'
				if(input.value) changeMade = true
				input.value = ''
				el.style.backgroundImage = 'url('+grS()+'/graphics/colorpickBG.gif)'
			}
			else if(hex){
				el.style.backgroundColor = '#' + hex
				if(input.value != '#' + hex) changeMade = true
				input.value = '#' + hex
				el.style.backgroundImage = 'url()'
			}
			if(changeMade){
				input.fire('1site1:onchange')
				input.fire('onchange')
			}
		}})
	},
	setColorPicker: function(el, hex){
		el = $(el)
		if(!el) return
		if(hex && !hex.match(/^#/)) hex = '#' + hex
		if(hex){
			try{
				$('colorPickerSpan_'+el.name).style.backgroundColor = hex
				el.value = hex
				$('colorPickerSpan_'+el.name).style.backgroundImage = 'url()'
			}
			catch(e){
				el.value = ''
				$('colorPickerSpan_'+el.name).style.backgroundImage = 'url('+grS()+'/graphics/colorpickBG.gif)'
				$('colorPickerSpan_'+el.name).style.backgroundColor = '#FFFFFF'
			}
		}
		else{
			el.value = ''
			$('colorPickerSpan_'+el.name).style.backgroundImage = 'url('+grS()+'/graphics/colorpickBG.gif)'
			$('colorPickerSpan_'+el.name).style.backgroundColor = '#FFFFFF'
		}
	},
	
	showElement: function(el){
		el = $(el)
		while(el && el != document.body){
			el = el.up()
			if(el.hasClassName('groupHeadingTbody')){
				GroupHeadings.open(el.getAttribute('headingName'))
			}
			else if(el.attributes['tabGroup']){
				TabGroups.open(el.getAttribute('tabGroup'), el.getAttribute('tabIndex'))
			}
		}
	},
	
	showWaitScreen: function(){
		if(!$('waitScreen')){
			var html = '<table cellspacing=0 cellpadding=0 border=0 id=waitScreen><tr><td align=center><div class=img>&nbsp;</div><div id=waitScreenProgressDiv></div></td></tr></table>'
			new Insertion.Top(document.body, html)
		}
		else{
			Element.show('waitScreen')
		}
	},
	hideWaitScreen: function(){
		if($('waitScreen')) Element.hide('waitScreen')
	},
	showProgress: function(progress){
		if(progress <= 0) progress = 0
		if(progress > 1) progress = 1
		progress = Math.round(progress * 100)
		if(!progress) progress = 1
		var cell = $('waitScreenProgressDiv')
		if(!cell.down('div')){
			cell.insert({top: new Element('div', {id: 'progressBar'}).insert({top: new Element('div', {id: 'progressBarContent'})})})
		}
		cell.down('div#progressBarContent').setStyle({width: progress + '%'})
	},
	
	showContactIndicator: function(){
		if($('ajaxLoadingEl')) Element.show('ajaxLoadingEl')
		else $(document.body).insert({bottom: '<div id=ajaxLoadingEl><span>loading...</span></div>'})
		
	},
	hideContactIndicator: function(){
		if($('ajaxLoadingEl')) Element.hide('ajaxLoadingEl')
	},
	
	indicate: function(message, options){
		
		var doc = Document.getIndicatorDoc()
		if(doc != self) return doc.Document.indicate(message, options)
		
		if(!Document.indicator){
			
			$(document.body).insert({bottom: '<div id=site1Indicator style="position: absolute; top: 0; display: none;">'})
			Document.indicator = $(document.body).down('div#site1Indicator')
			Document.indicator.observe('1site1:show', function(e){
				var options = (e.memo || {})
				
				if(this._delayTimerId) clearTimeout(this._delayTimerId)
				if(this._hideTimerId) clearTimeout(this._hideTimerId)
				
				this.update(Document.decimalEncodeHtml(options.message))
				this.fire('1site1:place')
				this._delayTimerId = setTimeout((function(){
					this.show()
					this.fire('1site1:place')
					
					if(options.length > 0){
						this._hideTimerId = setTimeout((function(){this.fire('1site1:hide')}).bind(this), options.length * 1000)
					}
				}).bind(this), (options.delay || 0) * 1000)
			})
			
			Document.indicator.observe('1site1:place', function(e){
				if(this.visible()){
					var viewport = document.getViewport()
					this.setStyle({left: (viewport.width / 2 - this.getWidth() / 2) + 'px'})
				}
			})
			
			Document.indicator.observe('1site1:hide', function(e){
				if(this._delayTimerId) clearTimeout(this._delayTimerId)
				setTimeout((function(){try{this.hide()}catch(e){}}).bind(this), 500)
				if(this._hideTimerId) clearTimeout(this._hideTimerId)
			})
			
		}
		
		if(!options) options = {}
		options.message = message
		
		Document.indicator.fire('1site1:show', options)
		
	},
	hideIndicator: function(){
		var doc = Document.getIndicatorDoc()
		if(doc != self) doc.Document.hideIndicator()
		else Document.indicator.fire('1site1:hide')
	},
	
	getIndicatorDoc: function(){
		var doc = self
		var access = true
		while(access && doc.Document && doc.Document.getRequestVar('holder-type') == 'iframe' && !doc.Document.getRequestVar('dialog-type')){
			try{
				var test = doc.parent.Document
				doc = doc.parent
			}
			catch(e){access = false}
		}
		return doc
	},
	
	initTopic: function(el){
		el = $(el)
		
		var html = '<table border=0 cellspacing=0 cellpadding=0 class="width100 height100">'
		html += '<tr><td class=header><div><div></div></div></td></tr>'
		html += '<tr><td class=content valign=top><div class=div1><div class=div2><div class=div3></div></div></td></tr>'
		if(el.hasClassName('dashBoardTopic')){
			html += '<tr><td class=bottom><div><div><img src="'+grS()+'/graphics/shim.gif" height=13 width=1 /></div></div></td>'
		}
		html += '</table>'
		
		var title = el.down('div').remove()
		var content = el.down('div').remove()
		el.update(html)
		
		var newTitle = el.down('div', 1)
		var newContent = el.down('tr', 1).down('div', 2)
		
		if(Prototype.Browser.IE) newContent.setStyle({height: newContent.getStyle('min-height')})
		
		$A(content.attributes).each(function(attribute){
			if(attribute.nodeValue && typeof attribute.nodeValue == 'string'){
				newTitle.setAttribute(attribute.nodeName, attribute.nodeValue)
			}
		})
		
		$A(title.childNodes).each(function(node){
			newTitle.insert({bottom: (node.nodeType != 1 ? node.nodeValue : node)})
		})
		$A(content.childNodes).each(function(node){
			newContent.insert({bottom: (node.nodeType != 1 ? node.nodeValue : node)})
		})
		
		if(el.getAttribute('onLoad')){
			onLoadCollection.add(el.getAttribute('onLoad'))
		}
		
	},
	
	initMenuHolder: function(el){
		el = $(el)
		
		var nodes = []
		$A(el.childNodes).each(function(node){
			nodes.push(node)
		})
		
		var html = '<table class="height100 width100" style="display: none;" border=0 cellpadding=0 cellspacing=0>'
		+ '<tr><td class="menuHolderHeader"></td></tr>'
		+ '<tr><td class="height100"><div class="div1"><div class="div2"><div class="div3"></div></div></div></td></tr>'
		+ '</table>'
		
		el.insert({top: html})
		
		var contentCell = el.down().down('div', 2)
		
		$A(nodes).each(function(node){
			contentCell.insert({bottom: (node.nodeType != 1 ? node.nodeValue : node)})
		})
		
		el.down().show()
		
		
	},
	
	setDialogDim: function(width, height){
		if(Interface.dialogType == 'inline' && Interface.inlineDialogObject){
			Interface.inlineDialogObject.setDimensions(width, height)
		}
		else{
			if(Prototype.Browser.IE){
				window.dialogWidth = width+'px'
				window.dialogHeight = (height+30)+'px'
			}
			if(Prototype.Browser.Gecko){
				window.innerWidth = width
				window.innerHeight = height
			}
		}
	},
	
	flashUploader: {
		onChange: function(attr){
			var el = $(attr.name)
			el.uploadStatus = {
				completed: false, 
				done: 0, 
				bitesDone: 0, 
				files: attr.files, 
				fileNames: attr.fileNames, 
				size: attr.size
			}
			
			el.value = $A(attr.fileNames).toJSON()
			
			if(typeof(el.myOnChange) == 'function') el.myOnChange.apply(el)
			else if(typeof(el.myOnChange) == 'string') (function(){eval(el.myOnChange)}).apply(el)
		},
		onProgress: function(attr){
			var el = $(attr.name)
			el.uploadStatus.done = attr.done
			el.uploadStatus.size = attr.size
			el.uploadStatus.bitesDone = attr.bitesDone
			
			if(el.onUploadProgress) el.onUploadProgress(el)
		},
		onComplete: function(attr){
			var el = $(attr.name)
			el.uploadStatus.done = 1
			el.uploadStatus.bitesDone = attr.size
			el.uploadStatus.completed = true
			
			el.value = $A(attr.files).toJSON()
			
			if(el.onCompleted) el.onCompleted(el)
		},
		onFailure: function(attr){
			var el = $(attr.name)
			el.uploadStatus.completed = false
			el.uploadStatus.done = 0
			el.uploadStatus.bitesDone = 0
			
			if(el.onFailure) el.onFailure(el)
		}
	},
	
	onCtrlS: null,
	onCtrlW: null,
	onCtrlN: null,
	onEsc: null
}

Document.holderType = Document.getRequestVar('holder-type')
Document.parentInScope = false
try{
	parent.location.href
	parent.document.body
	Document.parentInScope = true
}
catch(e){}

/*--------------------------------------------------------------------------*/
Lists = {
	openedMenus: [],
	
	init: function(div){
		if(div.getAttribute('initiated')) return false
		
		var div = $(div)
		var name = div.getAttribute('list')
		
		div.id = '_list_' + name
		div.setAttribute('prevNoShiftIndex', -1)
		
		if(div.attributes['selection']){
			var sel = div.getAttribute('selection')
			if(sel.toString().indexOf(',') < 0) sel = [sel.toString()]
			else if(typeof sel == 'string') sel = sel.split(/,/)
			else sel = sel.toString().split(/,/)
			var prevSelection = sel
		}
		else var prevSelection = Settings.getSetting('list:'+name)
		
		var selectorHtml = '<select name="'+name+'[]" id="'+name+'[]" size=1 multiple class=displayNone>'

		// events
		div.observe('mousedown', Lists.itemMouseDown)
		div.observe('click', Lists.itemClick)
		div.observe('dblclick', Lists.itemDblClick)
		
		// all list items
		var idList = []
		var items = $A(div.getElementsByTagName('DIV'))
		var selection = []
		items.each(function(itemDiv){
			if(!itemDiv.id) return
			
			var id = itemDiv.id
			itemDiv.setAttribute('dbId', id)
			itemDiv.id = '_list_'+name+'_' + id
			itemDiv.setAttribute('list', name)
			itemDiv.setAttribute('index', idList.length)
			
			var active = false
			if(prevSelection.length > 0){
				if(prevSelection.indexOf(id) > -1) active = true
				if(prevSelection.length == 1) div.setAttribute('prevNoShiftIndex', idList.length)
			}
			if(itemDiv.attributes['selected']) active = true
			if(active) selection[selection.length] = id
			
			itemDiv.className = 'listItem'
			
			selectorHtml += '<option value="'+id+'">'+id+'</option>'
			
			idList[idList.length] = id
			
			itemDiv.onselectstart = function(){return false}
			$A(itemDiv.getElementsByTagName('*')).each(function(el){
				el.onselectstart = function(){return false}
			})
		})
		
		if(!idList.length){
			div.insert({top: '<div class="error padding">'+(div.getAttribute('listEmptyMessage') || '---')+'</div>'})
		}
		
		selectorHtml += '</select>'
		var orderHtml = '<input type=hidden name="'+name+'_order" id="'+name+'_order" value="'+idList.join(',')+'">'
		div.insert({top: selectorHtml+orderHtml})
		
		Form.Element.setAsDefault(name+'[]')
		
		$A(selection).each(function(id){Lists.itemSelect(name, id)})
		
		Lists.onSelectionChange(name)
		
		onLoadCollection.add('Lists.scroll("'+name+'")')
		
		var menu = $$('table[listContextMenu="'+name+'"]')[0]
		if(menu && !menu.getAttribute('initiated')){
			menu.id = 'listMenu_' + name
			$(document.body).insert({top: menu.remove().hide()})

			$A(menu.select('tr')).each(function(tr){
				tr.setAttribute('list', name)

				try{
					if(tr.select('td').length > 1){
						tr.down('td').addClassName('iconCell')
						tr.down('td', 1).addClassName('textCell')
					}
				}
				catch(e){}
				
				Event.observe(tr, 'mouseover', function(e){tr.addClassName('over')})
				Event.observe(tr, 'mouseout', function(e){tr.removeClassName('over')})
				Event.observe(tr, 'click', function(e){
					Event.stop(e)
					var listName = tr.getAttribute('list')
					
					Lists.menuClose()
					
					var action = tr.getAttribute('action') || tr.down('td[action]').getAttribute('action')
					if(action){
						var func = (function(e, name, selection){
							eval(action)
						}).bind(div)
						try{func(e, listName, Lists.getSelection(listName))}
						catch(e){ErrorHandler.throwError(e, action)}
					}
				})
			})

			menu.setAttribute('initiated', 1)
		}
		Event.observe(div, 'contextmenu', Lists.menuOpen)
		
		div.observe('my:keydown', function(e){
			var keyCode = e.memo.keyCode
			var dir = null
			if(keyCode == 40) dir = 'down'
			else if(keyCode == 38) dir = 'up'
			
			if(dir){
				var sel = Lists.getSelection(name)
				if(sel.length != 1) return
				
				var itemDiv = Lists.getItemDiv(name, sel[0])
				var changeCount = 0
				if(dir == 'up' && itemDiv.previous('div') && itemDiv.previous('div').getAttribute('dbId')){
					changeCount += Lists.itemDeselect(name, itemDiv.getAttribute('dbId'))
					changeCount += Lists.itemSelect(name, itemDiv.previous('div').getAttribute('dbId'))
				}
				else if(dir == 'down' && itemDiv.next('div') && itemDiv.next('div').getAttribute('dbId')){
					changeCount += Lists.itemDeselect(name, itemDiv.getAttribute('dbId'))
					changeCount += Lists.itemSelect(name, itemDiv.next('div').getAttribute('dbId'))
				}
				
				Settings.setSetting('list:'+name, Lists.getSelection(name))
				if(changeCount) Lists.onSelectionChange(name)
			}
			
		})
		
		div.setAttribute('initiated', 1)
	},
	
	onSelectionChangeTimerId: {},
	onSelectionChange: function(name){
		var div = $('_list_'+name)
		if(!div) return false
		var code = div.getAttribute('onListChange')
		if(!code) return null
		
		var selection = Lists.getSelection(name)
		
		if(Lists.onSelectionChangeTimerId[name]) clearTimeout(Lists.onSelectionChangeTimerId[name])
		Lists.onSelectionChangeTimerId[name] = setTimeout((function(){
			var func = (function(name, selection){
				eval(code)
			}).bind(div)
			try{func(name, selection)}
			catch(e){ErrorHandler.throwError(e, code)}
		}).bind(this), 400)
	},
	
	scroll: function(name){
		return false
		var listItem = $('_list_'+name+'_' + $(name+'[]').value)
		var scroller = $('_list_'+name)
		if(!scroller.hasClassName('scroller')) return false
		
		var offset = listItem.cumulativeScrollOffset()
		var height = scroller.getHeight()
		
		return false
		
		if(scroller && scroller.doScroll){
			offset = Position.relativeCumulativeOffset(listItem, scroller)
			while(0 && offset[1] + listItem.clientHeight > scroller.scrollTop + scroller.clientHeight + 10){
				scroller.doScroll('scrollbarPageDown')
				alert(scroller.scrollTop)
			}
		}
	},
	
	itemMouseDown: function(e){
		Event.stop(e)
		var div = Event.findElement(e, 'DIV')
		if(!div.getAttribute('dbId')){
			div = div.up('div[dbId]')
			if(!div) return
		}

		var listName = div.getAttribute('list')
		var listDiv = $('_list_'+listName)
		var itemId = div.getAttribute('dbId')

		Document.setFocus(listDiv)
		
		var shift = e.shiftKey
		var rightClick = (!Event.isLeftClick(e) || mac && e.ctrlKey)
		var ctrl = !mac && e.ctrlKey
		var prevItemIndex = parseInt(listDiv.getAttribute('prevNoShiftIndex'))
		var sel = Lists.getSelection(listName)
		
		var multiple = $('_list_'+listName).getAttribute('multiple')
		var rightClick = (!Event.isLeftClick(e))
		
		var changeCount = 0
		
		if(rightClick){
			if(!Lists.itemSelect(div)) return false
			else{
				if(sel.length > 1 || sel.indexOf(div.getAttribute('dbId')) < 0){
					sel.each(function(id){
						if(itemId != id) changeCount += Lists.itemDeselect(listName, id)
					})
					changeCount += Lists.itemSelect(div)
				}
			}
		}
		else if(multiple < 1 || (!ctrl && (!shift || prevItemIndex < 0 || div.getAttribute('index') == prevItemIndex))){
			// reset
			itemDiv = div
			if(sel.length > 1 || sel.indexOf(div.getAttribute('dbId')) < 0){
				sel.each(function(id){
					if(itemId != id) changeCount += Lists.itemDeselect(listName, id)
				})
				changeCount += Lists.itemSelect(itemDiv)
			}
		}
		else if(ctrl && !shift){
			// cntrl
			if(div.getAttribute('selected') > 0) changeCount += Lists.itemDeselect(div)
			else changeCount += Lists.itemSelect(div)
		}
		else if(!ctrl && shift && prevItemIndex > -1){
			// shift
			if(div.getAttribute('index') * 1 > prevItemIndex){
				// up
				var currDiv = div
				var currSelection = Lists.getSelection(listName)
				while(currDiv && currDiv.getAttribute('index') > prevItemIndex){
					changeCount += Lists.itemSelect(currDiv)
					currDiv = currDiv.previous('div[dbId]')
				}
				// delesect rest
				var clickIndex = div.getAttribute('index')
				$A(currSelection).each(function(id){
					var currDiv = $('_list_'+listName+'_' + id)
					if(currDiv.getAttribute('selected') && currDiv.getAttribute('index') * 1 > clickIndex){
						changeCount += Lists.itemDeselect(currDiv)
					}
				})
			}
			else if(div.getAttribute('index') * 1 < prevItemIndex){
				// down
				var currDiv = div
				var currSelection = Lists.getSelection(listName)
				while(currDiv && currDiv.getAttribute('index') < prevItemIndex){
					changeCount += Lists.itemSelect(currDiv)
					currDiv = currDiv.next('div[dbId]')
				}
				// delesect rest
				var clickIndex = div.getAttribute('index')
				$A(currSelection).each(function(id){
					var currDiv = $('_list_'+listName+'_' + id)
					if(currDiv.getAttribute('selected') && currDiv.getAttribute('index') * 1 < clickIndex){
						changeCount += Lists.itemDeselect(currDiv)
					}
				})
			}
		}
		
		if(!shift) listDiv.setAttribute('prevNoShiftIndex', div.getAttribute('index'))
		
		Settings.setSetting('list:'+listName, Lists.getSelection(listName))
		
		if(changeCount) Lists.onSelectionChange(listName)

	},
	itemDblClick: function(e){
		Event.stop(e)
		
		if(e.shiftKey || e.ctrlKey) return
		
		var div = Event.findElement(e, 'DIV')
		
		if(!div.getAttribute('dbId')){
			if(div.parentNode) div = div.parentNode
			else return
			while(!div.tagName || div.tagName != 'DIV' || !div.getAttribute('dbId')){
				if(div.parentNode) div = div.parentNode
				else return
			}
			if(!div || !div.getAttribute('dbId')) return
		}
		
		var listName = div.getAttribute('list')
		var sel = Lists.getSelection(listName)
		var id = div.getAttribute('dbId')
		var index = div.getAttribute('index')
		
		var changeCount = 0
		
		if(sel.length > 1 || sel.indexOf(id) < 0){
			changeCount += Lists.reset(listName)
			changeCount += Lists.itemSelect(div)
		}
		
		if(changeCount) Lists.onSelectionChange(listName)
		
		if($('_list_'+listName).getAttribute('onItemDblClick')){
			var func = function(e){
				var name = listName
				var selection = Lists.getSelection(name)
				eval($('_list_'+listName).getAttribute('onItemDblClick'))
			}
			try{func.apply($('_list_'+listName))}
			catch(e){ErrorHandler.throwError(e, $('_list_'+listName).getAttribute('onItemDblClick'))}
		}
	},
	itemClick: function(e){
		var listDiv = Event.findElement(e, 'DIV')
		var listName = listDiv.getAttribute('list')
		if(listName && listDiv.id == '_list_' + listName){
			var changeCount = Lists.reset(listName)
			
			if(changeCount) Settings.setSetting('list:'+listName, Lists.getSelection(listName))
			
			if(changeCount) Lists.onSelectionChange(listName)
			
			return true
		}

	},
	itemSelect: function(name, id){
		if(typeof name == 'object') var div = name
		else var div = $('_list_'+name+'_'+id)
		
		var name = div.getAttribute('list')
		var id = div.getAttribute('dbId')
		if(!id) die('no id in Lists.itemSelect')
		var index = div.getAttribute('index')
		
		if(Lists.getSelection(name).indexOf(div.getAttribute('dbId')) > -1) return false
		
		$(name+'[]').options.item(div.getAttribute('index')).selected = true
		Form.Element.setAsDefault(name+'[]')
		
		div.className = 'listItem listItemDown'
		div.setAttribute('selected', 1)
		
		if($('_list_'+name).getAttribute('onItemSelect')){
			var func = function(e){
				var selection = Lists.getSelection(name)
				eval($('_list_'+name).getAttribute('onItemSelect'))
			}
			try{func.apply($('_list_'+listName))}
			catch(e){ErrorHandler.throwError(e, $('_list_'+name).getAttribute('onItemSelect'))}
		}
		
		return 1
	},
	itemDeselect: function(name, id){
		if(typeof name == 'object'){
			var div = name
			name = div.getAttribute('list')
			id = div.getAttribute('dbId')
		}
		else var div = $('_list_'+name+'_'+id)
		
		if(!div) return false
		if(Lists.getSelection(name).indexOf(div.getAttribute('dbId')) < 0) return false

		$(name+'[]').options.item(div.getAttribute('index')).selected = false
		Form.Element.setAsDefault(name+'[]')

		div.className = 'listItem'
		div.setAttribute('selected', 0)
		
		return 1
	},
	
	itemMove: function(name, id, dir){
		if(!$('_list_'+name)) die('no list found with name "'+name+'" in Lists.itemMove')
		if(!id) id = $F(name+'[]')
		if(!id) die('no selected list item found in Lists.itemMove')
		
		var div, listDiv
		
		if(typeof name == 'object'){
			div = name
			name = div.getAttribute('list')
			listDiv = $('_list_'+name)
			id = div.getAttribute('dbId')
		}
		else{
			div = $('_list_'+name+'_'+id)
			listDiv = $('_list_'+name)
		}
		
		var changeMade = false
		
		if(dir == 'up' && div.previous('div') && div.previous('div').getAttribute('dbId')){
			div.insert({after: listDiv.removeChild(div.previous('div'))})
			changeMade = true
		}
		else if(dir == 'down' && div.next('div') && div.next('div').getAttribute('dbId')){
			div.insert({before: div.next('div')})
			changeMade = true
		}
		
		if(changeMade){
			idList = []
			items = $A($('_list_'+name).getElementsByTagName('DIV'))
			items.each(function(itemDiv, index){
				if(!itemDiv.getAttribute('dbId')) return
				idList[idList.length] = itemDiv.getAttribute('dbId')
			})
			$(name+'_order').value = idList.join(',')

			if(listDiv.getAttribute('onOrderChange')){
				var func = function(){
					eval(listDiv.getAttribute('onOrderChange'))
				}
				try{func.apply(listDiv)}
				catch(e){ErrorHandler.throwError(e, listDiv.getAttribute('onOrderChange'))}
			}
}
	},
	itemMoveUp: function(name, id){
		Lists.itemMove(name, id, 'up')
	},
	itemMoveDown: function(name, id){
		Lists.itemMove(name, id, 'down')
	},
	
	reset: function(name){
		var changeCount = 0
		Lists.getSelection(name).each(function(id){
			changeCount += Lists.itemDeselect(name, id)
		})
		return changeCount
	},
	
	getItemDiv: function(name, dbId){
		if(!name) die('no list name in getItemDiv')
		if(!$('_list_'+name)) die('list "' + name + '" not found')
		if(!dbId) dbId = Lists.getSelection(name)[0]
		return $('_list_'+name+'_' + dbId)
	},
	getAttribute: function(listName, dbId, attrName){
		var div = Lists.getItemDiv(listName, dbId)
		if(div) return div.getAttribute(attrName)
	},
	
	getSelection: function(name){
		if(!$(name+'[]')) return []
		var selection = []
		$A($(name+'[]').options).each(function(option){
			if(option.selected) selection[selection.length] = option.value
		})
		return $A(selection)
	},

	menuOpen: function(e){
		var div = Event.findElement(e, 'DIV')
		if(!div.getAttribute('dbId')){
			if(div.parentNode) div = div.parentNode
			else return
			while(!div.tagName || div.tagName != 'DIV' || !div.getAttribute('dbId')){
				if(div.parentNode) div = div.parentNode
				else return
			}
			if(!div || !div.getAttribute('dbId')) return
		}
		
		if(div.attributes['noContextMenu']) return
		
		var x = Event.pointerX(e)
		var y = Event.pointerY(e)
		
		if(div.getAttribute('list') && $('listMenu_'+div.getAttribute('list'))){
			
			var menu = $('listMenu_'+div.getAttribute('list'))
			menu.show().setStyle({position: 'absolute', left: x + document.body.scrollLeft + 'px', top: y + 'px'})
			
			if(menu.offsetTop + menu.clientHeight > document.body.clientHeight){
				menu.setStyle({top: (y + document.body.scrollTop - menu.clientHeight)+'px'})
			}
			if(menu.offsetLeft + menu.clientWidth > document.body.clientWidth){
				menu.setStyle({left: (x + document.body.scrollLeft - menu.clientWidth)+'px'})
			}
			Lists.openedMenus[Lists.openedMenus.length] = menu
		}
	},
	menuClose: function(){
		for(i = 0; i < Lists.openedMenus.length; i++){
			Element.hide(Lists.openedMenus[i])
		}
		Lists.openedMenus = []
	},
	navCells: {},
	getNavCell: function(id){
		id = id.toString().toLowerCase()
		return Lists.navCells[id]
	}
}

/*--------------------------------------------------------------------------*/
Interface = {
	form: null,
	status: null,
	errors: null,
	returnValue: null,
	dialogArguments: null,
	opener: null,
	saveDone: false,
	closeAfterSave: false,
	
	submit: function(options){
		$$('input[_inserteByInterface]').each(function(el){el.remove()})
		
		if(options['target']) Interface.f().setAttribute('target', options['target'])
		
		Interface.f().submit()
	},
	
	flashUploadGroup: Class.create({
		elements: [],
		size: 0,
		done: 0,
		bitesDone: 0,
		completed: false,
		intervalId: null,
		
		initialize: function(){
			this.elements = []
		},
		
		addElement: function(el){
			this.elements.push(el)
			
			this.size += el.uploadStatus.size
			this.completed = false
			
			var group = this
			//el.onUploadProgress = function(el){group.onElementProgress(group, el)}
			el.onCompleted = function(el){group.onElementCompleted(group, el)}
			el.onFailure = function(el){group.onElementFailure(group, el)}
		},
		uploadNeeded: function(){
			if(!this.elements.length || this.completed) return false
			
			var needed = false
			$A(this.elements).each(function(el){
				if(el.uploadStatus.files.length && !el.uploadStatus.completed) needed = true
			})
			if(!needed){
				this.completed = true
				this.done = 1
			}
			return needed
		},
		getElementNames: function(){
			var names = []
			$A(this.elements).each(function(el){
				names.push(el.name)
			})
			return names
		},
		getSize: function(){
			return this.size
		},
		getDone: function(){
			var bitesDone = 0
			$A(this.elements).each(function(el){
				bitesDone += el.getFlash().getBitesDone()
			})
			return bitesDone > 0 ? Math.round(bitesDone/this.size*100)/100 : 0
		},
		start: function(){
			if(!this.uploadNeeded()){
				if(this.onCompleted) this.onCompleted()
				return false
			}
			
			this.done = 0
			this.bitesDone = 0
			this.completed = false
			
			$A(this.elements).each((function(el){
				el.getFlash().startUpload()
			}).bind(this))
			
			var onProgress = (function(){
				var bitesDone = 0
				$A(this.elements).each(function(el){
					bitesDone += el.getFlash().getBitesDone()
				})
				this.bitesDone = bitesDone
				var done = this.size > 0 && this.bitesDone > 0 ? Math.round(this.bitesDone/this.size*100)/100 : 0
				if(done != this.done){
					this.done = done
					if(this.onProgress) this.onProgress(this.done)
				}
			}).bind(this)
			this.intervalId = setInterval(onProgress, this.size > 1024 * 1024 ? 2000 : 500)
		},
		cancel: function(){
			$A(this.elements).each(function(el){
				el.flashEmbed.cancelUpload()
			})
			this.completed = false
			clearInterval(this.intervalId)
		},
		onElementProgress: function(group, el){
			group.bitesDone = 0
			$A(group.elements).each(function(el){
				if(el.uploadStatus.bitesDone > 0) group.bitesDone += el.uploadStatus.bitesDone
			})
			var done = group.size > 0 && group.bitesDone > 0 ? Math.round(group.bitesDone/group.size*100)/100 : 0
			if(done != this.done){
				this.done = done
				if(group.onProgress) group.onProgress(group.done)
			}
		},
		onElementCompleted: function(group, el){
			var completed = true
			$A(group.elements).each(function(el){
				if(!el.uploadStatus.completed) completed = false
			})
			group.completed = completed
			
			if(group.completed){
				clearInterval(group.intervalId)
				if(group.onCompleted) group.onCompleted()
			}
		},
		onElementFailure: function(group, el){
			clearInterval(group.intervalId)
			alert('upload error')
			if(this.onFailure) this.onFailure()
		}
	}),
	
	save: function(attr){
		if(Interface.onSave) return Interface.onSave()
		
		Interface.saving = true
		
		var f = Interface.f(attr ? (attr.form || attr.f) : null)
		if(!f || f.tagName != 'FORM' || !f.hasClassName('site1InterfaceForm')) return die('no form found')
		
		if(!attr) attr = {}
		
		var script = attr.script
		if(!script){
			script = f.attributes.getNamedItem('action') ? f.attributes.getNamedItem('action').value : ''
			if(!script){
				script = document.location.href
				if(script.indexOf('#') >= 0) script = script.replace(/(.*)(#.*)/, '$1')
				if(script.indexOf('?') >= 0) script = script.replace(/(.*)(\?.*)/, '$1')
			}
		}
		
		Document.showWaitScreen()
		
		var flashUploadGroup = new Interface.flashUploadGroup()
		$A(Form.getInputs(f, 'hidden')).each(function(el){
			if(el.getAttribute('flashUpload')){
				flashUploadGroup.addElement(el)
			}
		})
		
		if(flashUploadGroup.uploadNeeded()){
			flashUploadGroup.onCompleted = function(){Interface.save(attr)}
			var formSize = Form.serialize(f).length
			var uploadSize = flashUploadGroup.getSize()
			var uploadPart = uploadSize / (uploadSize + formSize)
			flashUploadGroup.onProgress = function(done){Document.showProgress(done * uploadPart)}
			
			var secondes = (formSize + uploadSize) / (1024 * 70)
			Document.showProgress(secondes < .5 ? .5 : .5 / secondes)
			flashUploadGroup.start()
			return
		}
		else if(flashUploadGroup.elements.length){
			if(!f.elements['flash-upload-elements']){
				f.insert({bottom: new Element('input', {type: 'hidden', name: 'flash-upload-elements', _inserteByInterface: 1})})
			}
			var flashUploadDescr = {}
			$A(flashUploadGroup.elements).each(function(el){
				flashUploadDescr[el.name] = el.getAttribute('multipleFiles') ? 'multiple' : 'single'
			})
			f.elements['flash-upload-elements'].value = $H(flashUploadDescr).toJSON()
		}
		
		if(Editors && Editors.save) Editors.save()
		TinyMceManager.save()
		
		if(!f.elements.action || !f.elements.action.getAttribute){
			f.insert({bottom: '<input type=hidden name=action value=save _inserteByInterface=1>'})
		}
		this.status = 'saving'
		
		if(f.getAttribute('name') && !f.elements[f.getAttribute('name')]){
			f.insert({bottom: '<input type=hidden name=form value="'+f.getAttribute('name')+'" _inserteByInterface=1>'}) 
		}
		
		Interface.onSaveSuccess = attr.onSaveSuccess
		
		var frameSave = (attr.method == 'frame')
		if(!frameSave){
			$A(Form.getInputs(f, 'file')).each(function(el){
				if(el.value) frameSave = true
			})
		}
		
		if(!frameSave){
			if($('ajaxInFrame')) $('ajaxInFrame').value = ''
			var content = Form.serialize(f)
			if(content.length > 1024 * 100) frameSave = true
		}

		if(frameSave || attr.test){
			if(!$('ajaxInFrame')){
				$(f).insert({bottom: '<input type=hidden name=ajaxInFrame id=ajaxInFrame value=1>', after: '<iframe name=fileSaveFrame style="display: none;"></iframe>'})
			}
			else $('ajaxInFrame').value = 1
			
			if(attr.test) f.setAttribute('target', '_blank')
			else f.setAttribute('target', 'fileSaveFrame')
			f.setAttribute('encoding', 'multipart/form-data')
			f.setAttribute('method', 'post')
			f.setAttribute('action', script)
			f.submit()
		}
		else{
			//Document.trace('script: '+script)
			new Ajax.Request(script, 
			{method: 'post', postBody: content, 
			onComplete: function(transport){
				//Document.trace('status: '+transport.status)
				//Document.trace('content: '+transport.responseText)
				Interface.onAfterSave(f)
			}, onFailure: Interface.onSaveFailure,
			onException: Interface.onException, evalJS: 'force', evalScripts: true
			})
	
			return true
		}
	},
	
	savePart: function(script, parameters){
		if(!script || script == 'self'){
			script = document.location.href
			if(script.match(/\?/)) script = script.replace(/(.*)\?.*/, '$1')
		}
		
		if(Editors && Editors.save) Editors.save()
		TinyMceManager.save()
		
		parameters = Interface.buildQueryArray(parameters)
		
		Interface.saveInProgress = true
		//Document.showWaitScreen()
		new Ajax.Request(script, 
		{method: 'post', postBody: parameters.join('&'), onComplete: Interface.onAfterSave, onFailure: Interface.onSaveFailure, evalJS: 'force', evalScripts: true})
		
	},
	
	callScript: function(script, parameters){
		defaultParameters = Interface.getDefaultElements()
		
		params = []
		if(parameters){
			if(typeof parameters == 'string') params = parameters
			else{
				params = []
				$A(parameters).each(function(param){
					if(typeof param == 'string' && param.match(/=/)) params[params.length] = param
					else if($(param)) params[params.length] = Form.Element.serialize(param)
				})
			}
			params = params.concat(defaultParameters)
		}
		else params = defaultParameters
		
		pars = params.join('&')
		
		settingsPars = Settings.save()
		if(settingsPars) pars += '&' + settingsPars
		
		new Ajax.Request(script, {method: 'get', parameters: pars, evalJS: 'force', evalScripts: true})
	},
	
	onAfterSave: function(f){
		Interface.saveDone = true
		Interface.saving = false
		
		Document.hideWaitScreen()
		Interface.hideErrors()
		
		if(Interface.errors){
			Interface.showErrors(f)
			return false
		}
		else{
			if(Interface.f()){
				Form.setAsDefault(Interface.f())
				Interface.f().reset()
			}
			if(Interface.onSaveSuccess){
				var func = function(){eval(Interface.onSaveSuccess)}
				func()
			}
		}
		
		if(Interface.closeAfterSave) Interface.close()
	},
	
	onSaveFailure: function(){
		Interface.saving = false
		alert('oops... try again in a minute.')
	},
	
	close: function(saveFirst){
		if(!saveFirst && Interface.errors) return die('correct errors first.')
		
		if(Editors && Editors.save) Editors.save()
		TinyMceManager.save()
		
		if(!Form.isDefault(Interface.f())){
			if(saveFirst){
				Interface.closeAfterSave = true
				Interface.save()
				return true
			}// save changes
			else{
				var answ = yesNoCancel('do you want to save the changes?')
				if(answ > 0){
					Interface.closeAfterSave = true
					Interface.save()
					return true
				}
				else if(answ < 0){
					if(Interface.returnValue === null) Interface.returnValue = Interface.saveDone
					Interface.closeDialog()
				}
				else return false
			}
		}
		Interface.closeDialog()
	},
	
	showErrors: function(f){
		f = Interface.f(f)
		if(!Interface.errors) return false
		var errorDivs = {}
		$$('div.error[for]').each(function(el){errorDivs[el.getAttribute('for')] = el})
		
		
		Interface.errors.each(function(error){
			var key = error[0]
			var message = error[1]
			var el = $(f.elements[key])
			if(errorDivs[key]){
				errorDivs[key].update(message).setStyle({cursor: 'pointer'}).show()
				errorDivs[key].onmousedown = function(e){el.focus(); Event.stop(e)}
			}
			else if(el && el.type != 'hidden'){
				errorDivs[key] = new Element('div', {'class': 'error pointer', errorDiv: key}).update(message)
				var nextSib = el.next()
				if(nextSib && nextSib.tagName == 'IMG' || 
					(el.type == 'checkbox' && (nextSib.tagName == 'LABEL' || nextSib.hasClassName('label')))
				){
					nextSib.insert({after: errorDivs[key]})
				}
				else el.insert({after: errorDivs[key]})
				errorDivs[key].onmouseup = function(e){try{el.focus(); el.select(); Event.stop(e)}catch(e){}}
				//if(el.type == 'text') el.addClassName('error')
			}
			else{
				errorDivs[key] = new Element('div', {'class': 'error', errorDiv: key}).update(message)
				if($('_list_'+key)){
					$('_list_'+key).insert({before: errorDivs[key]})
					alert(message)
				}
				else if(f.elements[key] && f.elements[key].realElement){
					f.elements[key].realElement.insert({after: errorDivs[key]})
				}
				else alert(message)
			}
		})
		
		var firstElement = null
		
		f.elements[Interface.errors.keys().first()]
		var errorKeys = Interface.errors.keys()
		for(var i = 0; i < f.elements.length; i++){
			if(errorKeys.indexOf(f.elements[i].name) >= 0){
				firstElement = f.elements[i]
				break
			}
		}
		
		if(firstElement){
			Document.showElement(firstElement)
			try{firstElement.focus(); firstElement.select();}
			catch(e){}
		}
	},
	
	hideErrors: function(){
		$$('*.error[errorDiv]').each(function(el){Element.remove(el)})
		$$('*.error[for]').each(function(el){el.hide()})
	},
	
	contentChanged: function(){
		if(Editors && Editors.save) Editors.save()
		TinyMceManager.save()
		return (!Form.isDefault(Interface.f()))
	},

	currentSections: [],
	loadSection: function(target, script, parameters, options, reload){
		if(!options) options = []
		if(!target || target == self) target = document
		if(target == document || target == parent || target == top){
			targetType = 'document'
		}
		else if($('section_' + target)){
			target = $('section_' + target)
			targetType = 'domelement'
		}
		else if($(target) && $(target).tagName == 'IFRAME'){
			target = $(target)
			targetType = 'iframe'
		}
		else if(parent && parent.$(target) && parent.$(target).tagName == 'IFRAME'){
			target = parent.$(target)
			targetType = 'iframe'
		}
		else if($(target)){
			target = $(target)
			targetType = 'domelement'
		}
		if(!target) die('no element found with property section=' + target)
		if(!reload && target.getAttribute && target.getAttribute('sectionLoaded') > 0) return
		
		if(!script || script == 'self'){
			script = document.location + ''
			if(script.match(/\?/)) script = script.replace(/(.*)\?.*/, '$1')
			script = script.replace(/.*?\/([^\/]*)$/, '$1')
		}
		
		if(parameters !== false) parameters = Interface.buildQueryArray(parameters)
		if(!parameters) parameters = []
		var pars = parameters.join('&')

		if(targetType == 'domelement'){
			var location
			if(script.match(/^https?\:/) || script.match(/^\//)) location = script
			else{
				location = document.location.pathname.replace(/[^\/]+$/, '') + script
				if(!location.match(/^\//)) location = '/' + location
			}
			var queryString = pars.replace(/(action|subAction|tmp\w+|r)=[^&]+&?/ig, '')
			target.setAttribute('script', location)
			target.setAttribute('queryString', queryString)
			target.setAttribute('location', location + '?' + queryString)
		}
		
		this.currentSections[name] = {script: script, parameters: parameters}
		
		if(options.waitScreen) Document.showWaitScreen()
		
		if(targetType == 'domelement'){
			if(options.message){
				Document.indicate(options.message)
				//target.update('&nbsp;')
			}
			else if(!options.hideIndicator) Document.indicate('loading...', {delay: .5})
			
			new Ajax.Request(script, {
				method: 'get',
				parameters: pars+'&holder-type=domelement&r='+r(),
				evalJS: 'force',
				evalScripts: true,
				onSuccess: function(transport){Interface.updateSection(target, transport.responseText)}
			})
			
		}
		else if(targetType == 'iframe'){
			setTimeout(function(){target.src = script + '?holder-type=iframe&' + pars + '&r=' + r()}, 10)
		}
		else if(targetType == 'document'){
			target.location = script + '?r=' + r() + '&holder-type=window&' + pars
		}
		
		if(target.setAttribute) target.setAttribute('sectionLoaded', 1)
	},
	reloadSection: function(name, script, parameters, options){
		Interface.loadSection(name, script, parameters, options, true)
	},
	refreshSection: function(target, options){
		options = (options || {})
		if(!target || target == self) target = document
		if(target == document || target == parent || target == top){
			targetType = 'document'
		}
		else if($('section_' + target)){
			target = $('section_' + target)
			targetType = 'domelement'
		}
		else if($(target) && $(target).tagName == 'IFRAME'){
			target = $(target)
			targetType = 'iframe'
		}
		else if(parent && parent.$(target) && parent.$(target).tagName == 'IFRAME'){
			target = parent.$(target)
			targetType = 'iframe'
		}
		else if($(target)){
			target = $(target)
			targetType = 'domelement'
		}
		if(!target) die('no element found with property section=' + target)
		
		if(options['waitScreen']) Document.showWaitScreen()
		
		if(targetType == 'domelement'){
			var q = target.getAttribute('queryString')
			var script = target.getAttribute('script')
			if(!script) return null
			
			Document.indicate('loading...', {delay: .5})
			
			new Ajax.Request(script, {
				method: 'get',
				parameters: q+'&r='+r(),
				evalJS: 'force',
				evalScripts: true,
				onSuccess: function(transport){Interface.updateSection(target, transport.responseText)}
			})
		}
		else if(targetType == 'iframe'){
			document.frames[name].document.location.replace(document.frames[name].document.location.href.replace(/(action|subAction|tmp\w+|r)=[^&]+&?/ig, ''))
		}
		else if(targetType == 'document'){
			target.location.reload()
		}
		return true
	},
	emptySection: function(name, content){
		var target, targetType
		if(!name || name == 'self'){
			targetType = 'frame'
			target = self.location
		}
		else if($('section_' + name)){
			target = $('section_' + name)
			targetType = 'domelement'
		}
		else if(!name || name == self || name == document){
			target = document
			targetType = 'document'
		}
		else if($(name) && $(name).tagName == 'IFRAME'){
			target = $(name)
			targetType = 'frame'
		}
		if(!target) return

		if(targetType == 'domelement'){
			$(target).removeAttribute('script')
			$(target).removeAttribute('queryString')
			$(target).removeAttribute('location')
		}

		target.setAttribute('sectionLoaded', 0)
		if(targetType == 'domelement'){
			if(!content) content = '&nbsp;'
			Element.update(target, content)
		}
		else if(targetType == 'frame'){
			target.src = '/blank.html'
		}
		else if(targetType == 'document'){
			target.location.replace('/blank.html')
		}
	},
	updateSection: function(target, content){
		var target = $(target)
		Document.hideWaitScreen()
		if(target.tagName.match(/(div|td|span)/i)){
			try{
				target.descendants().invoke('stopObserving')
				target.descendants().reverse().each(function(el){el.remove()})
			}
			catch(e){}
			
			target.update(content)
			document.init(target)
		}
		else if($(name) && $(name).tagName == 'IFRAME'){
			document.frames[name].document.open()
			document.frames[name].document.write(content)
			document.frames[name].document.close()
		}
		else if(parent && parent.$(name) && parent.$(name).tagName == 'IFRAME'){
			parent.document.frames[name].document.open()
			parent.document.frames[name].document.write(content)
			parent.document.frames[name].document.close()
		}
		else die('no element found with property section=' + name)
	},
	clearSection: function(name, content){
		this.emptySection(name, content)
	},
	sectionLoaded: function(name){
		if($('section_' + name)){
			return($('section_' + name).getAttribute('sectionLoaded'))
		}
		else if($(name) && $(name).tagName == 'IFRAME'){
			return ($(name).src && !$(name).src.match(/blank\.html$/))
		}
	},
	
	f: function(f){
		if(f && typeof(f) == 'string'){
			var formEl = null
			$$('form.site1InterfaceForm').each(function(el){
				if(el.attributes.getNamedItem('name') && el.attributes.getNamedItem('name').value == f) formEl = el
			})
			f = formEl
		}
		if(!f || f.tagName != 'FORM' || !f.hasClassName('site1InterfaceForm')) f = null
		else if(f) return f
		
		if(Interface.form) return Interface.form
		
		var f = $$('form.site1InterfaceForm').first()
		if(!f) return null
		
		Interface.form = f
		//Interface.form.observe('submit', function(){return false})
		return Interface.form
	},
	
	getDefaultElements: function(){
		var ar = [], f = Interface.f()
		if(!f) return ar
		$A(f.elements).each(function(element){
			if(element.name && element.attributes['default']){
				ar.push(Form.Element.serialize(element))
			}
		})
		return ar
	},
	
	buildQueryArray: function(parameters){
		parameters = (parameters || [])
		if(typeof(parameters) == 'string') parameters = Array(parameters)
		parameters = $A(Interface.getDefaultElements()).concat($A(parameters))
		
		var keys = {}
		$A(parameters).each(function(param, i){
			if(typeof(param) == 'string' && !param.match(/=/) && $(param)){
				var el = $(param)
				if(el.tagName == 'INPUT' && el.type == 'radio'){
					var form = el.up('form')
					var value = ''
					for(var j = 0; j < form[el.name].length && !value; j++){
						if(form[el.name][j].checked) value = form[el.name][j].value
					}
					parameters[i] = param+'='+value
				}
				else{
					try{parameters[i] = Form.Element.serialize(param)}
					catch(e){parameters[i] = ''}
				}
			}
			else if(typeof(param) == 'string' && !param.match(/=/)){
				if(Document.getRequestVar(param)) parameters[i] = param+'='+Document.getRequestVar(param)
			}
			if(parameters[i].match(/=/)){
				keys[$A(parameters[i].split(/=/)).first()] = i
			}
		})
		
		if(keys['r'] === undefined){
			keys['r'] = parameters.length
			parameters.push('r='+r())
		}
		
		var ret = []
		$H(keys).each(function(par){
			ret.push(parameters[par[1]])
		})
		
		return ret
	},
	
	currDialogReturnValue: null,
	dialog: function(script, parameters, options, dialogVars){
		if(!script) return false
		
		var base = script.replace(/^([htpsfile]+:\/\/[\w\.-]+(\:\d+)?\/)?.*/, '$1')
		if(!base && !script.match(/^\//)){
			script = document.location.pathname.replace(/\/[\w\.]*$/, '/') + script
			if(!script.match(/^\//)) script = '/'+script
		}
		
		var o = (options || {})
		
		if(o.resizable == undefined) o.resizable = 'yes'
		if(o.center == undefined) o.center = 'yes'
		if(o.help == undefined) o.help = 'no'
		if(o.status == undefined) o.status = 'no'
		if(!o.type) o.type = base && document.location.href.indexOf(base) != 0 ? 'modal' : 'inline'
		o.windowType = (o.windowName || script.replace(/[^\w]/, '_'))
		
		if(parameters !== false){
			parameters = Interface.buildQueryArray(parameters)
			if(o.type == 'inline' || !o.type) parameters.push('holder-type=iframe')
			else{
				if(o.type == 'fullWindow') parameters.push('holder-type=window')
				else if(o.type == 'window') parameters.push('holder-type=window')
				else if(o.type == 'modal') parameters.push('holder-type=modalWindow')
			}
			if(o.type != 'window' && o.type != 'fullWindow') parameters.push('dialog-type='+o.type)
		}
		else parameters = []
		
		var url = script + '?' + parameters.join('&')
		
		dialogVars = (dialogVars || o.dialogVars)
		dialogVars = {'document': self, arguments: dialogVars}
		
		if(o.type == 'inline' || !o.type){
			InlineDialogs.open(script, parameters, {width: o.width, height: o.height, fullScreen: o.fullScreen, dialogVars: dialogVars, onClose: o.onClose, title: o.title, returnScript: o.returnScript, fade: o.fade})
		}
		else{
			if(o.width == undefined) o.width = 450
			if(o.height == undefined) o.height = 300
			o.width = parseInt(o.width)+'px'
			o.height = parseInt(o.height)+'px'
			
			var url = parameters.length ? script+'?'+parameters.join('&') : script
			
			if(o.type == 'fullWindow'){
				var win = Document.getTop().window.open(url, o.windowName)
				try{win.focus()}catch(e){}
				return win
			}
			else if(o.type == 'window'){
				win = Document.getTop().window.open(url, o.windowName, 'width='+o.width+',height='+o.height+',resizable='+o.resizable)
				try{win.focus()}catch(e){}
				return win
			}
			else if(o.type == 'modal'){
				if(!o.modeless || !window.showModelessDialog){
					Interface.currDialogReturnValue = null
					try{
						var ret = window.showModalDialog(url, dialogVars, 'dialogWidth:'+o.width+';dialogHeight:'+o.height+';center:'+o.center+';status:'+o.status+';resizable:'+o.resizable+';')
					}
					catch(err){
						alert('Your browser is blocking pop-ups for cms.1site1.nl Try holding the Ctrl-Alt keys while you repeat this action.')
					}
					ret = (ret || Interface.currDialogReturnValue)
					
					Document.focus()
					if(o.onClose) return o.onClose(ret)
					else return ret
				}
				else{
					return top.showModelessDialog(url, dialogVars, 'dialogWidth:'+o.width+';dialogHeight:'+o.height+';center:'+o.center+';status:'+o.status+';resizable:'+o.resizable+';')
				}
			}
		}
	},
	
	setDialogReturnValue: function(val){
		if(Interface.dialogType == 'inline' && Document.parentInScope){
			Interface.inlineDialogObject.returnValue = val
		}
		else if(Interface.dialogType == 'inline' && !Document.parentInScope){
			Interface.currReturnValue = val
		}
		else if(Interface.dialogType == 'modal'){
			Interface.opener.Interface.currDialogReturnValue = val
			window.returnValue = val
		}
	},
	
	returnDialogValue: function(val){
		Interface.setDialogReturnValue(val)
		Interface.closeDialog()
	},
	
	closeDialog: function(){
		if(Interface.dialogType == 'inline'){
			if(Document.parentInScope){
				try{Interface.inlineDialogObject.close()}catch(e){}
			}
			else if(Document.getRequestVar('dialog-return-script')){
				var url = Document.getRequestVar('dialog-return-script') + '?'
				url += 'dialog-id='+Document.getRequestVar('dialog-id')
				url += '&dialog-type=inline'
				if(Interface.currReturnValue){
					url += '&return-value='+escape(JSON.encode(Interface.currReturnValue))
				}
				Document.showWaitScreen()
				document.location.replace(url)
			}
		}
		else window.close()
	},
	
	onException: function(aj, er){
		return
		if(Prototype.Browser.IE) return true
		er = exception(er)
		alert('exceptionn in ' + aj.url + ':\n\r' + er.message + ' (line: '+er.line+')' + '\n\r\n\r' + aj.transport.responseText)
	}
	
}

Interface.dialogType = Document.getRequestVar('dialog-type')

if(Interface.dialogType == 'modal'){
	Interface.dialogArguments = window.dialogArguments['arguments']
	var opener = Interface.opener = window.dialogArguments['document']
}
else if(Interface.dialogType == 'inline' && Document.parentInScope){
	Interface.inlineDialogObject = parent.InlineDialogs.getDialog(Document.getRequestVar('dialog-id'))
	if(!Interface.inlineDialogObject) Interface.inlineDialogObject = parent.InlineDialogs.getDialog('auto')
	
	Interface.dialogArguments = Interface.inlineDialogObject.dialogVars['arguments']
	var opener = Interface.opener = Interface.inlineDialogObject.dialogVars['document']
}
else if(Interface.dialogType == 'inline' && !Document.parentInScope && Document.getRequestVar('dialog-arguments')){
	try{
		Interface.dialogArguments = Document.getRequestVar('dialog-arguments').evalJSON()
	}
	catch(e){
		alert('dialogArguments can only be integers or strings when send to a different domain')
	}
}


/*--------------------------------------------------------------------------*/
if(Prototype.Browser.Gecko){
	document.write('<style type=\"text/css\">.scroller {display: none;}</style>')
}
Scrollers = {
	init: function(el){
		
		el = $(el)
		el.observe('1site1:showel', function(e){
			var showEl = $(e.memo.el)
			if(!showEl || !showEl.descendantOf(el)) return null
			
			var offsetTop = 0, tmpEl = showEl, scrollY = 0
			var scrolledY = el.scrollTop, showElHeight = showEl.getHeight(), scrollerHeight = el.getHeight()
			do{
				if(tmpEl == el || tmpEl == el.offsetParent) break
				offsetTop += (tmpEl.offsetTop || 0)
				tmpEl = tmpEl.offsetParent
			} while (tmpEl)
			
			
			// element above scroller viewport
			if(offsetTop - scrolledY < 0) scrollY = offsetTop - scrolledY - 20
			// element under scroller viewport
			if(offsetTop - scrolledY + showElHeight > scrollerHeight){
				scrollY = offsetTop - scrolledY + showElHeight - scrollerHeight + 20
			}
			
			if(scrollY != 0) el.scrollTop = scrolledY + scrollY
		})
		
		el.observe('1site1:go', function(e){
			el.scrollTop = el.scrollTop + (e.memo == 'down' ? 20 : -20)
		})
		
		if(Prototype.Browser.Gecko){
			var container = el.up()
			if(container.tagName == 'TD') container.setAttribute('valign', 'top')
			var dim = container.getDimensions()
			if(dim.height){
				dim.height -= (el.offsetTop || 0) + 1
				dim.height -= parseInt((el.getStyle('border-top-width') || 0))
				dim.height -= parseInt((el.getStyle('border-bottom-width') || 0))
				el.setStyle({height: dim.height+'px'})
				if(el.hasClassName('xscroll')){
					dim.width -= (el.offsetLeft || 0) + 1
					el.setStyle({width: dim.width+'px'})
				}
			}
			el.setStyle({display: 'block'})
		}
	},
	reset: function(el){
		if(!Prototype.Browser.Gecko) return false
		var scrollers
		if(!el) scrollers = $$('div.scroller')
		else if(hasClassName(el, 'scroller')) scrollers = $A([el])
		else scrollers = $(el).select('div.scroller')
		
		scrollers.each(function(el){
			el.setStyle({display: 'none'})
		})
		scrollers.each(function(el){
			Scrollers.init(el)
		})
	},
	resize: function(){
		Scrollers.reset()
	}
}

/*--------------------------------------------------------------------------*/
GroupHeadings = {
	headings: [],
	
	init: function(tbody){
		if(tbody.getAttribute('initiated')) return false
		tbody = $(tbody)
		
		var name = tbody.getAttribute('headingName')
		if(!name) die('groupHeading has no name')
		GroupHeadings.headings[name] = tbody

		var title = tbody.getAttribute('groupHeadingTitle')
		var state = (tbody.getAttribute('state') || Settings.getSetting('ghead:'+name))
		if(!state) state = tbody.getAttribute('defaultState') ? tbody.getAttribute('defaultState') : 'opened'
		
		var heading = $(tbody.parentNode.insertBefore(new Element('tbody').addClassName('groupHeading'), tbody))
		
		heading.update('<tr><td><table class=table cellpadding=0 cellspacing=0 border=0><tr><td class=arrow></td><td class=text>'+title+'</td></tr></table></td></tr>')
		
		tbody.observe('my:open', function(e){
			tbody.className = 'groupHeadingTbodyOpened'
			heading.addClassName('groupHeadingOpened').removeClassName('groupHeadingHover')
			tbody.setAttribute('state', 'opened')
			Settings.setSetting('ghead:'+name, 'opened')
			
			if(tbody.getAttribute('onOpen')){
				try{(function(){eval(tbody.getAttribute('onOpen'))}).apply(tbody)}
				catch(e){ErrorHandler.throwError(e, tbody.getAttribute('onOpen'))}
			}
		})
		
		tbody.observe('my:close', function(e){
			tbody.className = 'groupHeadingTbody'
			heading.removeClassName('groupHeadingOpened')
			tbody.setAttribute('state', 'closed')
			Settings.setSetting('ghead:'+name, 'closed')
			
			if(tbody.getAttribute('onClose')){
				try{(function(){eval(tbody.getAttribute('onClose'))}).apply(tbody)}
				catch(e){ErrorHandler.throwError(e, tbody.getAttribute('onClose'))}
			}
		})
		
		tbody.observe('my:toggle', function(e){
			if(tbody.getAttribute('state') == 'opened') tbody.fire('my:close')
			else tbody.fire('my:open')
		})
		
		heading.observe('mousedown', function(e){
			tbody.fire('my:toggle')
			Event.stop(e)
		}).observe('dblclick', function(e){Event.stop(e)})
		heading.observe('mouseover', function(){
			if(tbody.getAttribute('state') != 'opened') heading.addClassName('groupHeadingHover')
		}).observe('mouseout', function(){
			heading.removeClassName('groupHeadingHover')
		})
		
		tbody.setAttribute('initiated', 1)

		if(state == 'opened') tbody.fire('my:open')
	},
	
	close: function(name){
		var tbody = GroupHeading.headings[name]
		if(tbody) tbody.fire('my:close')
	},
	
	open: function(name, init){
		var tbody = GroupHeading.headings[name]
		if(tbody) tbody.fire('my:open')
	}
}

/*--------------------------------------------------------------------------*/
TabGroups = {
	currentTab: [],
	
	init: function(table, groupIndex){
		table = $(table)
		
		// group name
		var tabGroupName = table.getAttribute('tabName')
		if(!tabGroupName){
			tabGroupName = 'tabGroup' + groupIndex
			table.setAttribute('tabName', tabGroupName)
		}
		table.setAttribute('id', 'tabGroup_' + tabGroupName)
		
		var tabs = table.select('tbody.tabbody[!tabgroup]')
		if(!tabs.length) die('no tabs in tab group')
		
		// tabs cell
		var tabsHtml = '<table class="tabsTable" border=0 cellspacing=0 cellpadding=0><tr>'
		
		// get tabFocus
		if(table.getAttribute('focusIndex')) var tabFocus = table.getAttribute('focusIndex') * 1
		else if(!table.attributes['noMemory']){
			var tabFocus = Settings.getSetting('tabf:'+tabGroupName) * 1
			table.setAttribute('noMemory', 0)
		}
		else{
			var tabFocus = 0
			table.setAttribute('noMemory', 1)
		}
		
		// tabs
		var tabList = []
		var index = 0
		var defaultTab = 0
		tabs.each(function(tbody){
			if(tbody.parentNode != table) return
			var tabTitle = tbody.getAttribute('tabTitle')
			if(!tabTitle) tabTitle = 'tab ' + index
			tbody.setAttribute('tabGroup', tabGroupName)
			tbody.setAttribute('tabIndex', index)
			tbody.id = 'tab_' + tabGroupName + '_' + index
			tabList[index] = {'index': index, 'title': tabTitle}
			if(tbody.getAttribute('defaultTab')) defaultTab = index
			index++
		})// tabs
		
		if(tabFocus && !$('tab_' + tabGroupName + '_' + tabFocus)) tabFocus = 0
		
		if(!tabFocus && tabFocus != 0 && defaultTab) tabFocus = defaultTab
		else if(!tabFocus) tabFocus = 0
		
		tabsHtml += '<td class="tabEmpty" valign=bottom><div><img src="'+grS()+'/graphics/shim.gif" width=12 height=1></div></td>'
		
		$A(tabList).each(function(tab, index){
			tabsHtml += '<td tabGroup="'+tabGroupName+'" index='+index+' id="tabButton_'+tabGroupName+'_'+index+'" class="tab'+(index == 0 ? ' tabFirst' : '')+'" nowrap valign=bottom><div><div>'+tab['title']+'</div></div></td>'
		})
		tabsHtml += '<td class="tabEmpty width100" valign=bottom><div>&nbsp;</div></td>'
		
		tabsHtml += '</tr></table>'
		
		table.insert({before: '<table class="width100 height100" style="display: none;" border=0 cellpadding=0 cellspacing=0><tr><td class=tabsCell valign=bottom></td></tr><tr><td class="height100"></td></tr></table>'})
		
		var wrapper = $(table.previousSibling)
		var wrapper1 = wrapper.down('td')
		var wrapper2 = wrapper.down('td', 1)
		
		wrapper1.update(tabsHtml)
		wrapper2.insert({top: table})
		
		wrapper.show()
		
		wrapper1.select(['td.tab', 'td.tabActive']).each(function(cell){
			cell.observe('mouseover', function(e){TabGroups.over(e, cell)})
			cell.observe('mouseout', function(e){TabGroups.out(e, cell)})
			cell.observe('click', function(e){TabGroups.click(e, cell)})
			cell.observe('mousedown', function(e){Event.stop(e)})
		})
		
		onLoadCollection.add(function(){TabGroups.open(tabGroupName, tabFocus)})
	},
	
	open: function(tabGroupName, index){
		var tbody = $('tab_' + tabGroupName + '_' + index)
		var cell = $('tabButton_' + tabGroupName + '_' + index)
		
		if(TabGroups.currentTab[tabGroupName] > 0 || TabGroups.currentTab[tabGroupName] == 0){
			TabGroups.close(tabGroupName, TabGroups.currentTab[tabGroupName])
		}
		
		tbody.className = 'tabbodyActive'
		cell.addClassName('tabActive').removeClassName('tabOver')
		TabGroups.currentTab[tabGroupName] = index
		if($('tabGroup_'+tabGroupName).getAttribute('noMemory') == 0){
			Settings.setSetting('tabf:'+tabGroupName, index)
		}
		
		Scrollers.reset(tbody)
		if(tbody.getAttribute('onOpen')){
			var func = function(){
				eval(tbody.getAttribute('onOpen'))
			}
			try{func.apply(tbody)}
			catch(e){ErrorHandler.throwError(e, tbody.getAttribute('onOpen'))}
		}
	},
	
	close: function(tabGroupName, index){
		var tbody = $('tab_' + tabGroupName + '_' + index)
		var cell = $('tabButton_' + tabGroupName + '_' + index)
		
		tbody.className = 'tabbody'
		cell.removeClassName('tabActive').removeClassName('tabOver')
		
		if(tbody.getAttribute('onClose')){
			var func = function(){
				eval(tbody.getAttribute('onClose'))
			}
			try{func.apply(tbody)}
			catch(e){ErrorHandler.throwError(e, tbody.getAttribute('onClose'))}
		}
	},
	
	over: function(e, td){
		if(td.className != 'tabActive') td.addClassName('tabOver')
	},
	out: function(e, td){
		if(td.className != 'tabActive') td.removeClassName('tabOver')
	},
	click: function(e, td){
		var tabGroupName = td.getAttribute('tabGroup')
		var index = td.getAttribute('index')
		if(TabGroups.currentTab[tabGroupName] != index) TabGroups.open(tabGroupName, index)
	},
	getOpenedIndex: function(tabGroupName){
		return TabGroups.currentTab[tabGroupName]
	}
	
}

var Cookie = {
	set: function(name, value, daysToExpire, path, domain, secure){
		//alert(name+': '+value)
		var expire = '';
		if(daysToExpire != undefined){
			var d = new Date()
			d.setTime(d.getTime() + (86400000 * parseFloat(daysToExpire)))
			expire = '; expires=' + d.toGMTString()
		}
		return (document.cookie = escape(name) + '=' + escape(value || '') + expire + (path ? ';path='+path : ';path=/') + (domain ? ';domain='+domain : '') + (secure ? ';secure' : ''))
	},
	get: function(name){
		var cookie = document.cookie.match(new RegExp('(^|;)\\s*' + escape(name).gsub('.', '\\.') + '=([^;\\s]*)'))
		return (cookie ? unescape(cookie[2]) : undefined)
	},
	getKeys: function(){
		var list = []
		$A(document.cookie.split(/\s*;\s*/)).each(function(cookie){
			cookie = cookie.split(/\s*=\s*/)
			var key = unescape(cookie[0])
			list.push(key)
		})
		return list
	},
	erase: function(name){
		var cookie = Cookie.get(name) || true;
		Cookie.set(name, '', -1, '/')
		return cookie;
	},
	
	accepted: false,
	rejected: false,
	accept: function(){
		if(Cookie.accepted) return true
		else if(Cookie.rejected) return false
		
		var accept = null
		
		if(typeof navigator.cookieEnabled == 'boolean') accept = navigator.cookieEnabled
		else{
			Cookie.set('_test', '1');
			accept = (Cookie.erase('_test') = '1')
		}
		
		if(accept) Cookie.accepted = true
		else Cookie.rejected = true
		
		return accept
	}
};

/*--------------------------------------------------------------------------*/
Settings = {
	paths: new Hash(),
	changes: false,
	currentPath: null,
	cookieHoursToLive: 12,
	
	setSetting: function(name, value, path){
		if(path == 'main') path = '/'
		name = name.toString()
		if(!name) return false
		
		if(!path) path = Settings.getPath()
		path = Settings.cleanPath(path)
		
		if(value || value == 0){
			// save setting
			var pathSettings = Settings.paths.get(path)
			if(!pathSettings){
				var pathSettings = new Hash()
				Settings.paths.set(path, pathSettings)
			}
			
			pathSettings.set(name, value)
			Settings.changed = true
			Settings.savePathSettings(pathSettings, path)
			return true
		}
		else{
			// delete setting
			var pathSettings = Settings.paths.get(path)
			var currValue = pathSettings ? pathSettings.get(name) : null
			if(currValue){
				pathSettings.unset(name)
				Settings.changed = true
				Settings.savePathSettings(pathSettings, path)
				return true
			}
		}
	},
	savePathSettings: function(sett, path){
		if(sett.keys().length < 1) Cookie.erase('intsett:'+path)
		else if(Cookie.get('intsett:'+path) != sett.toJSON()){
			Cookie.set('intsett:'+path, sett.toJSON(), 1/24*Settings.cookieHoursToLive, path)
		}
	},
	
	getSetting: function(name, path){
		if(path == 'main') path = '/'
		path = (path || Settings.getPath())
		path = Settings.cleanPath(path)
		
		var pathSettings = Settings.paths.get(path)
		var value = pathSettings ? pathSettings.get(name) : ''
		if(!value && value != 0) value = ''
		return value
	},
	
	getPath: function(){
		if(Settings.currentPath) return Settings.currentPath
		
		Settings.currentPath = Settings.cleanPath(document.location.pathname)
		
		return Settings.currentPath
	},
	cleanPath: function(path){
		path = path.replace(/[\w\.-]+$/, '')
		if(!path.match(/\/$/)) path += '/'
		if(!path.match(/^\//)) path = '/' + path
		return path
	},
	
	loadPath: function(path){
		path = Settings.cleanPath(path)
		var json = Cookie.get('intsett:'+path)
		if(json && json.toString().isJSON()){
			//Cookie.set('intsett:'+path, json)
			Settings.paths.set(path, new Hash(json.toString().evalJSON()))
		}
	},
	
	load: function(){
		var keys = $A(Cookie.getKeys())
		keys.each(function(key){
			var path = key.match(/^intsett:[\w\/_]+$/) ? key.replace(/^intsett:([\w\/_]+)$/, '$1') : null
			if(path) Settings.loadPath(Settings.cleanPath(path))
		})
		
		// set settings with special cookies
		keys.each(function(key){
			if(key.match(/^intsett_set_\d+$/)){
				var data = Cookie.get(key).toString().evalJSON()
				Settings.setSetting(data.name, data.value, data.path)
				Cookie.erase(key)
			}
		})
		Settings.checkCookieTimer()
		new PeriodicalExecuter(Settings.checkCookieTimer, Settings.cookieHoursToLive*60*60/4)
	},
	
	save: function(){
		return ''
	},
	
	checkCookieTimer: function(){
		if(!Cookie.get('intsett_cookietimer')){
			$A(Cookie.getKeys()).each(function(key){
				var path = key.match(/^intsett:[\w\/_]+$/) ? key.replace(/^intsett:([\w\/_]+)$/, '$1') : null
				if(path){
					Cookie.set(key, Cookie.get(key), 1/24*Settings.cookieHoursToLive, path)
					Cookie.set('intsett_cookietimer', 1, 1/12*Settings.cookieHoursToLive/2, path)
				}
			})
			
		}
	}
}
Settings.load()

/*--------------------------------------------------------------------------*/
Buttons = {
	all: {},
	radioGroup: {},
	
	init: function(div){
		// init one button
		
		var div = $(div)
		
		var name = (div.getAttribute('buttonName') || Buttons.all.length)
		Buttons.all[name] = div
		
		div.behaviour = (div.getAttribute('buttonBehaviour') || 'default')
		
		if(div.behaviour == 'radio' && div.getAttribute('radioGroup')){
			var groupName = div.getAttribute('radioGroup')
			if(!Buttons.radioGroup[groupName]) Buttons.radioGroup[groupName] = []
			Buttons.radioGroup[groupName].push(div)
		}
		
		var html = div.innerHTML.replace(/[\r\n]/g, ' ')
		
		var icon = {src: html.match(/.*<img.*/i) ? html.replace(/.*src="([^"]+)".*/i, '$1') : div.getAttribute('icon')}
		if(icon.src && icon.src.match(/^\w+$/)) icon.src = grS()+'/icons/'+icon.src+'_16.png'
		if(!icon.src) icon = null
		
		var text = (div.innerText || div.textContent) || ''
		
		var type = div.hasClassName('button') ? 'button' : 'link'
		
		if(type == 'button'){
			div.update('<div><div><table cellspacing=0 cellpadding=0 border=0><tr>'+(icon ? '<td class=iconCell><img class="icon" src="'+icon.src+'"></td>' : '')+(text ? '<td class=text>'+text+'</td>' : '')+'</tr></table></div></div>')
		}
		else{
			div.update('<table cellspacing=0 cellpadding=0 border=0><tr><td class=iconCell>'+(icon ? '<img class="icon" src="'+icon.src+'">' : '')+(text ? '</td><td class=text>'+text+'</td>' : '')+'</tr></table>')
		}
		
		div.observe('1site1:over', function(){
			if(div.status != 'off') return false
			div.addClassName(type == 'button' ? 'buttonOver' : 'linkOver')
			div.status = 'over'
		})
		div.observe('1site1:out', function(){
			if(div.status != 'over') return false
			div.removeClassName(type == 'button' ? 'buttonOver' : 'linkOver')
			div.status = 'off'
		})
		div.observe('1site1:down', function(){
			if(div.status != 'over' && div.status != 'off') return false
			
			div.removeClassName(type == 'button' ? 'buttonOver' : 'linkOver')
			div.addClassName(type == 'button' ? 'buttonDown' : 'linkDown')
			
			div.status = 'down'
			
			if(div.resetTimeoutId) clearTimeout(div.resetTimeoutId)
			
			div.resetTimeoutId = setTimeout(function(){
				try{div.fire('1site1:up')}catch(e){}
			}, 2000)
		})
		div.observe('1site1:up', function(){
			if(div.status != 'down') return false
			
			div.removeClassName(type == 'button' ? 'buttonOver' : 'linkOver')
			div.removeClassName(type == 'button' ? 'buttonDown' : 'linkDown')
		})
		div.observe('1site1:disable', function(){
			div.removeClassName(type == 'button' ? 'buttonOver' : 'linkOver')
			div.removeClassName(type == 'button' ? 'buttonDown' : 'linkDown')
			div.addClassName(type == 'button' ? 'buttonDisabled' : 'linkDisabled')
			
			div.status = 'disabled'
			
			if(div.behaviour == 'radio'){
				var groupName = div.getAttribute('radioGroup')
				if(!groupName || !Buttons.radioGroup[groupName]) return
				$A(Buttons.radioGroup[groupName]).each(function(gdiv){
					if(gdiv != div) gdiv.fire('1site1:reset')
				})
			}
		})
		div.observe('1site1:reset', function(){
			if(!div.status == 'off') return
			
			div.removeClassName(type == 'button' ? 'buttonOver' : 'linkOver')
			div.removeClassName(type == 'button' ? 'buttonDown' : 'linkDown')
			div.removeClassName(type == 'button' ? 'buttonDisabled' : 'linkDisabled')
			
			div.status = 'off'
		})
		div.act = function(e){
			if(typeof(div.action) == 'function') div.action(e)
			else{
				var action = div.getAttribute('action')
				if(action){
					var func = (function(e){
						eval(action)
					}).bind(div)
					
					func(e)
				}
			}
		}
		div.observe('1site1:act', function(e){
			var e = e.memo.e
			div.act(e)
		})
		div.observe('1site1:click', function(e){
			if(!e.memo.actionDone && div.behaviour != 'fast') div.act(e.memo.e)
			
			if(div.status == 'disabled') return
			
			if(div.behaviour == 'default'){
				if(div.resetTimeoutId) clearTimeout(div.resetTimeoutId)
				div.status = 'down'
				try{
					setTimeout(function(){
						if(div.status == 'down') div.fire('1site1:reset')
					}, 400)
				}
				catch(er){}
			}
			else if(div.behaviour == 'once') div.fire('1site1:disable')
			else if(div.behaviour == 'fast') div.fire('1site1:reset')
			else if(div.behaviour == 'radio') div.fire('1site1:disable')
		})
		
		Event.observe(div, 'mouseover', function(e){div.fire('1site1:over')})
		Event.observe(div, 'mouseout', function(e){div.fire('1site1:out')})
		Event.observe(div, 'click', function(e){
			if(div.status == 'disabled') return
			if(div.behaviour != 'fast') div.act(e)
			div.fire('1site1:click', {e: e, actionDone: true})
		})
		Event.observe(div, 'mousedown', function(e){
			Event.stop(e)
			if(div.status == 'disabled') return
			if(div.behaviour == 'fast'){
				div.fire('1site1:down')
				div.act(e)
			}
			else div.fire('1site1:down')
		})
		Event.observe(div, 'dblclick', function(e){
			Event.stop(e)
			if(div.status == 'disabled') return
			if(div.behaviour != 'fast') div.act(e)
			div.fire('1site1:click', {e: e, actionDone: true})
		})
		
		div.status = (div.getAttribute('buttonStatus') || 'off')
		if(div.status == 'disabled') div.fire('1site1:disable')
		
		if(Prototype.Browser.IE){
			$A(div.getElementsByTagName('*')).each(function(el){el.onselectstart = function(){return false}})
		}
	},
	
	act: function(name, e){
		var div = Buttons.all[name]
		if(div) div.act(e)
	},
	
	reset: function(){
		for(i = 0; i < arguments.length; i++){
			var div = Buttons.all[arguments[i]]
			if(div) div.fire('1site1:reset')
		}
	},
	
	disable: function(){
		for(i = 0; i < arguments.length; i++){
			var div = Buttons.all[arguments[i]]
			if(div) div.fire('1site1:disable')
		}
	},
	
	setText: function(name, text){
		if(!name || !text) return false
		var div = Buttons.all[name]
		if(div && div.down('td.text')) div.down('td.text').update(text)
	},
	getText: function(name){
		if(!name) return ''
		var div = Buttons.all[name]
		if(div && div.down('td.text')) return Prototype.Browser.Gecko ? div.down('td.text').textContent : div.down('td.text').innerText
		else return ''
	},
	
	hide: function(){
		for(i = 0; i < arguments.length; i++){
			var div = Buttons.all[arguments[i]]
			if(div) div.hide()
		}
	},
	show: function(){
		for(i = 0; i < arguments.length; i++){
			var div = Buttons.all[arguments[i]]
			if(div) div.show()
		}
	}
}
Buttons.enable = Buttons.reset

/*--------------------------------------------------------------------------*/
Calendars = {
	currCalendar: null,
	currCalDate: null,
	cal: null,
	
	weekDays: Array('Sun','Mon','Tue','Wed','Thu','Fri','Sat'),
	months: Array('Januari','Februari','Maart','April','Mei','Juni','Juli','Augustus','September','Oktober','November','December'),
	
	init: function(el){
		if(el.getAttribute('calendarInitiated')) return false
		
		el = $(el)
		if(!el || el.tagName != 'INPUT') return die('form element not found in Calendar.create()')
		el.id = el.name
		
		if(el.value.match(/ \d\d:\d\d/)){
			new Insertion.Before(el, '<table calendarName='+el.name+' id=calendar_'+el.name+' width=130 border=0 cellpadding=1 cellspacing=0 bgcolor=white style="border: 1px solid #7B9EBD;"><tr><td class=dateString width=75 style="padding-left: 5px; cursor: default;"></td><td width=16><img src="'+grS()+'/graphics/calendar.open.gif" width=16 height=16 style="margin-top: 1px; margin-right: 1px; cursor: pointer;"></td><td width=30 class=timeString></td></tr></table>')
		}
		else{
			new Insertion.Before(el, '<table calendarName='+el.name+' id=calendar_'+el.name+' width=95 border=0 cellpadding=1 cellspacing=0 bgcolor=white style="border: 1px solid #7B9EBD;"><tr><td class=dateString width=100% style="padding-left: 5px; cursor: default;"></td><td width=16><img src="'+grS()+'/graphics/calendar.open.gif" width=16 height=16 style="margin-top: 1px; margin-right: 1px; cursor: pointer;"></td></tr></table>')
		}
		
		var table = $('calendar_'+el.name)
		table.down('td.dateString').update(this.dateToString(el.value))
		if(el.value.match(/ \d\d:\d\d/)){
			table.down('td.timeString').update(this.dateToTime(el.value)).setAttribute('timeCell', 1)
		}
		Event.observe(table, 'click', Calendars.open, false)
		
		el.setAttribute('calendarInitiated', 1)

	},
	
	dateToString: function(date){
		if(!date.match(/^\d{4}-\d{1,2}-\d{1,2}/) || date.match(/^0000-00-00/)) return ''
		return date.substr(8, 2) + '-' + date.substr(5, 2) + '-' + date.substr(0, 4)
	},
	
	dateToTime: function(date){
		if(!date.match(/ \d\d:\d\d/)) return ''
		return date.replace(/.* (\d\d:\d\d).*/, '$1')
	},
	
	open: function(e){
		if($('calendarTable')){
			Calendars.hide()
			return
		}
		
		var td = Event.findElement(e, 'TD')
		if(td.getAttribute('editModus')) return
		if(td.getAttribute('timeCell')){
			Element.update(td, '<input style="border: 0px; padding: 0px; margin: 0px; width: 30px; font-family: Arial; font-size: 11px;" value="'+td.innerHTML+'">')
			td.setAttribute('editModus', 1)
			var input = td.firstChild
			Event.observe(input, 'keydown', function(e){
				e = e || event
				var iCode = (e.keyCode || e.charCode)
				if(( iCode >= 48 && iCode <= 57 )		// Numbers
					|| (iCode >= 37 && iCode <= 40)		// Arrows
					|| (iCode >= 96 && iCode <= 105)		// Keypad numbers
					|| iCode == 8		// Backspace
					|| iCode == 46		// Delete
					|| iCode == 16		// Shift
					|| iCode == 186		// Colon
					|| iCode == 110 || iCode == 190		// Dot
				){
					return true
				}
				else{
					return false
				}
			})
			Event.observe(input, 'keyup', function(e){
				e = e || event
				var el = Event.element(e)
				el.value = el.value.replace(/[^\d]/g, ':')
				if(el.value.match(/\d+:\d+/)){
					
				}
			})
			Event.observe(input, 'blur', function(e){
				e = e || event
				var el = Event.element(e)
				var table = Event.findElement(e, 'TABLE')
				
				el.value = el.value.replace(/^(\d)\:/, '0$1:')
				el.value = el.value.replace(/\:(\d)$/, ':0$1')
				if(el.value.match(/^\d\d$/)) el.value = el.value + ':00'
				else if(el.value.match(/^\d{4}$/)){
					var hour = el.value.replace(/^(\d\d).*$/, '$1')
					var min = el.value.replace(/^.*(\d\d)$/, '$1')
					el.value = hour + ':' + min
				}
				
				if(!el.value.match(/^\d{1,2}\:\d{1,2}$/)) el.value = '00:00'
				
				var hour = el.value.replace(/^(\d\d).*/, '$1')
				var min = el.value.replace(/.*(\d\d)$/, '$1')
				if(hour > 23) hour = '23'
				if(min > 59) min = '00'
				var time = hour + ':' + min
				
				el.parentNode.removeAttribute('editModus')
				el.parentNode.innerHTML = time
				
				var el = $(table.getAttribute('calendarName'))
				var currDate = el.value.replace(/^(\d+-\d+-\d+).*$/, '$1')
				el.value = currDate + ' ' + time
			})
			input.select()
			return
		}
		
		var table = Event.findElement(e, 'TABLE')
		Calendars.currCalendar = table.attributes.calendarName.value
		
		var monthSelector = '<select name="calendarMonthSelector" id="calendarMonthSelector" style="font-size: 10px; font-family: Arial;" onChange="Calendars.goMonth(this.selectedIndex)">'
		for(var i = 0; i < 12; i++){
			monthSelector += '<option value="' + i + '">' + Calendars.months[i] +'</option>'
		}
		monthSelector += '</select>'
		
		var html = $A([
		'<table id=calendarTable class=calendarTable border="0" cellspacing="0" cellpadding="0">',
		'<tr><td class=headingColor style="padding: 3px; padding-bottom: 0px;" align=right><img src="'+grS()+'/graphics/close.gif" width=10 height=8 onClick=Calendars.hide() style="cursor: pointer;"></td></tr>',
		'<tr><td class="heading">',
		'<table width="100%" border="0" cellspacing="0" cellpadding="0"><tr>',
		'<td><img src="'+grS()+'/graphics/calendar.prev.gif" width="18" height="18" style="cursor: pointer;" onMouseUp="Calendars.prevMonth()"></td>',
		'<td>'+monthSelector+'</td>',
		'<td width=100%><img src="'+grS()+'/graphics/calendar.next.gif" width="18" height="18" style="cursor: pointer;" onMouseUp="Calendars.nextMonth()"></td>',
		'<td align="right"><input type="text" name="calendarYear" id="calendarYear" style="font-size: 10px; font-family: Arial; width: 35px;" size="5" onKeyUp="if(this.value.length == 4)Calendars.goYear(0)" onFocus="this.select()"></td>',
		'<td width="23"><img src="'+grS()+'/graphics/calendar.year.up.gif" width="18" height="9" style="cursor: pointer;" onMouseUp="Calendars.goYear(1)"><br><img src="'+grS()+'/graphics/calendar.year.down.gif" width="18" height="9" style="cursor: pointer;" onMouseUp="Calendars.goYear(-1)"></td>',
		'</tr></table></td></tr>',
		'<tr><td height="134" valign="top" bgcolor="#FFFFFF" id="calendarCell" style="background-color: white;">&nbsp;</td></tr>',
		'<tr><td class="headingColor padding"><table width="100%" border="0" cellspacing="0" cellpadding="1"><tr><td><input type="button" value="today" onClick="Calendars.setToToday()" style="font-family: Arial; font-size: 11px;"></td>',
		'<td align=right><input type="button" value="none" style="font-family: Arial; font-size: 11px;" onClick="Calendars.close(); this.blur()"></td></tr></table>'
		])
		
		$(document.body).insert({top: html.join("\n")})
		
		var pos = Position.cumulativeOffset(table)
		var dim = Element.getDimensions(table)
		pos[1] += dim['height']
		$('calendarTable').setStyle({left: pos[0], top: pos[1]})
		
		Calendars.setCalendar()
		
		var calDim = Element.getDimensions($('calendarTable'))
		if(document.body.clientHeight < pos[1] + calDim['height'])
			$('calendarTable').style.top = document.body.clientHeight - calDim['height']

		if(document.body.clientWidth < pos[0] + calDim['width'])
			$('calendarTable').style.left = document.body.clientWidth - calDim['width']

	},
	
	setCalendar: function(year, month){
		
		var now = new Date()
		
		var curDBDate = $F(Calendars.currCalendar)
		
		var currDate
		if(curDBDate && !curDBDate.match(/^0000-00-00/)){
			currDate = new Date()
			currDate.setYear(curDBDate.substr(0, 4))
			currDate.setMonth(curDBDate.substr(5, 2) * 1 - 1)
			currDate.setDate(curDBDate.substr(8, 2))
		}
		
		if(!year || (!month && month != 0)){
			if(currDate){
				year = currDate.getFullYear()
				month = currDate.getMonth()
			}
			else{
				year = now.getFullYear()
				month = now.getMonth()
			}
		}
		
		var cal = new Date()
		cal.setFullYear(year, month, 1)
		
		Calendars.cal = cal
		
		var html
		
		$('calendarMonthSelector').selectedIndex = cal.getMonth()
		
		$('calendarYear').value = cal.getFullYear()
		
		html = '<table border=0 cellspacing=1 cellpadding=0 align=center style="margin: 1px; width: 185px">'
		html += '<tr>'

		for(i = 0; i < 7; i++)
			html += '<td width=14% align=center style="'+(now.getDay() == i ? 'color: black; ' : 'color: #666666; ')+'cursor: default; font-size: 12px; font-family: Arial; font-weight: bold;" onselectstart="return false">' + this.weekDays[i] + '</td>'
		
		html += '</tr><tr><td colspan=7 align=center style="background-color: black; height: 1px;" onselectstart="return false"></td></tr><tr>'
		html += '</tr><tr><td colspan=7 align=center style="height: 4px;" onselectstart="return false"></td></tr><tr>'
		
		for(i = 0 - cal.getDay(); i  < 0; i++)
			html += '<td width=14% align=center onselectstart="return false;">&nbsp;</td>'
		
		for(i=0; i < 33; i++){
			if(cal.getDate() > i ){
				week_day = cal.getDay();
			
				if(week_day == 0)
					html += '<tr>';
			
				if(week_day != 7){
					var day = cal.getDate()
					if(currDate && currDate.getDate() == cal.getDate() && currDate.getMonth() == cal.getMonth() && currDate.getFullYear() == cal.getFullYear()) cellClass = 'calendarCellSelectedDay'
					else if(now.getDate() == cal.getDate() && now.getMonth() == cal.getMonth() && now.getFullYear() == cal.getFullYear()) cellClass = 'calendarCellToday'
					else cellClass = 'calendarCell'
					html += '<td class=' + cellClass + ' width=14% align=center onClick="Calendars.close(\'' + cal.getFullYear() + '-' + (cal.getMonth() + 1) + '-' + cal.getDate() + '\')">' + day + '</td>'
				}
		
				if(week_day == 7)
					html += '</tr>'
			}
		
			cal.setDate(cal.getDate() + 1)
		
		}// end for loop
		
		html += '</td></tr></table>'
		Element.update($('calendarCell'), html)
	},

	close: function(date){
		date = this.dateToDBForm(date)
		
		var currDate = $F(Calendars.currCalendar).replace(/^(\d+-\d+-\d+).*$/, '$1')
		var currTime = ''
		if($F(Calendars.currCalendar).match(/ \d\d\:\d\d/)){
			 currTime = $F(Calendars.currCalendar).replace(/^.*(\d\d\:\d\d)$/, '$1')
		}
		
		var changed = date != currDate
		$(Calendars.currCalendar).value = date
		if(currTime) $(Calendars.currCalendar).value += ' ' + currTime
		
		if(changed && $(Calendars.currCalendar).attributes.onCh){
			try{(function(){eval($(Calendars.currCalendar).attributes.onCh.value)}).apply(Calendars.currCalendar)}
			catch(e){ErrorHandler.throwError(e, $(Calendars.currCalendar).attributes.onCh.value)}
		}
		
		table = $('calendar_'+Calendars.currCalendar)
		Element.update(table.firstChild.firstChild.firstChild, this.dateToString(date))
		
		Calendars.hide()
	},
	
	hide: function(){
		Calendars.currCalendar = Calendars.cal = null
		Element.remove($('calendarTable'))
	},
	
	goMonth: function(month){
		var year = $F('calendarYear')
		Calendars.setCalendar(year, month)
	},
	
	goYear: function(direction){
		var year = $F('calendarYear') * 1 + direction
		var month = $('calendarMonthSelector').selectedIndex * 1
		Calendars.setCalendar(year, month)
	},
	
	nextMonth: function(){
		var month = $('calendarMonthSelector').selectedIndex * 1
		var year = $F('calendarYear') * 1
		if(month < 11){
			nextMonth = month + 1
			nextMonthYear = year
		}
		else{
			nextMonth = 0
			nextMonthYear = year + 1
		}
		Calendars.setCalendar(nextMonthYear, nextMonth)
	},
	
	prevMonth: function(){
		var month = $('calendarMonthSelector').selectedIndex * 1
		var year = $F('calendarYear') * 1
		if(month > 0){
			prevMonth = month - 1
			prevMonthYear = year
		}
		else{
			prevMonth = 11
			prevMonthYear = year - 1
		}
		Calendars.setCalendar(prevMonthYear, prevMonth)
	},

	setToToday: function(){
		now = new Date()
		this.close(now.getFullYear() + '-' + (now.getMonth() + 1) + '-' + now.getDate())
	},
	
	dateToDBForm: function(date){
		if(!date) return ''
		if(date.match(/^\d{2}-\d{1,2}-\d{1,2}/)){
			date = '20' + date
		}
		if(!date.match(/^\d{4}-\d{1,2}-\d{1,2}$/)){
			return die('date input error (' + date + ')')
		}
		
		var year = date.replace(/^(\d{4})-\d{1,2}-\d{1,2}.*$/, '$1')
		var month = date.replace(/^\d{4}-(\d{1,2})-\d{1,2}.*$/, '$1')
		var day = date.replace(/^\d{4}-\d{1,2}-(\d{1,2}).*$/, '$1')
		month = month < 10 ? '0' + month : month
		day = day < 10 ? '0' + day : day
		return year + '-' + month + '-' + day
	}
	
}

Phrases = {
	initiated: false,
	initiate: function(){
		$H(Phrases.phrases).each(function(phrase){
			var key = phrase[0]
			var value = phrase[1]
			if(key.toLowerCase() != key) Phrases.phrases[key.toLowerCase()] = value
		})
	},
	translate: function(phrase){
		if(!Phrases.initiated) Phrases.initiate()
		
		key = phrase.toLowerCase()
		if(Phrases.phrases[key]) return Phrases.phrases[key]
		else return phrase
	},
	tr: function(phrase){return Phrases.translate(phrase)},
	phrases: {}
}

JSON = {
	encode: function(v){
		if(v.toJSON) return v.toJSON()
		else if(typeof(v) == 'object' && $A(v).length) return $A(v).toJSON()
		else if(typeof(v) == 'object' && $H(v).keys().length) return $H(v).toJSON()
		else if(v.toString()) return v.toString().toJSON()
		return ''
	},
	decode: function(v){
		try{return v.evalJSON()}
		catch(e){return null}
	}
}

Editors = null


/*
Copyright (c) Copyright (c) 2007, Carl S. Yestrau All rights reserved.
Code licensed under the BSD License: http://www.featureblend.com/license.txt
Version: 1.0.4
*/
var FlashDetect = new function(){
    var self = this;
    self.installed = false;
    self.raw = "";
    self.major = -1;
    self.minor = -1;
    self.revision = -1;
    self.revisionStr = "";
    var activeXDetectRules = [
        {
            "name":"ShockwaveFlash.ShockwaveFlash.7",
            "version":function(obj){
                return getActiveXVersion(obj);
            }
        },
        {
            "name":"ShockwaveFlash.ShockwaveFlash.6",
            "version":function(obj){
                var version = "6,0,21";
                try{
                    obj.AllowScriptAccess = "always";
                    version = getActiveXVersion(obj);
                }catch(err){}
                return version;
            }
        },
        {
            "name":"ShockwaveFlash.ShockwaveFlash",
            "version":function(obj){
                return getActiveXVersion(obj);
            }
        }
    ];
    /**
     * Extract the ActiveX version of the plugin.
     * 
     * @param {Object} The flash ActiveX object.
     * @type String
     */
    var getActiveXVersion = function(activeXObj){
        var version = -1;
        try{
            version = activeXObj.GetVariable("$version");
        }catch(err){}
        return version;
    };
    /**
     * Try and retrieve an ActiveX object having a specified name.
     * 
     * @param {String} name The ActiveX object name lookup.
     * @return One of ActiveX object or a simple object having an attribute of activeXError with a value of true.
     * @type Object
     */
    var getActiveXObject = function(name){
        var obj = -1;
        try{
            obj = new ActiveXObject(name);
        }catch(err){
            obj = {activeXError:true};
        }
        return obj;
    };
    /**
     * Parse an ActiveX $version string into an object.
     * 
     * @param {String} str The ActiveX Object GetVariable($version) return value. 
     * @return An object having raw, major, minor, revision and revisionStr attributes.
     * @type Object
     */
    var parseActiveXVersion = function(str){
        var versionArray = str.split(",");//replace with regex
        return {
            "raw":str,
            "major":parseInt(versionArray[0].split(" ")[1], 10),
            "minor":parseInt(versionArray[1], 10),
            "revision":parseInt(versionArray[2], 10),
            "revisionStr":versionArray[2]
        };
    };
    /**
     * Parse a standard enabledPlugin.description into an object.
     * 
     * @param {String} str The enabledPlugin.description value.
     * @return An object having raw, major, minor, revision and revisionStr attributes.
     * @type Object
     */
    var parseStandardVersion = function(str){
        var descParts = str.split(/ +/);
        var majorMinor = descParts[2].split(/\./);
        var revisionStr = descParts[3];
        return {
            "raw":str,
            "major":parseInt(majorMinor[0], 10),
            "minor":parseInt(majorMinor[1], 10), 
            "revisionStr":revisionStr,
            "revision":parseRevisionStrToInt(revisionStr)
        };
    };
    /**
     * Parse the plugin revision string into an integer.
     * 
     * @param {String} The revision in string format.
     * @type Number
     */
    var parseRevisionStrToInt = function(str){
        return parseInt(str.replace(/[a-zA-Z]/g, ""), 10) || self.revision;
    };
    /**
     * Is the major version greater than or equal to a specified version.
     * 
     * @param {Number} version The minimum required major version.
     * @type Boolean
     */
    self.majorAtLeast = function(version){
        return self.major >= version;
    };
    /**
     * Is the minor version greater than or equal to a specified version.
     * 
     * @param {Number} version The minimum required minor version.
     * @type Boolean
     */
    self.minorAtLeast = function(version){
        return self.minor >= version;
    };
    /**
     * Is the revision version greater than or equal to a specified version.
     * 
     * @param {Number} version The minimum required revision version.
     * @type Boolean
     */
    self.revisionAtLeast = function(version){
        return self.revision >= version;
    };
    /**
     * Is the version greater than or equal to a specified major, minor and revision.
     * 
     * @param {Number} major The minimum required major version.
     * @param {Number} (Optional) minor The minimum required minor version.
     * @param {Number} (Optional) revision The minimum required revision version.
     * @type Boolean
     */
    self.versionAtLeast = function(major){
        var properties = [self.major, self.minor, self.revision];
        var len = Math.min(properties.length, arguments.length);
        for(i=0; i<len; i++){
            if(properties[i]>=arguments[i]){
                if(i+1<len && properties[i]==arguments[i]){
                    continue;
                }else{
                    return true;
                }
            }else{
                return false;
            }
        }
    };
    /**
     * Constructor, sets raw, major, minor, revisionStr, revision and installed public properties.
     */
    self.FlashDetect = function(){
        if(navigator.plugins && navigator.plugins.length>0){
            var type = 'application/x-shockwave-flash';
            var mimeTypes = navigator.mimeTypes;
            if(mimeTypes && mimeTypes[type] && mimeTypes[type].enabledPlugin && mimeTypes[type].enabledPlugin.description){
                var version = mimeTypes[type].enabledPlugin.description;
                var versionObj = parseStandardVersion(version);
                self.raw = versionObj.raw;
                self.major = versionObj.major;
                self.minor = versionObj.minor; 
                self.revisionStr = versionObj.revisionStr;
                self.revision = versionObj.revision;
                self.installed = true;
            }
        }else if(navigator.appVersion.indexOf("Mac")==-1 && window.execScript){
            var version = -1;
            for(var i=0; i<activeXDetectRules.length && version==-1; i++){
                var obj = getActiveXObject(activeXDetectRules[i].name);
                if(!obj.activeXError){
                    self.installed = true;
                    version = activeXDetectRules[i].version(obj);
                    if(version!=-1){
                        var versionObj = parseActiveXVersion(version);
                        self.raw = versionObj.raw;
                        self.major = versionObj.major;
                        self.minor = versionObj.minor; 
                        self.revision = versionObj.revision;
                        self.revisionStr = versionObj.revisionStr;
                    }
                }
            }
        }
    }();
};

/*--------------------------------------------------------------------------*/

/*	SWFObject v2.2 <http://code.google.com/p/swfobject/> 
	is released under the MIT License <http://www.opensource.org/licenses/mit-license.php> 
*/
var swfobject=function(){var D="undefined",r="object",S="Shockwave Flash",W="ShockwaveFlash.ShockwaveFlash",q="application/x-shockwave-flash",R="SWFObjectExprInst",x="onreadystatechange",O=window,j=document,t=navigator,T=false,U=[h],o=[],N=[],I=[],l,Q,E,B,J=false,a=false,n,G,m=true,M=function(){var aa=typeof j.getElementById!=D&&typeof j.getElementsByTagName!=D&&typeof j.createElement!=D,ah=t.userAgent.toLowerCase(),Y=t.platform.toLowerCase(),ae=Y?/win/.test(Y):/win/.test(ah),ac=Y?/mac/.test(Y):/mac/.test(ah),af=/webkit/.test(ah)?parseFloat(ah.replace(/^.*webkit\/(\d+(\.\d+)?).*$/,"$1")):false,X=!+"\v1",ag=[0,0,0],ab=null;if(typeof t.plugins!=D&&typeof t.plugins[S]==r){ab=t.plugins[S].description;if(ab&&!(typeof t.mimeTypes!=D&&t.mimeTypes[q]&&!t.mimeTypes[q].enabledPlugin)){T=true;X=false;ab=ab.replace(/^.*\s+(\S+\s+\S+$)/,"$1");ag[0]=parseInt(ab.replace(/^(.*)\..*$/,"$1"),10);ag[1]=parseInt(ab.replace(/^.*\.(.*)\s.*$/,"$1"),10);ag[2]=/[a-zA-Z]/.test(ab)?parseInt(ab.replace(/^.*[a-zA-Z]+(.*)$/,"$1"),10):0}}else{if(typeof O.ActiveXObject!=D){try{var ad=new ActiveXObject(W);if(ad){ab=ad.GetVariable("$version");if(ab){X=true;ab=ab.split(" ")[1].split(",");ag=[parseInt(ab[0],10),parseInt(ab[1],10),parseInt(ab[2],10)]}}}catch(Z){}}}return{w3:aa,pv:ag,wk:af,ie:X,win:ae,mac:ac}}(),k=function(){if(!M.w3){return}if((typeof j.readyState!=D&&j.readyState=="complete")||(typeof j.readyState==D&&(j.getElementsByTagName("body")[0]||j.body))){f()}if(!J){if(typeof j.addEventListener!=D){j.addEventListener("DOMContentLoaded",f,false)}if(M.ie&&M.win){j.attachEvent(x,function(){if(j.readyState=="complete"){j.detachEvent(x,arguments.callee);f()}});if(O==top){(function(){if(J){return}try{j.documentElement.doScroll("left")}catch(X){setTimeout(arguments.callee,0);return}f()})()}}if(M.wk){(function(){if(J){return}if(!/loaded|complete/.test(j.readyState)){setTimeout(arguments.callee,0);return}f()})()}s(f)}}();function f(){if(J){return}try{var Z=j.getElementsByTagName("body")[0].appendChild(C("span"));Z.parentNode.removeChild(Z)}catch(aa){return}J=true;var X=U.length;for(var Y=0;Y<X;Y++){U[Y]()}}function K(X){if(J){X()}else{U[U.length]=X}}function s(Y){if(typeof O.addEventListener!=D){O.addEventListener("load",Y,false)}else{if(typeof j.addEventListener!=D){j.addEventListener("load",Y,false)}else{if(typeof O.attachEvent!=D){i(O,"onload",Y)}else{if(typeof O.onload=="function"){var X=O.onload;O.onload=function(){X();Y()}}else{O.onload=Y}}}}}function h(){if(T){V()}else{H()}}function V(){var X=j.getElementsByTagName("body")[0];var aa=C(r);aa.setAttribute("type",q);var Z=X.appendChild(aa);if(Z){var Y=0;(function(){if(typeof Z.GetVariable!=D){var ab=Z.GetVariable("$version");if(ab){ab=ab.split(" ")[1].split(",");M.pv=[parseInt(ab[0],10),parseInt(ab[1],10),parseInt(ab[2],10)]}}else{if(Y<10){Y++;setTimeout(arguments.callee,10);return}}X.removeChild(aa);Z=null;H()})()}else{H()}}function H(){var ag=o.length;if(ag>0){for(var af=0;af<ag;af++){var Y=o[af].id;var ab=o[af].callbackFn;var aa={success:false,id:Y};if(M.pv[0]>0){var ae=c(Y);if(ae){if(F(o[af].swfVersion)&&!(M.wk&&M.wk<312)){w(Y,true);if(ab){aa.success=true;aa.ref=z(Y);ab(aa)}}else{if(o[af].expressInstall&&A()){var ai={};ai.data=o[af].expressInstall;ai.width=ae.getAttribute("width")||"0";ai.height=ae.getAttribute("height")||"0";if(ae.getAttribute("class")){ai.styleclass=ae.getAttribute("class")}if(ae.getAttribute("align")){ai.align=ae.getAttribute("align")}var ah={};var X=ae.getElementsByTagName("param");var ac=X.length;for(var ad=0;ad<ac;ad++){if(X[ad].getAttribute("name").toLowerCase()!="movie"){ah[X[ad].getAttribute("name")]=X[ad].getAttribute("value")}}P(ai,ah,Y,ab)}else{p(ae);if(ab){ab(aa)}}}}}else{w(Y,true);if(ab){var Z=z(Y);if(Z&&typeof Z.SetVariable!=D){aa.success=true;aa.ref=Z}ab(aa)}}}}}function z(aa){var X=null;var Y=c(aa);if(Y&&Y.nodeName=="OBJECT"){if(typeof Y.SetVariable!=D){X=Y}else{var Z=Y.getElementsByTagName(r)[0];if(Z){X=Z}}}return X}function A(){return !a&&F("6.0.65")&&(M.win||M.mac)&&!(M.wk&&M.wk<312)}function P(aa,ab,X,Z){a=true;E=Z||null;B={success:false,id:X};var ae=c(X);if(ae){if(ae.nodeName=="OBJECT"){l=g(ae);Q=null}else{l=ae;Q=X}aa.id=R;if(typeof aa.width==D||(!/%$/.test(aa.width)&&parseInt(aa.width,10)<310)){aa.width="310"}if(typeof aa.height==D||(!/%$/.test(aa.height)&&parseInt(aa.height,10)<137)){aa.height="137"}j.title=j.title.slice(0,47)+" - Flash Player Installation";var ad=M.ie&&M.win?"ActiveX":"PlugIn",ac="MMredirectURL="+O.location.toString().replace(/&/g,"%26")+"&MMplayerType="+ad+"&MMdoctitle="+j.title;if(typeof ab.flashvars!=D){ab.flashvars+="&"+ac}else{ab.flashvars=ac}if(M.ie&&M.win&&ae.readyState!=4){var Y=C("div");X+="SWFObjectNew";Y.setAttribute("id",X);ae.parentNode.insertBefore(Y,ae);ae.style.display="none";(function(){if(ae.readyState==4){ae.parentNode.removeChild(ae)}else{setTimeout(arguments.callee,10)}})()}u(aa,ab,X)}}function p(Y){if(M.ie&&M.win&&Y.readyState!=4){var X=C("div");Y.parentNode.insertBefore(X,Y);X.parentNode.replaceChild(g(Y),X);Y.style.display="none";(function(){if(Y.readyState==4){Y.parentNode.removeChild(Y)}else{setTimeout(arguments.callee,10)}})()}else{Y.parentNode.replaceChild(g(Y),Y)}}function g(ab){var aa=C("div");if(M.win&&M.ie){aa.innerHTML=ab.innerHTML}else{var Y=ab.getElementsByTagName(r)[0];if(Y){var ad=Y.childNodes;if(ad){var X=ad.length;for(var Z=0;Z<X;Z++){if(!(ad[Z].nodeType==1&&ad[Z].nodeName=="PARAM")&&!(ad[Z].nodeType==8)){aa.appendChild(ad[Z].cloneNode(true))}}}}}return aa}function u(ai,ag,Y){var X,aa=c(Y);if(M.wk&&M.wk<312){return X}if(aa){if(typeof ai.id==D){ai.id=Y}if(M.ie&&M.win){var ah="";for(var ae in ai){if(ai[ae]!=Object.prototype[ae]){if(ae.toLowerCase()=="data"){ag.movie=ai[ae]}else{if(ae.toLowerCase()=="styleclass"){ah+=' class="'+ai[ae]+'"'}else{if(ae.toLowerCase()!="classid"){ah+=" "+ae+'="'+ai[ae]+'"'}}}}}var af="";for(var ad in ag){if(ag[ad]!=Object.prototype[ad]){af+='<param name="'+ad+'" value="'+ag[ad]+'" />'}}aa.outerHTML='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'+ah+">"+af+"</object>";N[N.length]=ai.id;X=c(ai.id)}else{var Z=C(r);Z.setAttribute("type",q);for(var ac in ai){if(ai[ac]!=Object.prototype[ac]){if(ac.toLowerCase()=="styleclass"){Z.setAttribute("class",ai[ac])}else{if(ac.toLowerCase()!="classid"){Z.setAttribute(ac,ai[ac])}}}}for(var ab in ag){if(ag[ab]!=Object.prototype[ab]&&ab.toLowerCase()!="movie"){e(Z,ab,ag[ab])}}aa.parentNode.replaceChild(Z,aa);X=Z}}return X}function e(Z,X,Y){var aa=C("param");aa.setAttribute("name",X);aa.setAttribute("value",Y);Z.appendChild(aa)}function y(Y){var X=c(Y);if(X&&X.nodeName=="OBJECT"){if(M.ie&&M.win){X.style.display="none";(function(){if(X.readyState==4){b(Y)}else{setTimeout(arguments.callee,10)}})()}else{X.parentNode.removeChild(X)}}}function b(Z){var Y=c(Z);if(Y){for(var X in Y){if(typeof Y[X]=="function"){Y[X]=null}}Y.parentNode.removeChild(Y)}}function c(Z){var X=null;try{X=j.getElementById(Z)}catch(Y){}return X}function C(X){return j.createElement(X)}function i(Z,X,Y){Z.attachEvent(X,Y);I[I.length]=[Z,X,Y]}function F(Z){var Y=M.pv,X=Z.split(".");X[0]=parseInt(X[0],10);X[1]=parseInt(X[1],10)||0;X[2]=parseInt(X[2],10)||0;return(Y[0]>X[0]||(Y[0]==X[0]&&Y[1]>X[1])||(Y[0]==X[0]&&Y[1]==X[1]&&Y[2]>=X[2]))?true:false}function v(ac,Y,ad,ab){if(M.ie&&M.mac){return}var aa=j.getElementsByTagName("head")[0];if(!aa){return}var X=(ad&&typeof ad=="string")?ad:"screen";if(ab){n=null;G=null}if(!n||G!=X){var Z=C("style");Z.setAttribute("type","text/css");Z.setAttribute("media",X);n=aa.appendChild(Z);if(M.ie&&M.win&&typeof j.styleSheets!=D&&j.styleSheets.length>0){n=j.styleSheets[j.styleSheets.length-1]}G=X}if(M.ie&&M.win){if(n&&typeof n.addRule==r){n.addRule(ac,Y)}}else{if(n&&typeof j.createTextNode!=D){n.appendChild(j.createTextNode(ac+" {"+Y+"}"))}}}function w(Z,X){if(!m){return}var Y=X?"visible":"hidden";if(J&&c(Z)){c(Z).style.visibility=Y}else{v("#"+Z,"visibility:"+Y)}}function L(Y){var Z=/[\\\"<>\.;]/;var X=Z.exec(Y)!=null;return X&&typeof encodeURIComponent!=D?encodeURIComponent(Y):Y}var d=function(){if(M.ie&&M.win){window.attachEvent("onunload",function(){var ac=I.length;for(var ab=0;ab<ac;ab++){I[ab][0].detachEvent(I[ab][1],I[ab][2])}var Z=N.length;for(var aa=0;aa<Z;aa++){y(N[aa])}for(var Y in M){M[Y]=null}M=null;for(var X in swfobject){swfobject[X]=null}swfobject=null})}}();return{registerObject:function(ab,X,aa,Z){if(M.w3&&ab&&X){var Y={};Y.id=ab;Y.swfVersion=X;Y.expressInstall=aa;Y.callbackFn=Z;o[o.length]=Y;w(ab,false)}else{if(Z){Z({success:false,id:ab})}}},getObjectById:function(X){if(M.w3){return z(X)}},embedSWF:function(ab,ah,ae,ag,Y,aa,Z,ad,af,ac){var X={success:false,id:ah};if(M.w3&&!(M.wk&&M.wk<312)&&ab&&ah&&ae&&ag&&Y){w(ah,false);K(function(){ae+="";ag+="";var aj={};if(af&&typeof af===r){for(var al in af){aj[al]=af[al]}}aj.data=ab;aj.width=ae;aj.height=ag;var am={};if(ad&&typeof ad===r){for(var ak in ad){am[ak]=ad[ak]}}if(Z&&typeof Z===r){for(var ai in Z){if(typeof am.flashvars!=D){am.flashvars+="&"+ai+"="+Z[ai]}else{am.flashvars=ai+"="+Z[ai]}}}if(F(Y)){var an=u(aj,am,ah);if(aj.id==ah){w(ah,true)}X.success=true;X.ref=an}else{if(aa&&A()){aj.data=aa;P(aj,am,ah,ac);return}else{w(ah,true)}}if(ac){ac(X)}})}else{if(ac){ac(X)}}},switchOffAutoHideShow:function(){m=false},ua:M,getFlashPlayerVersion:function(){return{major:M.pv[0],minor:M.pv[1],release:M.pv[2]}},hasFlashPlayerVersion:F,createSWF:function(Z,Y,X){if(M.w3){return u(Z,Y,X)}else{return undefined}},showExpressInstall:function(Z,aa,X,Y){if(M.w3&&A()){P(Z,aa,X,Y)}},removeSWF:function(X){if(M.w3){y(X)}},createCSS:function(aa,Z,Y,X){if(M.w3){v(aa,Z,Y,X)}},addDomLoadEvent:K,addLoadEvent:s,getQueryParamValue:function(aa){var Z=j.location.search||j.location.hash;if(Z){if(/\?/.test(Z)){Z=Z.split("?")[1]}if(aa==null){return L(Z)}var Y=Z.split("&");for(var X=0;X<Y.length;X++){if(Y[X].substring(0,Y[X].indexOf("="))==aa){return L(Y[X].substring((Y[X].indexOf("=")+1)))}}}return""},expressInstallCallback:function(){if(a){var X=c(R);if(X&&l){X.parentNode.replaceChild(l,X);if(Q){w(Q,true);if(M.ie&&M.win){l.style.display="block"}}if(E){E(B)}}a=false}}}}();

function returnFalse(){return false}