/*******************************************************************************\
|	Name:		Window handler													|
|	Filename:	window.js														|
|	Version:	2.0.0															|
|	Author:		Eric van Blokland												|
|	Project:	Shared library													|
|	Summary:	Javascript support for window classes (window.php)				|
|																				|
\*******************************************************************************/

var wnd_winW;
var wnd_winH;
var wnd_step;
var wnd_act_id;
var wnd_cxt_id=Array();
var wnd_top;
var wnd_clientx;
var wnd_clienty;
var wnd_id=null;
var wnd_context_menus=Array();
function wnd_handler_index_error() {
	fader=API.faders.New(document.getElementById('system_error'),.2,20,0,100,false);
	fader.element.style.display='block';
	fader.fadeIn();
	slider=API.sliders.New(document.getElementById('system_error_details'),'height',.5,40,0,150);

}

function wnd_property_datepicker(id,value,container,bMayBeEmpty) {
	if(!container) {
		document.write('<div class="wndDatePickerContainer" id="'+id+'container"></div>');
	}
	var self=this;	
	this.value=value;
	
	if(bMayBeEmpty)
		var mayBeEmpty=true;
	else
		var mayBeEmpty=false;
	 
	if(this.value) {
		var date=new Date(this.value);
		var currentDate=new Date(this.value);
	}
	else {
		var date=new Date(); 
		var currentDate=null;
	}
	
	var rangePrev=null;
	var rangeNext=null;
	
	var container=document.getElementById(id+'container');
	
	var input=document.createElement('input');
	
	var months= ["JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC"];
	
	var yearSelect=null;
	var monthSelect=null;
	var daySelect=null;
	
	
	input.name=id;
	input.id=id;
	input.readOnly=false;
	input.onchange=function() {
		var date=this.value.split('/',3);
		
		self.setDateValue(parseFloat(date[2]), parseFloat(date[0])-1, parseFloat(date[1]));
	}
	input.value=value;
	input.datePicker=this;
	input.className='wndDatePickerInput';
	var button=document.createElement('div');	
	button.className='wndDatePickerButton';
	
	container.appendChild(input);
	container.appendChild(button);
	
	var selectContainer=document.createElement('div');
	selectContainer.className="wndDatePicker";
	selectContainer.style.display='none';
	selectContainer.style.position='absolute';
	
	var monthSelection=document.createElement('div');	
	monthSelection.className="wndDatePickerMonthSelection";
	
	var monthPrevious=document.createElement('div');
	monthPrevious.className="wndDatePickerMonthPrevious";
	
	var monthLabel=document.createElement('div');
	monthLabel.className="wndDatePickerMonthLabel";
	
	var monthNext=document.createElement('div');
	monthNext.className="wndDatePickerMonthNext";
	
	monthPrevious.onmousedown=function() {
		this.className='wndDatePickerMonthPreviousDown';
	}
	monthPrevious.onmouseout=function() {
		this.className='wndDatePickerMonthPrevious';		
	}
	monthPrevious.onmouseup=function(e) {
		e=e||window.event;
		this.className='wndDatePickerMonthPrevious';
		self.previousMonth();		
		if(e.preventDefault)
			e.preventDefault();
		e.cancelBubble=true;
		return false;
	}
	
	monthNext.onmousedown=function() {
		this.className='wndDatePickerMonthNextDown';
	}
	monthNext.onmouseout=function() {
		this.className='wndDatePickerMonthNext';
	}
	monthNext.onmouseup=function(e) {
		e=e||window.event;
		this.className='wndDatePickerMonthNext';
		self.nextMonth();
		if(e.preventDefault)
			e.preventDefault();
		e.cancelBubble=true;
		return false;
	}
	
	
	monthSelection.appendChild(monthPrevious);
	monthSelection.appendChild(monthLabel);
	monthSelection.appendChild(monthNext);
	
	var daySelection=document.createElement('div');	
	daySelection.className="wndDatePickerDaySelection";
	
	var dayOverview=document.createElement('div');	
	dayOverview.className="wndDatePickerDayOverview";
	
	var days=['S','M','T','W','T','F','S'];
	for(var i=0;i<days.length;i++) {
		var oDay=document.createElement('div');
		oDay.innerHTML=days[i];	
		dayOverview.appendChild(oDay);
	}
	daySelection.appendChild(dayOverview);
	
	var shown=false;
	
	var dayContainer=document.createElement('div');	
	dayContainer.className="wndDatePickerDayContainer";
	
	daySelection.appendChild(dayContainer);
	
	var clearContainer=document.createElement('div');
	clearContainer.className="wndDatePickerClear";
	
	if(mayBeEmpty) {
		var clearButton=document.createElement('a');
		clearButton.innerHTML='Clear';
		clearButton.onclick=function(e) {
			e=e||window.event;			
			self.clear();
			self.updateMonth();
			if(rangeNext)
				rangeNext.clear();
			if(rangePrev)
				rangePrev.clear();
			if(e.preventDefault)
				e.preventDefault();
			e.cancelBubble=true;
			return false;
		}
		clearContainer.appendChild(clearButton);
	}
	daySelection.appendChild(clearContainer);
	
	selectContainer.appendChild(monthSelection);
	selectContainer.appendChild(daySelection);
	
	
	container.appendChild(selectContainer);
	if(typeof(button)!='object') {
		button=document.getElementById(button);
	}
	if(typeof(button)=='object') {		
		button.onclick=function(e) {
			e=e||window.event;			
			self.toggle();
			if(e.preventDefault)
				e.preventDefault();
			e.cancelBubble=true;
			return false;
		}
		
	}
	
	this.setPrevious=function(datePicker) {
		rangePrev=datePicker;
		rangePrev.setNext(this);
	}
	this.setNext=function(datePicker) {
		rangeNext=datePicker;
	}
	
	this.previousMonth=function() {
		date.setMonth(date.getMonth()-1);
		this.updateMonth();
	}
	this.nextMonth=function() {
		date.setMonth(date.getMonth()+1);
		this.updateMonth();
	}
	this.updateMonth=function() {
		monthLabel.innerHTML=months[date.getMonth()]+' '+date.getFullYear();
		this.updateDays();
	}
	this.updateDays=function() {
		dayContainer.innerHTML='';
		var dayToday=new Date();
		var dayDate=new Date(date.valueOf())
		dayDate.setDate(1);
		var prevDate=new Date(dayDate.valueOf());
		prevDate.setDate(1-dayDate.getDay());
		var x=0;
		for(var i=0;i<dayDate.getDay();i++) {
			var oDay=document.createElement('div');
			oDay.innerHTML=prevDate.getDate();
			var postFix='';
			if(rangePrev && rangePrev.getSelectedDate() && prevDate.valueOf()<rangePrev.getSelectedDate().valueOf())
				postFix='X';
			if(rangeNext && rangeNext.getSelectedDate() && prevDate.valueOf()>rangeNext.getSelectedDate().valueOf())
				postFix='X';
			oDay.className='wndDatePickerDayBlur'+postFix;
			dayContainer.appendChild(oDay);
			prevDate.setDate(prevDate.getDate()+1);
			x++;
		}
		while(dayDate.getMonth()==date.getMonth()) {
			var oDay=document.createElement('div');
			oDay.innerHTML=dayDate.getDate();
			var postFix='';
			if(rangePrev && rangePrev.getSelectedDate() && dayDate.valueOf()<rangePrev.getSelectedDate().valueOf())
				postFix='X';
			if(rangeNext && rangeNext.getSelectedDate() && dayDate.valueOf()>rangeNext.getSelectedDate().valueOf())
				postFix='X';
			if(currentDate!=null && dayDate.getDate()==currentDate.getDate() && dayDate.getMonth()==currentDate.getMonth() && dayDate.getFullYear()==currentDate.getFullYear()) {			
				oDay.className='wndDatePickerDaySelected'+postFix;
			}
			else if(dayDate.getDate()==dayToday.getDate() && dayDate.getMonth()==dayToday.getMonth() && dayDate.getFullYear()==dayToday.getFullYear()) {
				oDay.className='wndDatePickerDayToday'+postFix;
			}
			else {
				oDay.className='wndDatePickerDay'+postFix;
			}
			if(postFix!='X') {
				oDay.onclick=function() {
					self.setDateValue(date.getFullYear(),date.getMonth(),this.innerHTML);
					self.hide();
				}
			}
			dayContainer.appendChild(oDay);
			dayDate.setDate(dayDate.getDate()+1);			
			x++;
		}
		while(x<42) {
			var oDay=document.createElement('div');
			oDay.innerHTML=dayDate.getDate();
			var postFix='';
			if(rangePrev && rangePrev.getSelectedDate() && dayDate.valueOf()<rangePrev.getSelectedDate().valueOf())
				postFix='X';
			if(rangeNext && rangeNext.getSelectedDate() && dayDate.valueOf()>rangeNext.getSelectedDate().valueOf())
				postFix='X';
			oDay.className='wndDatePickerDayBlur'+postFix;
			dayContainer.appendChild(oDay);
			dayDate.setDate(dayDate.getDate()+1);			
			x++;
		}
	}
	this.validate=function() {
		if(yearSelect && daySelect && monthSelect) {
			var testDate=new Date(yearSelect.value,monthSelect.value-1,daySelect.value);			
			if(testDate.getDate()!=daySelect.value || testDate.getMonth()!=monthSelect.value-1 || testDate.getFullYear() !=yearSelect.value) 
				return false;			
		}
		return true;
	}
	this.setClass =function(className) {
		if(daySelect)
			daySelect.className=className;
		if(monthSelect)
			monthSelect.className=className;
		if(yearSelect)
			yearSelect.className=className;
	}
	this.getSelectedDate= function() {
		return currentDate;
	}
	this.clear=function() {
		currentDate=null;
		input.value='';
	}
	this.setDateValue=function(year,month,day) {
		date.setFullYear(year);
		date.setMonth(month);
		date.setDate(day);
		if(currentDate==null)
			currentDate=new Date();
		currentDate.setFullYear(year);
		currentDate.setMonth(month);
		currentDate.setDate(day);
		this.updateMonth();		
		if(yearSelect)
			yearSelect.value=year;	
		if(monthSelect)
			monthSelect.value=month+1;		
		if(daySelect)
			daySelect.value=day;
		input.value=(currentDate.getMonth()+1)+'/'+currentDate.getDate()+'/'+currentDate.getFullYear();
	}
	this.hide=function() {
		shown=false;
		selectContainer.style.display='none';
	}
	
	this.show=function() {
		this.updateMonth();
		shown=true;
		selectContainer.style.display='block';
	}
	
	this.toggle=function() {
		if(shown)
			this.hide();
		else
			this.show();
	}	
	
	this.hideInput =function() {
		input.style.display="none";
	}
	function getObject(object) {
		if((typeof object)!='object')
			return document.getElementById(object);
		return object;
	}
	this.setSelects=function(year,month,day) {
		this.setYearSelect(year);
		this.setMonthSelect(month);
		this.setDaySelect(day);
	}
	this.setYearSelect=function(object) {
		yearSelect=getObject(object);
		AttachEvent(yearSelect,'change',function() {
			self.setDateSelect();
		});
	}
	this.setMonthSelect=function(object) {
		monthSelect=getObject(object);
		AttachEvent(monthSelect,'change',function() {
			self.setDateSelect();
		});
	}
	this.setDaySelect=function(object) {
		daySelect=getObject(object);
		AttachEvent(daySelect,'change',function() {
			self.setDateSelect();
		});
	}
	
	this.setDateSelect=function() {
		//this.value=this.monthSelect.value+'/'+this.daySelect.value+'/'+this.yearSelect.value;
		this.setDateValue(yearSelect.value,monthSelect.value-1,daySelect.value);		
		input.value=monthSelect.value+'/'+daySelect.value+'/'+yearSelect.value;
	}
	
	
	function AttachEvent(targetObject,eventName,eventFunction) {
		if(!targetObject)
			return;
		if(targetObject.attachEvent) {		
			targetObject.attachEvent('on'+eventName,eventFunction);	
		}
		else {
			targetObject.addEventListener(eventName,eventFunction,false);
		}
		
	}	
	
	AttachEvent(window.document.body,'mouseup',function() {
		self.hide();
	});
}


