/* SVN FILE: $Id: visitnc.search.js 1928 2009-07-10 20:12:45Z michaelklauss $ */
/* -- date picker -- */
var Picker = Class.create();
Picker.prototype = {
	button_back    : 'cal_back',
	button_next    : 'cal_next',
	calendar       : 'cal',
	calendar_title : 'cal_title',
	calendar_div   : 'cal_element',
	selecteddate   : null,
	months         : ['Gennaio','Febbraio','Marzo','Aprile','Maggio','Giugno','Luglio','Agosto','Settembre','Ottobre','Novembre','Dicembre'],
	monthlen       : [31,0,31,30,31,30,31,31,30,31,30,31],
	days           : ['S','M','T','W','T','F','S'],
	today          : new Date(),
	current_year   : new Date().getFullYear(),
	current_month  : new Date().getMonth(),
	callback       : null,
	cal_root       : null,
	initialize : function(start,callback,ele) {
		if(callback) { this.callback = callback; }
		this.today.setHours(0);
		this.today.setMinutes(0);
		this.today.setSeconds(0);
		this.today.setMilliseconds(0);
		var s = new Date(start);
		if(!s.getDate()) {
			var s = new Date();
		}
		s.setHours(0);
		s.setMinutes(0);
		s.setSeconds(0);
		s.setMilliseconds(0);
		this.current_month = s.getMonth()+1;
		this.current_year  = s.getFullYear();
		this.selecteddate = s;
		// create & position root calendar element
		this.removeCal(); // kill existing
		var style = {'zIndex':'100000','display':'none','position':'absolute','top':0,'left':0};
		if(ele) {
			var pos    = Element.cumulativeOffset(ele);
			style.top  = pos.top +'px'; 
			style.left = (pos.left-10) +'px'; 
		}
		var div = new Element('div',{'id':'cal_root'});
		this.cal_root = div;
		div.setStyle(style);
		this.render(this.current_month,this.current_year);
	},
	removeCal: function() {
		if($('cal_root')){
			$('cal_root').remove();
			this.cal_root=null;
		}
	},
	selectDate : function(d) {
		this.selecteddate = d;
		this.render(this.current_month,this.current_year);
		if(this.callback!=null){
			this.callback(this.selecteddate);
		}
		this.removeCal();
	},
	move : function(n) {
		var m = this.current_month + n;
		var y = this.current_year;
		if(m==13){m=1;y++}
		if(m==0){m=12;y--}
		this.current_year  = y;
		this.current_month = m;
		this.render(m,y);
	},
	render : function(month, year) {
		// clear current calendar
		this.cal_root.update();
		// css display elements
		var div1 = new Element('div',{'id':'cal_div','class':'twosixfive'});
		var div2 = new Element('div',{'class':'bloc265'});
		div1.insert(div2);
		var div3 = new Element('div',{'id':'cal_element'});
		div2.insert(div3);
		// nav prev month
		var eleBack = new Element('a',{'id':'cal_back'});
		eleBack.update('&lt;');
		var action = function(){this.move(-1)}
		eleBack.observe('click',action.bindAsEventListener(this));
		div3.insert(eleBack);
		// month title
		var cal_title = new Element('div',{'id':'cal_title'});
		cal_title.update(this.months[month-1]+' '+year);
		div3.insert(cal_title);
		// nav next month
		var eleNext  = new Element('a',{'id':'cal_next'});
		eleNext.update('&gt;');
		var action = function(){this.move(1)}
		eleNext.observe('click',action.bindAsEventListener(this));
		div3.insert(eleNext);
		// calendar table
		var cal = new Element('table',{'id':'cal','border':0,'cellspacing':0});
		div3.insert(cal);
		// user prompt
		var p = new Element('p');
		p.update('<strong>Click<\/strong> date to select.');
		div3.insert(p);
		// close
		var eleClose = new Element('input',{'value':'close','type':'button'});	
		eleClose.setStyle({'fontSize':'10px','marginBottom':'10px','padding':'2px'});
		var action = function(){this.removeCal()}
		eleClose.observe('click',action.bindAsEventListener(this));
		div3.insert(eleClose);
		// footer
		div2.insert(new Element('div',{'class':'bloc265end'}));
		this.cal_root.insert(div1);
		var nodes = cal.descendants();
		nodes.each(function(node){node.remove()});
		var monthStart = new Date(year,month-1,1);    // first day of the month
		monthStart.firstDay = monthStart.getDay()+1;  // day of week that our month starts
		// find Feb leap year
		this.monthlen[1] = (((monthStart.getFullYear()%100!=0)&&(monthStart.getFullYear()%4==0))||(monthStart.getFullYear()%400==0))? 29 : 28 ;
		// css class for start & end of week
		var cls = ['nol','','','','','','nor'];
		// build table & header
		var tbody = new Element('tbody');
		var tr  = new Element('tr');
		for(i=0; i<7; i++) { 
			var th = new Element('th',{'class':cls[i]});
			th.update(this.days[i]);
			tr.insert(th);
		}
		tbody.insert(tr);
		// how many rows of days in this cal?
		var rows = Math.ceil(((monthStart.firstDay-1) + this.monthlen[month-1])/7 );
		var ii = 1;
		for(j=0;j<rows;j++)
		{
			var tr = new Element('tr');
			for(i=0;i<=6;i++)
			{
				var day = ((ii-monthStart.firstDay>=0) && (ii-monthStart.firstDay<this.monthlen[month-1]) )? ii-monthStart.firstDay+1 : null ;
				var td  = new Element('td');
				td.writeAttribute({'title':'Click to select date.'});
				td.thisdate = (day==null)? null : new Date(year,month-1,day);
				td.addClassName(cls[(ii-1)%7]); // set class for first && last day of week
				if(j==(rows-1)){td.addClassName('nob');} // last row gets last row class
				if(td.thisdate!=null)
				{
					if(td.thisdate.valueOf()==this.selecteddate.valueOf()){
						td.addClassName('sel');
						td.setStyle({'fontStyle':'italic'});
					}
					if(this.today.valueOf() == td.thisdate.valueOf()) {
						td.addClassName('today');
						td.setStyle({'fontWeight':'bold'});
					}
					td.update(day);
					var action = function(evt) {
						var ele = evt.element();
						this.selectDate(ele.thisdate);
					}
					td.observe('click',action.bindAsEventListener(this));
				}
				else
				{
					td.update(day);
				}
				tr.insert(td);
				ii++;
			}
			tbody.insert(tr);
		}
		cal.insert(tbody);
		if(!document.body.insert){Element.extend(document.body);}
		document.body.insert(this.cal_root);
		this.cal_root.show();
	}
}

