// PROTOTYPE CALENDAR - it's using prototype.js
// INVOCATION EXAMPLE
//
//if(isDefined("DP")) if(DP.container.visible()) DP.forceQuit(); DP = new datePicker("INPUT FIELD ID",left,top); DP.updateContainer();
//left / top can be obtained from the picker image with element.cumulativeOffset().left / top
//


var datePicker = Class.create (
{
	initialize: function(dateFieldId,left,top)
	{
		this.id=dateFieldId;
		this.months=new Array('January','February','March','April','May','June','July','August','September','October','November','December');
		this.days=new Array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday');
		
		this.container = new Element('div',{'class':'datePickerWindow','id':'datePicker','style':
			'width:180px;position:absolute;background-color:white;border:1px solid silver;top:'+top+'px;left:'+left+'px;'} );
		
		document.body.appendChild(this.container);
		
		this.today = new Date();
		
		day=parseInt($(this.id+'-day').value);
		month=parseInt($(this.id+'-month').value);
		year=parseInt($(this.id+'-year').value);
		if(isNaN(day) || isNaN(month) || isNaN(year))
		this.date=this.today; else this.date=new Date($(this.id+'-year').value,$(this.id+'-month').value-1,$(this.id+'-day').value);
		this.updateContainer(this.date);
	},
	
	alterDate: function(date,year,month,day)
	{
		return new Date(date.getFullYear()+year,date.getMonth()+month,date.getDate()+day);
	},

	getDaysInMonth: function(monthDate)
	{
		firstDayOfMonth = new Date(monthDate.getFullYear(),monthDate.getMonth(),1);
		this.temp=firstDayOfMonth;
		temp=firstDayOfMonth;
		tempMonth = new Array();
		while(firstDayOfMonth.getMonth()==temp.getMonth())
		{
			day=temp.getDate();
			dayOfWeek=temp.getDay();
			if(dayOfWeek==0 || day==1) tempWeek = new Array();
			if(day==1) { for(i=0;i<=dayOfWeek;i++) { tempWeek[i]=null; } }
			if(dayOfWeek<=6) tempWeek[dayOfWeek] = temp;
			if(dayOfWeek==6) tempMonth[tempMonth.length]=tempWeek;
			temp=this.alterDate(temp,0,0,1)
			if(firstDayOfMonth.getMonth()!=temp.getMonth())
				if(tempMonth[tempMonth.length-1]!=tempWeek) tempMonth[tempMonth.length]=tempWeek;
		}
		return tempMonth;
	},
	
	viewMonth: function(monthArray)
	{
		date=monthArray[1][1];
		month=date.getMonth();
		year=date.getFullYear();
		
		monthTable = new Element('table',{'cellpadding':'0','cellspacing':'0','class':'datePickerWindow','style':'table-layout:fixed; empty-cells:hide; boder-collapse:collapse; border-spacing:0px; width:100%;'});
		tBody = new Element('tbody');
		monthTable.update(tBody);
		titleRow = new Element('tr',{'class':'datePickerTitle'});
		leftCell = new Element('td').update('&nbsp;'); titleRow.appendChild(leftCell);
		centerBlock= new Element('td',{'colspan':5}).update(this.months[month]+', '+year); titleRow.appendChild(centerBlock);
		rightCell = new Element('td').update('x'); titleRow.appendChild(rightCell);
		rightCell.observe('click',function() {DP.closeContainer();});
		tBody.appendChild(titleRow);
		
		menuRow = new Element('tr',{'class':'datePickerMenu'});
		prevYear = new Element('td').update('<<'); menuRow.appendChild(prevYear);
		prevYear.observe('click',function() { DP.updateContainer(DP.alterDate(DP.temp,-1,0,0)); });
		prevMonth = new Element('td').update('<'); menuRow.appendChild(prevMonth);
		prevMonth.observe('click',function() { DP.updateContainer(DP.alterDate(DP.temp,0,-1,0)); });
		todayCell = new Element('td',{'colspan':3}).update('Today'); menuRow.appendChild(todayCell);
		todayCell.observe('click',function()
		{
			DP.updateContainer(DP.today);
			if($$('.datePickerSelectedDay')[0]) $$('.datePickerSelectedDay')[0].removeClassName('datePickerSelectedDay');
			$(DP.today.getFullYear()+'-'+DP.today.getMonth()+'-'+DP.today.getDate()).addClassName('datePickerSelectedDay');
		});
		nextMonth = new Element('td').update('>'); menuRow.appendChild(nextMonth);
		nextMonth.observe('click',function() { DP.updateContainer(DP.alterDate(DP.temp,0,1,0)); });
		nextYear = new Element('td').update('>>'); menuRow.appendChild(nextYear);
		nextYear.observe('click',function() { DP.updateContainer(DP.alterDate(DP.temp,1,0,0)); });
		tBody.appendChild(menuRow);
		
		daysOfWeekRow = new Element('tr',{'class':'datePickerDaysOfWeek'});
		for(i=0;i<this.days.length;i++)
		{
			day = new Element('td',{'title':this.days[i]}).update(this.days[i].substr(0,1)); daysOfWeekRow.appendChild(day);
		}
		tBody.appendChild(daysOfWeekRow);
		
		for(w=0;w<monthArray.length;w++)
		{
			week = new Element('tr');
			weekDays = monthArray[w];
			for(i=0;i<=6;i++)
			{
				if(weekDays[i]!=null)
				{
					day = new Element('td',{'class':'datePickerDays','id':weekDays[i].getFullYear()+'-'+weekDays[i].getMonth()+'-'+weekDays[i].getDate()}).update(weekDays[i].getDate());
					if(this.date.getFullYear()==weekDays[i].getFullYear() && this.date.getMonth()==weekDays[i].getMonth() && this.date.getDate()==weekDays[i].getDate()) day.addClassName('datePickerSelectedDay')
					day.observe('click',function(event)
					{
						if($$('.datePickerSelectedDay')[0]) $$('.datePickerSelectedDay')[0].removeClassName('datePickerSelectedDay');
						this.addClassName('datePickerSelectedDay');
					});
					day.observe('dblclick',function(event)
					{
						DP.closeContainer();
						dateParts=this.id.split('-');
						if(dateParts[2]>9) $(DP.id+'-day').value=dateParts[2]; else $(DP.id+'-day').value='0'+dateParts[2];
						if(dateParts[1]>8) $(DP.id+'-month').value=(parseInt(dateParts[1])+1); else $(DP.id+'-month').value='0'+(parseInt(dateParts[1])+1);
						$(DP.id+'-year').value=dateParts[0];
						$(DP.id).value=$(DP.id+'-year').value+'-'+$(DP.id+'-month').value+'-'+$(DP.id+'-day').value;
					});
					day.observe('mouseover',function(event)
					{
						dateParts=this.id.split('-');
						$('datePickerStatus').update(dateParts[2]+' '+DP.months[dateParts[1]]+' '+dateParts[0]);
					});				
					day.observe('mouseout',function(event)
					{
						$('datePickerStatus').update('Select date');
					});
					
				} else day = new Element('td');
				week.appendChild(day);
			}
			tBody.appendChild(week);
		}
		
		statusRow = new Element('tr',{'class':'datePickerStatus'});
		statusCell= new Element('td',{'colspan':7,'id':'datePickerStatus'}).update('Select date'); statusRow.appendChild(statusCell);
		tBody.appendChild(statusRow);
		
		return monthTable;
	},
	
	updateContainer: function(date)
	{
		if(date===undefined) date=this.today;
		var newContainer=this.viewMonth(this.getDaysInMonth(date));
		this.container.update(newContainer);
//		if(Prototype.Browser.IE) { this.container.update(this.container.innerHTML); }
	},
	
	closeContainer: function()
	{
		if(this.container.getOpacity()>0.05)
		{ 
			this.container.setOpacity(this.container.getOpacity()-0.05);
			setTimeout(function() {DP.closeContainer();},20);
		}
		else
		{
			this.container.hide();
			this.container.remove();
		}
	},
	
	forceQuit: function()
	{
		this.container.hide();
		this.container.remove();
	}
});
	