function wnd_property_slider(name,container,min,max,value,scale) {
		this.name=name;
		this.slider=document.createElement('div');
		this.slider.className='wnd_property_slider';
		this.slider.id=name+"Slider";
		this.ticker=document.createElement('div');
		this.ticker.className='wnd_property_slider_ticker';
		this.slider.id=name+"Ticker";
		
		this.tracker=document.createElement('div')
		this.tracker.className='wnd_property_slider_tracker';
		this.tracker.id=name+"Tracker";
		
		this.input=document.createElement('input');
		this.input.type='text';
		this.input.value=value;
		this.input.name=name;
		this.input.className='wnd_property_slider_input';
		this.input.slider=this;
		this.input.onchange=function() {
			this.value=this.slider.setValue(this.value*this.slider.scale)/this.slider.scale;
		}

		if(typeof container == 'object') {
			this.container=container;
		}
		else if(typeof container=='string') {
			this.container=document.getElementById(container);
		}
		else {
			return;
		}
		this.container.appendChild(this.slider);
		this.container.appendChild(this.input);

		this.slider.appendChild(this.ticker);
		this.slider.appendChild(this.tracker);

		this.max=max;
		this.min=min;
		this.value=value;
		this.scale=scale;
		
		this.slider.property=this;
		this.setValue=function(value,noChange) {
			var changed=false;
			if(value>this.max)
				value=this.max;
			if(value<this.min)
				value=this.min;
			if(this.value!=value)
				changed=true;
			this.value=value;
			this.input.value=(this.value/this.scale);
			this.tracker.style.top=((this.max-this.min)-(this.value-this.min))+'px';
			if(changed==true && !noChange && this.onchange instanceof Function)
				this.onchange();
			return this.value;
		}
		this.changeValue=function(change) {
			this.setValue(this.value+change);
		}

		this.slider.slider=this;
		this.slider.style.height=(this.max-this.min+12)+'px';
		this.ticker.style.height=(this.max-this.min)+'px';

		this.tracker.slider=this;
		this.tracker.drag=false;
		this.tracker.onmousedown=function(e) {
			e=e||window.event;
			this.drag=true;
			this.dragY=e.clientY;
			if(e.preventDefault)
				e.preventDefault();
		}
		this.slider.onmouseup=function(e) {
			e=e||window.event;
			this.slider.tracker.drag=false;
		}

		this.slider.onmouseout=function(e) {
			var e=e||window.event;
			var reltg = (e.relatedTarget) ? e.relatedTarget : e.toElement;
			if(reltg && this.id==reltg.id && reltg.id==this.property.name+"Tracker")
				return;
			if((e.clientX<this.offsetLeft || e.clientX>this.offsetLeft+this.offsetWidth || 
				e.clientY<this.offsetTop || e.clientY>this.offsetTop+this.offsetHeight)  ) {
				this.slider.tracker.drag=false;				
				}
		}
		/* dont mouseout on the tracker for a smoother experience
		this.tracker.onmouseout=function(e) {
			e=e||window.event;
			e.cancelBubble=true;
		}
		*/
		this.slider.onmousemove=function(e) {
			e=e||window.event;
			if(this.slider.tracker.drag==true) {
				this.slider.changeValue(-(e.clientY-this.slider.tracker.dragY));
				this.slider.tracker.dragY=e.clientY;
			}
		}

		this.setValue(value);
		this.onchange=function() {

		}
	}