/* -- listing search picker -- */
var pform = {
	eleTopCat: null,
	eleSubCat: null,
	eleArrow : null,
	eleAreaId: null,
	eleCityId: null,
	eleSubmit: null,
	eleForm  : null,
	cache: {},
	regions: {'151':'Mountain','150':'Piedmont','149':'Coast'},
	init: function() {
		this.eleTopCat = $('SearchCategoryId');
		this.eleSubCat = $('SearchSubCategoryId');
		this.eleArrow  = $('cattosub');
		this.eleAreaId = $('SearchAreaId');
		this.eleCityId = $('SearchCityId');
		this.eleSubmit = $('SearchesSubmit');
		this.eleForm   = $('SearchesForm');
		var action = function() {this.updateCats();}
		this.eleTopCat.observe('change',action.bind(this));
		var action = function() {this.updateCities();}
		this.eleAreaId.observe('change',action.bind(this));
		var action = function(evt) {
			Event.stop(evt);
			this.eleForm.submit();
			return false;
		}
		this.eleSubmit.observe('click',action.bind(this));
		this.setCatStyle();
	},
	updateCats: function() {
		if(this.eleTopCat.selectedIndex==0) {
			this.setCats({});
			return;
		}
		var id  = this.eleTopCat.getValue();
		var url = '/searches/getcats/'+id+'/3/';
		var action = function(transport) {
			var data = transport.responseJSON;
			this.cache[url] = data;
			this.setCats(data);
		}
		action.url=url;
		if(!this.cache[url]) {
			new Ajax.Request(url, {
				onSuccess: action.bind(this)
			});
		} else {
			this.setCats(this.cache[url]);
		}
	},
	setCats: function(data) {
		this.eleArrow.removeClassName('subok');
		this.eleSubCat.removeClassName('subyes');
		this.setOpts(this.eleSubCat,{},false);
		if(Object.keys(data).length>0) {
			var empty = {label:'Select',value:''};
		} else {
			var empty = false;
			data = {};
		}
		this.setOpts(this.eleSubCat,data,empty);
		this.setCatStyle();
	},
	setCatStyle: function() {
		this.eleArrow.removeClassName('subok');
		this.eleSubCat.removeClassName('subyes');
		if(this.eleSubCat.options.length>0) {
			this.eleArrow.addClassName('subok');
			this.eleSubCat.addClassName('subyes');
			this.eleSubCat.disabled=false;
		} else {
			this.eleSubCat.disabled=true;
		}
	},
	updateCities: function() {
		var id = this.eleAreaId.getValue();
		var url = '/searches/getcities/'+id;
		var action = function(transport){
			var data = transport.responseJSON;
			this.cache[url] = data;
			this.setCities(data);
		}
		action.url=url;
		if(!this.cache[url]) {
			new Ajax.Request(url, {
				onSuccess: action.bind(this)
			});
		} else {
			this.setCities(this.cache[url]);
		}
	},
	setCities: function(data) {
		this.setOpts(this.eleCityId,{},false);
		if(Object.keys(data).length>0) {
			this.setOpts(this.eleCityId,data,{label:'All Cities',value:''});
		}
	},
	setOpts: function(ele,data,empty){
		ele.update();
		var i=-1;
		if(Object.keys(data).length==0) {
			ele.disabled=true;
			return;
		}
		ele.disabled=false;
		if(empty) {
			i++; ele.options[i] = new Option(empty.label,empty.value);
		}
		for(key in data){
			i++; ele.options[i] = new Option(data[key],key);
		}
		ele.focus();
	}	
  };
 