function isDefined(variable)
{
	return (typeof(window[variable]) == "undefined") ? false : true;
}
// EO PROTOTYPE CALENDAR

// Ajaxy Select

var ajaxSelect = Class.create (
{
	initialize: function(fieldId,size,position)
	{
		this.id=fieldId;
		this.name=$(fieldId).name;
		this.inputId=fieldId+'-input';
		this.size=size;
		this.position=position;
		this.timer=0;
		this.monitorInputField();
	},
	
	monitorInputField: function()
	{
		inputField=$(this.inputId);
		inputField.observe('keyup', function(event) { this.checkUpdateSelect(); }.bindAsEventListener(this))
	},
	
	checkUpdateSelect: function()
	{
		delay=700; //miliseconds
		minLength=3;
		defLength=6;
//		if($(this.inputId).value.length>=defLength) clearTimeout(this.timer);
		clearTimeout(this.timer);
		if($(this.inputId).value.length>=minLength)
			{
				this.timer=setTimeout(function() { this.closeContainer(); this.getResults(); }.bindAsEventListener(this), delay);
			}
	},
	
	getResults: function()
	{
		new Ajax.Request(window.location,{postBody:'ajaxPost=true&name='+this.name+'&input='+$(this.inputId).value, onSuccess: function(transport)
			{
				resultsNr=0;
				resultsObject=transport.responseText.evalJSON();
				for (var i in resultsObject) resultsNr++;
				this.results=resultsObject;
				this.updateSelect(resultsNr);
			}.bind(this) })
	},
	
	updateSelect: function(resultsNr)
	{
		results=this.results;
		if(resultsNr==1)
		{
			for (var i in results) { optionValue=i; optionLabel=results[i]; } 
			this.updateFields(optionValue,optionLabel).bind(this);
		}
		else
		{
			if(this.size>resultsNr) size=resultsNr; else size=this.size;
			var top=$(this.inputId).cumulativeOffset().top;
			var left=$(this.inputId).cumulativeOffset().left+$(this.inputId).getWidth();
			if(this.position=='under')
			{
				var top=$(this.inputId).cumulativeOffset().top+$(this.inputId).getHeight();
				var left=$(this.inputId).cumulativeOffset().left;
				var width=$(this.inputId).getWidth()+'px';
			}
			else
			{
				var top=$(this.inputId).cumulativeOffset().top;
				var left=$(this.inputId).cumulativeOffset().left+$(this.inputId).getWidth();
				var width="auto";
			}
			container=new Element('div',{'id':this.id+'-container','class':'ajaxSelectContainer','style':'padding:0px;margin:0px;position:absolute;top:'+top+'px;left:'+left+'px;background-color:transparent;overflow:visible;'});
			select=new Element('select',{'id':this.id+'-select','class':'ajaxSelect','style':'width:'+width+';position:relative;','size':size});
			for (var i in results)
			{
				option=new Element('option',{'value':i}).update(results[i]);
				select.appendChild(option);
			}
			select.selectedIndex=-1;
			select.observe('change',function(event) { this.updateFields($(this.id+'-select').value,$(this.id+'-select').options[$(this.id+'-select').selectedIndex].text); }.bindAsEventListener(this))
			container.update(select);
			document.body.appendChild(container);
		}
	},
	
	updateFields: function(optionValue,optionLabel)
	{
		$(this.id).value=optionValue;
		$(this.inputId).value=optionLabel;
		$(this.id).fire("do:Change");
		this.closeContainer();
	},
	
	closeContainer: function()
	{
		for (i=0;i<$$('.ajaxSelectContainer').length;i++) { $$('.ajaxSelectContainer')[i].remove(); }
	}
});
		