function wnd_property_listview(id,template,column,item,subitem,multiselect,enabled)	{
	this.id=id;
	this.column=column;
	this.item=item;
	this.subitem=subitem;
	this.template=template;
	this.container=document.getElementById(this.id+"_container");
	this.columns=Array();
	this.items=Array();
	this.oncontextmenu=null;

	this.multiselect=multiselect;
	this.enabled=enabled;

	this.add_column=function(newcolumn) {
		this.columns.push(newcolumn);
	}
	this.add_item=function(newitem) {
		if(this.multiselect==true) {
			newitem.checkbox=window.document.createElement('input');
			newitem.checkbox.type='checkbox';
			newitem.checkbox.style.padding='0px';
			newitem.checkbox.style.margin='0px';
			newitem.checkbox.style.width='16px';
			newitem.checkbox.style.height='16px';						
		}
		newitem.parent=this;
		this.items.push(newitem);
	}

	this.select=function(id,selected) {
		if(this.enabled===false)
			return;
		if(selected!==false)
			selected=true;

		for(i=0;i<this.items.length;i++) {
			if (this.multiselect==false && this.items[i].selected==true && this.items[i].id!=id) {
				this.items[i].selected=false;
				this.items[i].set_class(false);
				this.setSelected(this.items[i].id,false);
			}
			else if(this.items[i].id==id) {
				this.items[i].selected=selected;
				this.items[i].set_class(selected);
				this.setSelected(this.items[i].id,selected);
			}

		}
	}

	this.setSelected =function(id,value) {
		data=getCookie('listview_data');
		//id=this.id+'_'+id;
		if(data) {
			pos1=data.indexOf(id);
			if(pos1!=-1) {
				pos2=data.indexOf(';',pos1);
				if(pos2==-1)
					pos2=data.length;
				data=data.substr(0,pos1-1)+data.substr(pos2,data.length-pos2);

			}
		}
		data=(data!=null ? data+';' : '')+id+'='+value;		
		setCookie('listview_data',data);
	}

	this.parse=function() {
		columns='';
		items='';
		selected=new Array();
		for(i=0;i<this.columns.length;i++)	{
			columns=columns+this.column.replace(/\[BUTTON\]/,'<DIV ID="'+this.columns[i].id+'_container"></DIV>');
		}
		for(i=0;i<this.items.length;i++)	{
			items=items+this.items[i].parse(this.item,this.subitem);
			if(this.items[i].selected===true)
				selected.push(this.items[i]);
		}
		this.container.innerHTML=this.template.replace(/\[COLUMNS\]/,columns).replace(/\[ITEMS\]/,items).replace(/\[ONCONTEXTMENU\]/,this.oncontextmenu).replace(/\[COUNT_COLUMNS\]/,this.columns.length);
		for(i=0;i<this.columns.length;i++)	{
			this.columns[i].parse();
		}
		for(var i=0;i<selected.length;i++)
			selected[i].set_class();
	}
}