/* -- event search -- */
var eform = {
	eleStart : null,
	eleEnd   : null,
	eleStartPick : null,
	eleEndPick   : null,
	eleStartDisplay : null,
	eleEndDisplay   : null,
	eleTopCat : null,
	eleSubCat : null,
	eleArrow  : null,
	eleAreaId : null,
	eleCityId : null,
	eleSubmit : null,
	eleForm   : null,
	cache: {},
	regions: {'151':'Mountain','150':'Piedmont','149':'Coast'},
	init: function() {
		var d = new Date();
		this.eleStart        = $('SearchStart');
		this.eleStartDisplay = $('displayStart');
		this.eleStartPick    = $('pickStart');
		this.eleEnd          = $('SearchEnd');
		this.eleEndDisplay   = $('displayEnd');
		this.eleEndPick      = $('pickEnd');
		this.eleTopCat = $('SearchCategoryId');
		this.eleSubCat = $('SearchSubCategoryId');
		this.eleAreaId = $('SearchAreaId');
		this.eleCityId = $('SearchCityId');
		this.eleSubmit = $('SearchesSubmit');
		this.eleForm   = $('SearchesForm');
		var action = function() {this.updateCats();}
		this.eleTopCat.observe('change',action.bind(this));
		var action = function() {this.updateCities();}
		this.eleAreaId.observe('change',action.bind(this));
		var action = function(evt) {
			Event.stop(evt);
			this.eleForm.submit();
			return false;
		}
		this.eleSubmit.observe('click',action.bind(this));
		var action = function(evt) { 
			Event.stop(evt);
			var dx = new Date(this.eleStart.getValue());
			dx = (dx)? dx : new Date();
			var action = function(d){
				this.eleStart.value=d.format('n/d/Y');
				this.updateDateLabel();
			}
			var myPicker = new Picker(dx,action.bind(this),this.eleStart);
			return false;
		}
		this.eleStartPick.observe('click',action.bind(this));
		this.eleStart.observe('click',action.bind(this));
		var action = function(evt) { 
			Event.stop(evt);
			var dx = new Date(this.eleEnd.getValue());
			dx = (dx)? dx : new Date();
			var action = function(d){
				this.eleEnd.value=d.format('n/d/Y');
				this.updateDateLabel();
			}
			var myPicker = new Picker(dx,action.bind(this),this.eleEnd);
		}
		this.eleEndPick.observe('click',action.bind(this));
		this.eleEnd.observe('click',action.bind(this));
		this.updateDateLabel();
		this.updateCats();
	},
	updateDateLabel : function() {
		var pfx = ['Start','End'];
		for(i=0;i<pfx.length;i++) {
			var Str = pfx[i];
			var dx = new Date(this['ele'+Str].getValue());
			if(dx!='Invalid Date') {
				this['ele'+Str+'Display'].update(dx.format('l, M. d, Y'));
			} else {
				this['ele'+Str+'Display'].update();
			}
		}
	},
	updateCats: function() {
		if(this.eleTopCat.selectedIndex==0) {
			this.setCats({});
			return;
		}
		var id  = this.eleTopCat.getValue();
		var url = '/searches/getcats/'+id+'/3/';
		var action = function(transport) {
			var data = transport.responseJSON;
			this.cache[url] = data;
			this.setCats(data);
		}
		action.url=url;
		if(!this.cache[url]) {
			new Ajax.Request(url, {
				onSuccess: action.bind(this)
			});
		} else {
			this.setCats(this.cache[url]);
		}
	},
	setCats: function(data) {
		this.setOpts(this.eleSubCat,{},false);
		if(Object.keys(data).length>0) {
			var empty = {label:'Select','value':''};
		} else {
			var empty = false;
		}
		this.setOpts(this.eleSubCat,data,empty);
	},
	updateCities: function() {
		var id = this.eleAreaId.getValue();
		var url = '/searches/getcities/'+id;
		var action = function(transport){
			var data = transport.responseJSON;
			this.cache[url] = data;
			this.setCities(data);
		}
		action.url=url;
		if(!this.cache[url]) {
			new Ajax.Request(url, {
				onSuccess: action.bind(this)
			});
		} else {
			this.setCities(this.cache[url]);
		}
	},
	setCities: function(data) {
		this.setOpts(this.eleCityId,{},false);
		if(Object.keys(data).length>0) {
			this.setOpts(this.eleCityId,data,{label:'All Cities',value:''});
		}
	},
	setOpts: function(ele,data,empty){
		ele.update();
		var i=-1;
		if(Object.keys(data).length==0) {
			ele.disabled=true;
			return;
		}
		ele.disabled=false;
		if(empty) {
			i++; ele.options[i] = new Option(empty.label,empty.value);
		}
		for(key in data){
			i++; ele.options[i] = new Option(data[key],key);
		}
		ele.focus();
	}	
};