// EO Ajaxy Select

// reFeedOnChange(hungrySelect, onChangeMonitoredInput)

function reFeedOnChange(selectToReFeed,monitoredElement)
{
	selectToReFeed=$(selectToReFeed);
	monitoredElement=$(monitoredElement);
	monitoredElement.observe('change', function(event)
	{
		new Ajax.Request(window.location,{postBody:'ajaxPost=true&name='+selectToReFeed.name+'&input='+monitoredElement.value, onSuccess: function(transport)
			{
				oldOptions=$(selectToReFeed.id).childElements();
				for(i=0;i<oldOptions.length;i++)
				{
					oldOptions[i].remove();
				}
				if(transport.responseText.substr(0,1)=="{")
				{
					if($(selectToReFeed.id).tagName!="SELECT")
					{
						var container=$(selectToReFeed.id).ancestors()[0];
						var newSelect=new Element("select", {"id":"job","name":"job","class":"formClass"});
						container.update(newSelect);
					}
						
					resultsObject=transport.responseText.evalJSON();
					for (var i in resultsObject)
					{
						newOption=new Element('option',{'value':i}).update(resultsObject[i]);
						$(selectToReFeed.id).appendChild(newOption);
					}
				}
					else
				{
					eval(transport.responseText);
				}
			} })
	});
}

// EO reFeedOnChange