function wnd_property_listview_item(id,text,selected,image,subitems,action,onmouseover,onmouseout,image2)	{
	this.id=id;
	this.selected=selected;
	this.text=text;
	this.image=image;
	this.image2=image2;
	this.subitems=subitems;
	this.action=action;
	this.oncontextmenu='';
	this.onmouseover=onmouseover;
	this.onmouseout=onmouseout;
	this.parent=null;
	this.checkbox=null;

	this.set_class=function(mouseover) {
		if(mouseover===true)
			document.getElementById(this.id).className='wnd_property_listview_item_mouseover';
		else if(this.selected==true)
			document.getElementById(this.id).className='wnd_property_listview_item_selected';
		else
			document.getElementById(this.id).className='wnd_property_listview_item_default';
	}
	this.parse=function(item,subitem)	{
		subitems='';
		for(a=0;a<this.subitems.length;a++)	{
			align='left';
			if(this.parent && this.parent.columns[a+1])
				align=this.parent.columns[a+1].align;
			subitems=subitems+subitem.replace(/\[TEXT\]/,this.subitems[a]).replace(/\[ALIGN\]/,align);
		}
		align='left';
		if(this.parent && this.parent.columns[0])
			align=this.parent.columns[0].align;
		if(this.checkbox) {
			this.checkbox.onclick=this.parent.id+".select('"+this.id+"',this.checked);"
			this.checkbox.checked=this.selected;
		}
		var checkbox='';
		if(this.checkbox) {
			if(this.checkbox.outerHTML)
				checkbox=this.checkbox.outerHTML;			
			if(checkbox.indexOf('onclick')==-1) {				
				checkbox = new XMLSerializer().serializeToString(this.checkbox);
				if(checkbox.indexOf('/>')!=-1)
					checkbox=checkbox.replace('/>','onclick="'+this.checkbox.onclick+'" '+(this.selected ? 'checked="checked" ' : '')+'/>');
				else
					checkbox=checkbox.replace('>','onclick="'+this.parent.id+".select('"+this.id+"',this.checked);"+'" '+(this.selected ? 'checked="checked" ' : '')+'/>');
			}			
		}
		return item.replace(/\[IMAGE2\]/,(this.image2? '<IMAGE style="position:relative;margin-left:-19px;" SRC="'+this.image2+'">' : '' )).replace(/\[IMAGE\]/,(this.image? '<IMAGE ALIGN="left" SRC="'+this.image+'">' : '' )).replace(/\[TEXT\]/,this.text).replace(/\[SUBITEMS\]/,subitems).replace(/\[ACTION\]/,(this.selected!==null && this.parent.multiselect==false ? this.parent.id+".select('"+this.id+"');" : '')+this.action).replace(/\[ONCONTEXTMENU\]/,this.oncontextmenu).replace(/\[ALIGN\]/,align).replace(/\[ONMOUSEOVER\]/,this.id+".set_class(true);"+this.onmouseover).replace(/\[ONMOUSEOUT\]/,this.id+".set_class(false);"+this.onmouseout).replace(/\[ID\]/,this.id).replace(/\[CHECKBOX\]/,checkbox);
	}
}

function wnd_property_listview_column(id,button_template_up,button_template_down,caption,image,align,direction) {
	this.id=id;
	this.button_template_up=button_template_up;
	this.button_template_down=button_template_down;
	this.caption=caption;
	this.image=image;
	this.button=null;
	this.align=align;
	this.direction=direction;
	this.parse=function()	{
		if(!this.button)	{
			//object=document.getElementById(this.id+'_object');
			//alert(object);
			direction=this.direction;
			if(!direction)
				direction='ASC';
			else if(direction=='ASC') {
				this.image='images/listview_asc.gif';
				direction='DESC';
			}
			else if(direction=='DESC') {
				this.image='images/listview_desc.gif';
				direction='ASC'
			}
			image='';
			if(this.image)
				image='<IMG SRC="'+this.image+'">';
			strLocation=window.location.href;
			if(strLocation.indexOf('&direction=')>0)	{
				strLocation=strLocation.replace(/\&order_by\=[\w]+?\&direction\=[\w]+/,'&order_by='+this.id+'&direction='+direction );
			} else  {
				strLocation=strLocation+'&order_by='+this.id+'&direction='+direction;
			}
			this.button=new wnd_property_button(this.id,this.button_template_up.replace(/\[IMAGE\]/,image),this.button_template_down.replace(/\[IMAGE\]/,image),null,"window.location.href='"+strLocation +"';return false;",true,this.caption)
			eval(this.id+'_object=this.button;');
		}
	}
}

function wnd_property_button(id,template_up,template_down,checked,action,enabled,value)	{
	this.id=id+'_object';
	this.input=document.getElementById(id+'_input');
	this.container=document.getElementById(id+'_container');
	this.action=action;
	this.value=value;
	this.template_up='<DIV onmousedown="'+this.id+'.onmousedown();" onmouseup="'+this.id+'.onmouseup();if('+this.id+'.enabled==false) {return false; }'+this.action.replace(/\[BUTTON_OBJECT_ID\]/g,this.id)+'" onmouseout="'+this.id+'.onmouseout();">'+template_up+'</DIV>';
	this.template_down='<DIV  onmousedown="'+this.id+'.onmousedown();" onmouseup="'+this.id+'.onmouseup();if('+this.id+'.enabled==false) { return false; }'+this.action.replace(/\[BUTTON_OBJECT_ID\]/g,this.id)+'" onmouseout="'+this.id+'.onmouseout();">'+template_down+'</DIV>';
	this.checked=checked;
	this.enabled=enabled;
	this.down=false;
	this.onmousedown=function()	{
		this.down=true;
		if(this.enabled==true)
			this.container.innerHTML=this.template_down.replace(/\[VALUE\]/g,this.value);
	}
	this.onmouseup=function(){
		this.down=false;
		if(this.enabled==true)	{
			//eval(this.action);
			if(this.checked===true)
				this.checked=false;
			else if (this.checked===false)
				this.checked=true;
			if(this.input)
				this.input.value=(this.checked ? 1 : 0);
		}
		this.apply();

	}
	this.onmouseout=function()	{
		if(this.down==true) {
			this.apply();
			this.down=false;
		}
	}
	this.apply=function()	{
		//alert(this.enabled);
		if(this.enabled==true)
			this.button_enabled='';
		else
			this.button_enabled='DISABLED';
		if(this.checked==true)	{
			this.container.innerHTML=this.template_down.replace(/\[ENABLED\]/g,this.button_enabled).replace(/\[VALUE\]/g,this.value);
		} else {
			this.container.innerHTML=this.template_up.replace(/\[ENABLED\]/g,this.button_enabled).replace(/\[VALUE\]/g,this.value);
		}
	}
	this.apply();
}