/* -- event home search -- */
var ehform = {
	eleStart : null,
	eleEnd   : null,
	eleStartPick : null,
	eleEndPick   : null,
	eleStartDisplay : null,
	eleEndDisplay   : null,
	eleTopCat : null,
	eleArrow  : null,
	eleCityId : null,
	eleSubmit : null,
	eleForm   : null,
	regions: {'151':'Mountain','150':'Piedmont','149':'Coast'},
	init: function() {
		var d = new Date();
		this.eleStart        = $('SearchStart');
		this.eleStartDisplay = $('displayStart');
		this.eleStartPick    = $('pickStart');
		this.eleEnd          = $('SearchEnd');
		this.eleEndDisplay   = $('displayEnd');
		this.eleEndPick      = $('pickEnd');
		this.eleTopCat = $('SearchCategoryId');
		this.eleCityId = $('SearchCityId');
		this.eleSubmit = $('SearchesSubmit');
		this.eleForm   = $('SearchesForm');
		var action = function(evt) {
			Event.stop(evt);
			this.eleForm.submit();
			return false;
		}
		this.eleSubmit.observe('click',action.bind(this));
		var action = function(evt) { 
			Event.stop(evt);
			var dx = new Date(this.eleStart.getValue());
			dx = (dx)? dx : new Date();
			var action = function(d){
				this.eleStart.value=d.format('n/j/Y');
				this.updateDateLabel();
			}
			var myPicker = new Picker(dx,action.bind(this),this.eleStart);
		}
		this.eleStartPick.observe('click',action.bind(this));
		this.eleStart.observe('click',action.bind(this));
		var action = function(evt) { 
			Event.stop(evt);
			var dx = new Date(this.eleEnd.getValue());
			dx = (dx)? dx : new Date();
			var action = function(d){
				this.eleEnd.value=d.format('n/j/Y');
				this.updateDateLabel();
			}
			var myPicker = new Picker(dx,action.bind(this),this.eleEnd);
		}
		this.eleEndPick.observe('click',action.bind(this));
		this.eleEnd.observe('click',action.bind(this));
		this.updateDateLabel();
	},
	updateDateLabel : function() {
		var pfx = ['Start','End'];
		for(i=0;i<pfx.length;i++) {
			var Str = pfx[i];
			var dx = new Date(this['ele'+Str].getValue());
			if(dx!='Invalid Date') {
				this['ele'+Str+'Display'].update(dx.format('M. d, Y'));
			} else {
				this['ele'+Str+'Display'].update();
			}
		}
	}	
};