function wnd_register_context_menu(menu)	{
	wnd_context_menus.push(menu);
}
function wnd_parse_context_menu()	{
	for(i=0;i<wnd_context_menus.length;i++)	{
		wnd_context_menus[i].parse();
	}
}



function wnd_context_menu(name,template) {
	this.items=Array();
	this.parent=this;
	this.name=name;
	this.height=0;
	this.width=0;
	this.template=template;
	this.container=window.document.createElement('DIV');
	this.container.id=this.name;
	this.container.style.position='absolute';
	this.container.style.visibility='hidden';	
	this.container.style.zIndex=0;
	//this.container.style.filter='alpha(opacity:100);';

	this.structure_id=1;
	this.add_item=function(item)	{
		item.parent=this;
		this.items.push(item);
	}
	this.open=function(submenu)	{
		this.parse();		
		window.clearInterval(this.interval);
		//if(submenu)
			//this.container.onmouseleave=wnd_context_close;		
		this.container.onmousemove=wnd_context_close;			
		wnd_context_open(this.container.id,submenu,this.parent.container);
	}
	this.capture=function(submenu)	{
		return;
		this.parse();
		clearInterval(this.interval);
		//if(submenu)
			//this.container.onmouseleave=wnd_context_close;
		this.container.onmousemove=wnd_context_close;
		wnd_context_capture(this.container.id,this.parent.container);
	}
	this.close=function()	{
	}
	this.validate=function(){

	}
	this.parse=function()	{
		//if(window.document.readyState=="complete")	{
			
			this.validate();
			
			if(!window.document.getElementById(this.container.id)) {
				window.document.body.appendChild(this.container);
			}
			// BF20090406:	Ugh.. content... use a "var" and lets name it cxt_content
			var cxt_content='';
			this.height=0;
			for(i=0;i<this.items.length;i++)	{
				cxt_content=cxt_content+this.items[i].parse();
				if(this.items[i].visible===true)
					this.height=this.height+this.items[i].height;
			}
			this.container.style.height=this.height;
			this.container.style.width=this.width;
			
			if(window.document.getElementById(this.template).innerText)			
				this.container.innerHTML=window.document.getElementById(this.template).innerText.replace('[ITEMS]',cxt_content);
			else
				this.container.innerHTML=window.document.getElementById(this.template).childNodes[0].nodeValue.replace('[ITEMS]',cxt_content);
			return true;
		//}
	}
	this.unload=function() {
		this.container.onmousemove=null;
		delete this.container;
	}
	var contextmenu=this;
	FSAttachEvent(window.document.body,'mouseup',function(e) {e=e||window.event; if(e.button!=2) wnd_context_close();});
	
	FSAttachEvent(window,'unload',function() { contextmenu.unload(); });
}

function wnd_context_menu_item(template,caption,image,href,target,onclick,description,enabled,grayed,visible) {
	this.submenu=null;
	this.template=template;
	this.caption=caption;
	this.image=image;
	this.onmouseover="";
	this.onmousemove="";
	this.onmouseout="";
	this.onmousedown="";
	if(grayed==true) {
		enabled=false;
	}
	this.enabled=enabled;
	this.grayed=grayed;
	this.visible=visible;
	this.target=target;
	this.onclick=onclick;
	this.description=description;
	this.href=href;
	this.parent=null;
	this.checked=null;
	this.parse=function()	{
		if(this.submenu)
			this.submenu.parent=this.parent;
		if(this.visible===true)	{
			// BF20090406:	Ugh.. content... use a "var" and lets name it cxt_content
			if(	window.document.getElementById(this.template).innerText)
				var cxt_content=window.document.getElementById(this.template).innerText;
			else
				var cxt_content=window.document.getElementById(this.template).childNodes[0].nodeValue;			
			cxt_content=cxt_content.replace(/\[CAPTION\]/g,'<DIV '+(this.grayed==true? 'STYLE="position:absolute;Filter:alpha(Opacity=30);"' : '')+'>'+this.caption+'</DIV>');
			if(this.checked===null)	{
				if(this.image)
					cxt_content=cxt_content.replace(/\[IMAGE\]/g,'<IMG '+(this.grayed==true? 'STYLE="Filter:Gray;Filter:alpha(Opacity=30);"' : '')+' BORDER="0" SRC="'+this.image+'" ALIGN="left">');
				else
					cxt_content=cxt_content.replace(/\[IMAGE\]/g,'');
			}
			else	{
				cxt_content=cxt_content.replace(/\[IMAGE\]/g,(this.checked ? '<IMG BORDER="0" SRC="images/cxt_checked.gif" ALIGN="left">' : '<IMG BORDER="0" SRC="images/cxt_unchecked.gif" ALIGN="left">'));
			}
			cxt_content=cxt_content.replace(/\[onclick\]/g,(!this.enabled? '' : (this.submenu!=null ? (this.submenu.container ? 'if(!'+this.submenu.container.id+'.id || '+ this.submenu.container.id+'.style.visibility!=\'visible\')':'')+" { clearInterval("+ this.submenu.name+".interval);}" : '')+ 'wnd_context_close(\'\',true);'+this.onclick+''));
			cxt_content=cxt_content.replace(/\[HREF\]/g,(this.href && this.enabled ? 'HREF="'+this.href+'"': ''));

			cxt_content=cxt_content.replace(/\[ENABLED\]/g,(this.enabled? '' : 'DISABLED'));
			cxt_content=cxt_content.replace(/\[enabled\]/g,(this.enabled? '' : 'DISABLED="disabled"'));
			/*
			if(this.grayed==false)
				cxt_content=cxt_content.replace(/\[STYLE\]/g,'');
			else
				cxt_content=cxt_content.replace(/\[STYLE\]/g,'filter: alpha(opacity:50);background-color:#FFFFFF;');
			*/
			cxt_content=cxt_content.replace(/\[TARGET\]/g,''+this.target+'');
			cxt_content=cxt_content.replace(/\[SUBMENU\]/g,(this.submenu!=null ? '<IMG BORDER="0" SRC="images/wnd_cxt_sub.gif">' : ''));
			cxt_content=cxt_content.replace(/\[onmousedown\]/g,(!this.enabled ? '' :''+this.onmousedown+''));			
			cxt_content=cxt_content.replace(/\[ONMOUSEOVER\]/g,'wnd_set_xy(event);'+(this.submenu!=null ? (this.submenu.container ? 'if(!'+this.submenu.container.id+'.id || '+ this.submenu.container.id+'.style.visibility!=\'visible\')':'')+" { clearInterval("+ this.submenu.name+".interval);" + this.submenu.name +'.interval=setInterval(\''+ this.submenu.name+'.open(true);\','+(this.onclick ? '1000' : '200' )+');}' :'')+this.onmouseover+'');
			cxt_content=cxt_content.replace(/\[ONMOUSEMOVE\]/g,'window.status=\''+this.description+'\';wnd_set_xy(event);'+this.onmousemove+'"');
			cxt_content=cxt_content.replace(/\[ONMOUSEOUT\]/g,'window.status=\'\';'+(this.submenu!=null ? 'clearInterval('+this.submenu.name+'.interval);':'')+this.onmouseout+'');
		}
		else
			cxt_content='';
		return cxt_content;
	}
}

function wnd_set_xy(e)	{ 	
	e=e || event;
	wnd_clientx=e.clientX;
	wnd_clienty=e.clientY;
}

function wnd_adialog(href)	{
	return openChild(href,null,480,160,true,true);
}

function wnd_handler_env()	{
	if (parseInt(navigator.appVersion)>3) {
		
		wnd_winW = (document.body.offsetWidth || document.documentElement.offsetWidth) +(window.document.body.scrollLeft || window.document.documentElement.scrollLeft);
		wnd_winH = (document.body.offsetHeight || document.documentElement.offsetHeight)+(window.document.body.scrollTop || window.document.documentElement.scrollTop);
		
		
	}
}
function wnd_handler_setup()
{
	wnd_handler_env();
	wnd_top=100;	
}

function wnd_capture_contextmenu(e,fn,obj) {
	e = e || event;	
	if(e.button==2) {	
		wnd_set_xy(e);	
		if(obj)
			fn.apply(obj);
		else
			fn();
	}
}

function wnd_context_capture(wnd_id,submenu)	{
	if (navigator.appName == 'Netscape' && e.which == 3) {
		wnd_context_open(wnd_id,submenu);
		return false;
	}
	if (navigator.appName == 'Microsoft Internet Explorer' && event.button==2) {
		//wnd_context_open(wnd_id);
		return false;
	}
	else
		return true;
}
function wnd_context_close(wnd_id,clear_all)	{
	// If this function is called by an event of a real browser, wnd_id might become the event object, clear it to immitate legacy IE behaviour
	//alert(this + "->"+wnd_id + "->"+clear_all +"->"+wnd_cxt_id.length);
	if(typeof(wnd_id)=='object')
		wnd_id=null;
	if(wnd_cxt_id.length==0)
		return;
	if(clear_all || (wnd_id && wnd_id.srcElement))	{
		index=0;		
		while(wnd_id=wnd_cxt_id[index++] )	{		
			wnd_handler_close(wnd_id);
		}
		wnd_cxt_id=Array();
		return
	}
	else if(!wnd_id ) {
		if(this) {						
			index=wnd_cxt_id.length-1;						
			while(this.id!=wnd_cxt_id[index--] && wnd_cxt_id.length>0 )	{							
				wnd_id=wnd_cxt_id.pop();
				if(wnd_id)
					wnd_handler_close(wnd_id);
			}
			return;
		}
		wnd_id=wnd_cxt_id.pop();
	}
	if(wnd_id) {	
		wnd_handler_close(wnd_id);
	}

}

function wnd_context_open(wnd_id,submenu,srcMenu)	{
	// Firefox "event undefined" fix;	
	try {
		var tmp=event;
	} catch(e) {
		var event=null;
	}
	try
	{
		test=window.document.getElementById(wnd_id).id;
		
		if(!submenu)
			wnd_context_close(null);
		else{
			index=wnd_cxt_id.length-1;
			while(srcMenu.id!=wnd_cxt_id[index--] )	{
				wnd_id=wnd_cxt_id.pop();
				wnd_handler_close(wnd_id);
			}
		}
		Xmo = (window.document.body.scrollLeft || window.document.documentElement.scrollLeft)+( (event ?event.clientX-6 : wnd_clientx-6 ));
		Ymo = (window.document.body.scrollTop || window.document.documentElement.scrollTop)+( (event ? event.clientY-6 : wnd_clienty-6));
		if(Xmo<1)
			Xmo=1;
		if(Ymo <1)
			Ymo=1;
		wnd_handler_env();
		wnd_top++;
		//width = new Number(document.getElementById(wnd_id).style.width.replace(/px/,""))+20;
		//alert(document.getElementById(wnd_id).offsetWidth+" -> "+document.getElementById(wnd_id).style.width);
		//width = new Number(document.getElementById(wnd_id).style.width.replace(/px/,""))+25;
		//height = new Number(document.getElementById(wnd_id).style.height.replace(/px/,""))+25;
		width = document.getElementById(wnd_id).offsetWidth;
		height = document.getElementById(wnd_id).offsetHeight;
		if(width+Xmo>wnd_winW)
			Xmo=Xmo-(width+Xmo-wnd_winW);
		if(height+Ymo>wnd_winH)
			Ymo=Ymo-(height+Ymo-wnd_winH)	
				
		document.getElementById(wnd_id).style.zIndex=wnd_top;		
		document.getElementById(wnd_id).style.visibility="visible";
		document.getElementById(wnd_id).style.left=Xmo+'px';
		document.getElementById(wnd_id).style.top=Ymo+'px';		
		//document.getElementById(wnd_id).filters.alpha.opacity=95;
		if(wnd_act_id)	{
			clearInterval(document['wnd_handler_fade']);
			//document.getElementById(wnd_act_id).filters.alpha.opacity=95;
		}
		wnd_act_id=wnd_id;
		wnd_cxt_id.push(wnd_id);
		//document['wnd_handler_fade'] = setInterval('wnd_handler_fadein("'+wnd_id+'")',10);
		return false;
	}
	catch(e)
	{
		//alert('Can\'t display contextmenu: '+e.message);
	}
}

function wnd_handler_close(wnd_id)	{
	try {	
		document.getElementById(wnd_id).style.visibility="hidden";
	}
	catch(e) {
		alert('Error closing contextmenu '+wnd_id+': '+e.description);
		throw e;
	}
}

function wnd_handler_open(wnd_id)	{
	try
	{
		if(!document.getElementById(wnd_id))
			return;
		var oWindow=document.getElementById(wnd_id);
		
		wnd_handler_env();
		wnd_top++;
		if(wnd_act_id)	{
			
			//clearInterval(document['wnd_handler_fade']);
			//wnd_handler_setOpacity(oWindow,90);
		}
		
		/* IIIIYIKES! Whatever this exactly did, if we run into related issues, refix those in a proper manner
		if(wnd_winW<500){
			for(i=0;i<document.getElementById(wnd_id).all.length;i++)	{
				if(document.getElementById(wnd_id).all(i).offsetWidth>=wnd_winW)	{
					document.getElementById(wnd_id).all(i).width=wnd_winW-10;
					document.getElementById(wnd_id).all(i).style.width=wnd_winW-10;
				}
			}
			document.getElementById(wnd_id).style.width=wnd_winW-10;
			document.getElementById(wnd_id).width=wnd_winW-10;
		}
		*/
		oWindow.style.zIndex=wnd_top;
		oWindow.style.visibility="visible";

		oWindow.style.left=wnd_winW/2-oWindow.offsetWidth/2 + 'px';
		oWindow.style.top=wnd_winH/2-oWindow.offsetHeight/2 + 'px';
		wnd_handler_setOpacity(oWindow,100);
		wnd_act_id=wnd_id;		
		//document['wnd_handler_fade'] = window.setTimeout('wnd_handler_fadein("'+wnd_id+'")',10);		
		
	}
	catch(e)
	{

	}
}

function wnd_handler_fadein(wnd_id)
{
	
	window.clearInterval(document['wnd_handler_fade']);
	var oWindow=document.getElementById(wnd_id);	
	
	wnd_handler_setOpacity(oWindow,oWindow.wndOpacity+20);	

	
	if(oWindow.wndOpacity<=90)
		document['wnd_handler_fade'] = window.setTimeout('wnd_handler_fadein("'+wnd_id+'")',10);
	else	{
		wnd_act_id=null;
		document['wnd_handler_fade']=null;
		//alert(document.getElementById(wnd_id).filters.alpha.opacity);
	}
}

function wnd_handler_setOpacity(object,opacity) {
	// Yeah sorry, I want to cache this and this sh*t isn't really object driven.
	object.wndOpacity=opacity;	
	// IE/Win
	try {
		object.style.filter = "alpha(opacity:"+opacity+")";
		//objects['borderTop'].style.filter = "alpha(opacity:"+opacity+")";
	   }
	catch(e) {
		
	}
	   // Safari<1.2, Konqueror
	try {
		object.style.KHTMLOpacity = opacity/100;
	}
	catch(e) {
	}
	   // Older Mozilla and Firefox
	try {
		object.style.MozOpacity = opacity/100;
	}
	catch(e) {
	}
	   // Safari 1.2, newer Firefox and Mozilla, CSS3
	try {
		object.style.opacity = opacity/100;
	}
	catch(e) {
	}
	
}



<!--
function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_dragLayer(objName,x,hL,hT,hW,hH,toFront,dropBack,cU,cD,cL,cR,targL,targT,tol,dropJS,et,dragJS) { //v4.01
  //Copyright 1998 Macromedia, Inc. All rights reserved.
  var i,j,aLayer,retVal,curDrag=null,curLeft,curTop,IE=document.all,NS4=document.layers;
  var NS6=(!IE&&document.getElementById), NS=(NS4||NS6); if (!IE && !NS) return false;
  retVal = true; if(IE && event) event.returnValue = true;
  if (MM_dragLayer.arguments.length > 1) {
    curDrag = MM_findObj(objName); if (!curDrag) return false;
    if (!document.allLayers) { document.allLayers = new Array();
      with (document) if (NS4) { for (i=0; i<layers.length; i++) allLayers[i]=layers[i];
        for (i=0; i<allLayers.length; i++) if (allLayers[i].document && allLayers[i].document.layers)
          with (allLayers[i].document) for (j=0; j<layers.length; j++) allLayers[allLayers.length]=layers[j];
      } else {
        if (NS6) { var spns = getElementsByTagName("span"); var all = getElementsByTagName("div");
          for (i=0;i<spns.length;i++) if (spns[i].style&&spns[i].style.position) allLayers[allLayers.length]=spns[i];}
        for (i=0;i<all.length;i++) if (all[i].style&&all[i].style.position) allLayers[allLayers.length]=all[i];
    } }
    curDrag.MM_dragOk=true; curDrag.MM_targL=targL; curDrag.MM_targT=targT;
    curDrag.MM_tol=Math.pow(tol,2); curDrag.MM_hLeft=hL; curDrag.MM_hTop=hT;
    curDrag.MM_hWidth=hW; curDrag.MM_hHeight=hH; curDrag.MM_toFront=toFront;
    curDrag.MM_dropBack=dropBack; curDrag.MM_dropJS=dropJS;
    curDrag.MM_everyTime=et; curDrag.MM_dragJS=dragJS;
    curDrag.MM_oldZ = (NS4)?curDrag.zIndex:curDrag.style.zIndex;
    curLeft= (NS4)?curDrag.left:(NS6)?parseInt(curDrag.style.left):curDrag.style.pixelLeft;
    if (String(curLeft)=="NaN") curLeft=0; curDrag.MM_startL = curLeft;
    curTop = (NS4)?curDrag.top:(NS6)?parseInt(curDrag.style.top):curDrag.style.pixelTop;
    if (String(curTop)=="NaN") curTop=0; curDrag.MM_startT = curTop;
    curDrag.MM_bL=(cL<0)?null:curLeft-cL; curDrag.MM_bT=(cU<0)?null:curTop-cU;
    curDrag.MM_bR=(cR<0)?null:curLeft+cR; curDrag.MM_bB=(cD<0)?null:curTop+cD;
    curDrag.MM_LEFTRIGHT=0; curDrag.MM_UPDOWN=0; curDrag.MM_SNAPPED=false; //use in your JS!
    document.onmousedown = MM_dragLayer; document.onmouseup = MM_dragLayer;
    if (NS) document.captureEvents(Event.MOUSEDOWN|Event.MOUSEUP);
  } else {
    var theEvent = ((NS)?objName.type:event.type);
    if (theEvent == 'mousedown') {
      var mouseX = (NS)?objName.pageX : event.clientX + document.body.scrollLeft;
      var mouseY = (NS)?objName.pageY : event.clientY + document.body.scrollTop;
      var maxDragZ=null; document.MM_maxZ = 0;
      for (i=0; i<document.allLayers.length; i++) { aLayer = document.allLayers[i];
        var aLayerZ = (NS4)?aLayer.zIndex:parseInt(aLayer.style.zIndex);
        if (aLayerZ > document.MM_maxZ) document.MM_maxZ = aLayerZ;
        var isVisible = (((NS4)?aLayer.visibility:aLayer.style.visibility).indexOf('hid') == -1);
        if (aLayer.MM_dragOk != null && isVisible) with (aLayer) {
          var parentL=0; var parentT=0;
          if (NS6) { parentLayer = aLayer.parentNode;
            while (parentLayer != null && parentLayer.style.position) {
              parentL += parseInt(parentLayer.offsetLeft); parentT += parseInt(parentLayer.offsetTop);
              parentLayer = parentLayer.parentNode;
          } } else if (IE) { parentLayer = aLayer.parentElement;
            while (parentLayer != null && parentLayer.style.position) {
              parentL += parentLayer.offsetLeft; parentT += parentLayer.offsetTop;
              parentLayer = parentLayer.parentElement; } }
          var tmpX=mouseX-(((NS4)?pageX:((NS6)?parseInt(style.left):style.pixelLeft)+parentL)+MM_hLeft);
          var tmpY=mouseY-(((NS4)?pageY:((NS6)?parseInt(style.top):style.pixelTop) +parentT)+MM_hTop);
          if (String(tmpX)=="NaN") tmpX=0; if (String(tmpY)=="NaN") tmpY=0;
          var tmpW = MM_hWidth;  if (tmpW <= 0) tmpW += ((NS4)?clip.width :offsetWidth);
          var tmpH = MM_hHeight; if (tmpH <= 0) tmpH += ((NS4)?clip.height:offsetHeight);
          if ((0 <= tmpX && tmpX < tmpW && 0 <= tmpY && tmpY < tmpH) && (maxDragZ == null
              || maxDragZ <= aLayerZ)) { curDrag = aLayer; maxDragZ = aLayerZ; } } }
      if (curDrag) {
        document.onmousemove = MM_dragLayer; if (NS4) document.captureEvents(Event.MOUSEMOVE);
        curLeft = (NS4)?curDrag.left:(NS6)?parseInt(curDrag.style.left):curDrag.style.pixelLeft;
        curTop = (NS4)?curDrag.top:(NS6)?parseInt(curDrag.style.top):curDrag.style.pixelTop;
        if (String(curLeft)=="NaN") curLeft=0; if (String(curTop)=="NaN") curTop=0;
        MM_oldX = mouseX - curLeft; MM_oldY = mouseY - curTop;
        document.MM_curDrag = curDrag;  curDrag.MM_SNAPPED=false;
        if(curDrag.MM_toFront) {
          eval('curDrag.'+((NS4)?'':'style.')+'zIndex=document.MM_maxZ+1');
          if (!curDrag.MM_dropBack) document.MM_maxZ++; }
        retVal = false; if(!NS4&&!NS6) event.returnValue = false;
    } } else if (theEvent == 'mousemove') {
      if (document.MM_curDrag) with (document.MM_curDrag) {
        var mouseX = (NS)?objName.pageX : event.clientX + document.body.scrollLeft;
        var mouseY = (NS)?objName.pageY : event.clientY + document.body.scrollTop;
        newLeft = mouseX-MM_oldX; newTop  = mouseY-MM_oldY;
        if (MM_bL!=null) newLeft = Math.max(newLeft,MM_bL);
        if (MM_bR!=null) newLeft = Math.min(newLeft,MM_bR);
        if (MM_bT!=null) newTop  = Math.max(newTop ,MM_bT);
        if (MM_bB!=null) newTop  = Math.min(newTop ,MM_bB);
        MM_LEFTRIGHT = newLeft-MM_startL; MM_UPDOWN = newTop-MM_startT;
        if (NS4) {left = newLeft; top = newTop;}
        else if (NS6){style.left = newLeft; style.top = newTop;}
        else {style.pixelLeft = newLeft; style.pixelTop = newTop;}
        if (MM_dragJS) eval(MM_dragJS);
        retVal = false; if(!NS) event.returnValue = false;
    } } else if (theEvent == 'mouseup') {
      document.onmousemove = null;
      if (NS) document.releaseEvents(Event.MOUSEMOVE);
      if (NS) document.captureEvents(Event.MOUSEDOWN); //for mac NS
      if (document.MM_curDrag) with (document.MM_curDrag) {
        if (typeof MM_targL =='number' && typeof MM_targT == 'number' &&
            (Math.pow(MM_targL-((NS4)?left:(NS6)?parseInt(style.left):style.pixelLeft),2)+
             Math.pow(MM_targT-((NS4)?top:(NS6)?parseInt(style.top):style.pixelTop),2))<=MM_tol) {
          if (NS4) {left = MM_targL; top = MM_targT;}
          else if (NS6) {style.left = MM_targL; style.top = MM_targT;}
          else {style.pixelLeft = MM_targL; style.pixelTop = MM_targT;}
          MM_SNAPPED = true; MM_LEFTRIGHT = MM_startL-MM_targL; MM_UPDOWN = MM_startT-MM_targT; }
        if (MM_everyTime || MM_SNAPPED) eval(MM_dropJS);
        if(MM_dropBack) {if (NS4) zIndex = MM_oldZ; else style.zIndex = MM_oldZ;}
        retVal = false; if(!NS) event.returnValue = false; }
      document.MM_curDrag = null;
    }
    if (NS) document.routeEvent(objName);
  } return retVal;
}
//-->


