/**************************************************************************************************/
/***
/***	TERNSTYLE (TM) CALENDAR JAVASCRIPT DOCUMENT (ternCal tm v2.0)
/***	-----------------------------------------------------------------------
/***	Written by Matthew Praetzel. Copyright (c) 2007 Matthew Praetzel.
/***	-----------------------------------------------------------------------
/***	Any use of these functions & scripts without written consent is prohibited.
/***
/**************************************************************************************************/

/*
{
	view : 'month',
	calendar : 1000,
	m : 1,
	y : 2008,
	mode : true,
	query : '',
	cfunc : function
}
*/
/*-----------------------
	ternCal (tm)
-----------------------*/
ternCal = {
	q : '',
	elap : '/ternstyle/images/elapsor.gif',
	init :
	function (a) {
		ternStyle().getBrowserType.apply(this);
		var d = this.todayArray();
		this.mcMonth = this.mMonth = this.eMonth = a.m ? a.m : d[1];
		this.mcYear = this.mYear = this.eYear = a.y ? a.y : d[2];
		this.q = a.query;
		this.mode = a.mode;
		this.calendar = a.calendar;
		this.cfunc = a.cfunc;
		if(a.view == 'month') {
			this.monthAtGlance();
		}
	},
	closeCalendar :
	function () {
		var th = this;
		ternStyle('ternCal').elapsor({
			image : th.elap,
			color : '#fff',
			opacity : 85,
			func : function () {
				//event being viewed
				if(th.mode) { th.addToQueue(th.saveEvent); }
				th.addToQueue(th.closeEvent);
				if(th.mode) {
					th.addToQueue(th.emptyCache);
					th.addToQueue(th.closeDraw);
				}
				//calendars
				if(th.mode) { th.ecalClose();th.closeForms(); }
				th.addToQueue(th.closeMonthAtGlance);
				//menu
				th.addToQueue(th.closeMenu);
				//url
				th.addToQueue(function () {
					clearInterval(th.timer);
					location.href = '#';
				});
				//close func
				if(th.cfunc) {
					th.addToQueue(th.cfunc);	
				}
			},
			text : 'Saving changes...'
		});
	},
	getCal :
	function (s) {
		this.calendar = s;
		this.getToMonth();
	},
	setTimer :
	function () {
		var th = this;
		th.timer = setInterval(function () {
			if((th.msie && document.URL.indexOf("#calendar-") == -1) || window.location.toString().indexOf("#calendar-") == -1) {
				clearInterval(th.timer);
				ternCal.closeCalendar();
			}
		},200);
	}
};
ternCal.extend = 
function (a,i) {
	var t = i ? i : this;
	for(k in a) {
		t[k] = a[k];
	}
	return t;
};
/*-----------------------
	QUEUE
-----------------------*/
ternCal.extend({
	queue : [],
	addToQueue :
	function (f,a) {
		this.queue.push([f,a]);
		if(!this.iq) {
			this.startQueue();
		}
	},
	startQueue :
	function () {
		if(this.queue.length > 0) {
			this.iq = true;
			var a = this.queue[0][1] ? this.queue[0][1] : [];
			this.queue[0][0].apply(this,a);
			return;
		}
		this.iq = false;
	},
	removeFromQueue :
	function () {
		this.queue.splice(0,1);
		this.startQueue();
	}
});
/*-----------------------
	MONTH AT A GLANCE
-----------------------*/
ternCal.extend({
	monthAtGlance :
	function () {
		var th = this;
		th.mag = true;th.ml = false;
		ternStyle(document.body).elapsor({
			image : th.elap,
			color : '#fff',
			opacity : 85,
			func : function () {
				th.loadMonth();
			},
			text : 'Loading Calendar...'
		});
	},
	closeMonthAtGlance :
	function () {
		var th = this;
		if(th.mag) {
			ternStyle('ternCal').elapsor({
				image : th.elap,
				color : '#fff',
				opacity : 85,
				func : function () {
					th.killMonth();
					th.cal.parentNode.removeChild(th.cal);
					th.ml = th.cal = false;
					th.removeFromQueue();
				},
				text : 'Closing Calendar...'
			});
		}
	},
	loadMonth :
	function (q) {
		var th = this;
		if(!th.ml) {
			ternAjax('ternCal').ajax({
				type : 'post',
				func : function (r) {
					th.initMonth();
					th.initMenu();
					if(th.mode) { th.initEcal(); }
					th.ml = true;
					ternStyle(document.body).hideElapsor();
					th.setUrl();
				},
				pass : true,
				node : document.body,
				empty : false,
				url : '/ternstyle/plugins/ternCal/calendar/month/',
				post : 'm='+th.mMonth+'&y='+th.mYear+'&calendar='+th.calendar+'&'+th.q
			});
		}
		else {
			if(!q) {
				ternStyle('ternCal').elapsor({
					image : th.elap,
					color : '#fff',
					opacity : 85,
					text : 'Loading '+th.monthAbbrv(th.mMonth-1)+' '+th.mYear+'...'
				});
			}
			th.killMonth();
			ternAjax('ternCal').ajax({
				type : 'post',
				func : function (r) {
					th.initMonth();
					if(th.mode) { th.ecalMonth(); }
					if(th.its) {
						th.selectDay(document.getElementById(th.its));
						th.its = false;
					}
					ternStyle('ternCal').hideElapsor();
					th.setUrl();
					th.removeFromQueue();
				},
				pass : true,
				node : 'ternCal_body',
				empty : true,
				url : '/ternstyle/plugins/ternCal/calendar/month/',
				post : 'b=1&m='+th.mMonth+'&y='+th.mYear+'&calendar='+th.calendar+'&'+th.q
			});
		}
	},
	setUrl :
	function () {
		var th = this;
		ternAjax('ternCal').ajax({
			type : 'post',
			func : function (r) {
				var h = location.href;
				h = h.substr(0,h.lastIndexOf("#"));
				h = h.substr(0,h.lastIndexOf("?"));
				location.href = h+'#calendar-'+r;
				if(!th.timer) {
					th.setTimer();
				}
			},
			pass : true,
			url : '/ternstyle/plugins/ternCal/calendar/',
			post : 'a=name&calendar='+th.calendar+'&'+th.q
		});
	},
	initMonth :
	function () {
		var th = this;
		//
		th.cal = _ternStyle.getNode('ternCal');
		th.head = _ternStyle.getNode('ternCal_head');
		th.cols = _ternStyle.getNode('ternCal_cols');
		th.body = _ternStyle.getNode('ternCal_body');
		th.grid = _ternStyle.getNode('ternCal_grid');
		th.rows = th.grid.getElementsByTagName('tr');
		th.cells = th.grid.getElementsByTagName('td');
		th.draw = _ternStyle.getNode('ternCal_draw');
		//
		ternEvents.addEvent(th.cells,function (e) { th.selectDay(e); },'click',true);
		th.setGrid();
		if(!th.ml) {
			ternEvents.addEvent(window,function () { th.setGrid(); },'resize');
			//setInterval(function () { alert(0);th.setGrid(); },1000);
		}
	},
	setGrid :
	function () {
		var d = _ternStyle.getWindowSize();
		//
		var h = ((d[1]-128)/this.rows.length);
		for(var i=0;i<this.cells.length;i++) {
			ternStyle(this.cells[i]).setStyle({
				height : h		   
			});
			ternStyle(this.cells[i].getElementsByTagName('div')[0]).setStyle({
				height : (h-22)	   
			});
		}
	},
	killMonth :
	function () {
		ternEvents.removeAllItemEvents(this.cells);
	},
	reset :
	function () {
		if(this.mode && this.se) {
			this.addToQueue(this.saveEvent,[true,true,true]);
			this.addToQueue(this.closeEvent);
			this.addToQueue(this.emptyCache);
			this.addToQueue(this.closeDraw);
		}
		else {
			this.getToMonth();
		}
	},
	getToMonth :
	function (m,y,s,c) {
		var t = 'This calendar does not currently support dates beyond 2037.';
		var d = this.getMY(m,this.mMonth,this.mYear);
		if(y && y < 2038) {
			this.mMonth = m;this.mYear = y;
		}
		else if((m == 1 || m === 0) && d[1] < 2038) {
			this.mMonth = d[0];this.mYear = d[1];
		}
		else if(m) {
			alert('This calendar does not support dates that fall in years greater than 2037.');
			return;
		}
		//
		if(s && this.mode) {
			this.addToQueue(this.saveEvent);
		}
		if(c !== false) {
			this.addToQueue(this.closeEvent);
			if(this.mode) {
				this.addToQueue(this.emptyCache);
				this.addToQueue(this.closeDraw);
			}
		}
		//
		this.addToQueue(this.loadMonth);
	}
});
/*-----------------------
	MENU
-----------------------*/
ternCal.extend({
	initMenu :
	function () {
		this.menu = document.getElementById('ternCal_menu');
		this.footer = document.getElementById('ternCal_footer');
		if(this.menu) {
			var m = this.menu.getElementsByTagName('ul')[0];
			this.mm = ternMenus(m).init({
				type : 'click',
				css : 'ternCal_mitem',
				hang : true
			});
			//this.show("ternCal_menu");
			//go to date
			this.initGTD();
			//forms
			if(this.mode) {
				this.initForms();
			}
		}
	},
	closeMenu :
	function () {
		//this.mm.killClick();
		this.menu.parentNode.removeChild(this.menu);
		this.footer.parentNode.removeChild(this.footer);
		this.menu = this.mm = false;
		//windows
		this.closeGTD();
		this.closeLegend();
		this.closeAbout();
		//queue
		this.removeFromQueue();
	},
	show :
	function (i) {
		ternCal.center(i);
		ternStyle(i).setStyle({visibility : 'visible'});
	},
	close :
	function (i) {
		ternStyle(i).setStyle({visibility : 'hidden'});
	},
	center :
	function (i,s) {
		var w = ternStyle().getWindowSize(),d = ternStyle(i).getDimensions(),t = parseInt((w[1]-d[1])/2) >= 30 ? parseInt((w[1]-d[1])/2) : 30;
		ternStyle(i).setStyle({
			'top' : t,
			'left' : (w[0]-d[0])/2
		});
		if(s) { this.show(i); }
	},
	loadWin :
	function (v,w,d,f) {
		var th = this;
		if(eval(v)) {
			th.show(w);
		}
		else {
			ternAjax('ternCal').ajax({
				type : 'post',
				func : function (r) {
					ternDrag(w).makeDraggable({
						type : 'item',
						handle : 'ternCal_alk',
						axis : 'xy'
					});
					var l = ternStyle(w).getElementsByClass('ternCal_acl',false,1)[0];
					ternEvents.addEvent(l,function () { th.close(w); },'click',false);
					th.center(w);
					th.show(w);
					if(f) { f(); }
					eval(v+' = true;');
				},
				pass : true,
				node : document.body,
				url : d
			});
		}
	},
	closeWin :
	function (w) {
		ternDrag(w).killDrag();
		var l = ternStyle(w).getElementsByClass('ternCal_acl',false,1)[0];
		ternEvents.removeAllItemEvents(l);
		var w = document.getElementById(w);
		w.parentNode.removeChild(w);
	}
});
/*-----------------------
	GO TO DATE
-----------------------*/
ternCal.extend({
	initGTD :
	function () {
		var th = this;
		th.goto = document.getElementById('ternCal_goto');
		//var l = ternStyle('ternCal_goto').getElementsByClass('ternCal_alk',false,1)[0];
		th.gtd = document.getElementById('ternCal_goto').getElementsByTagName('input')[0];
		//
		//ternDrag(l).makeDraggable('.parentNode.parentNode','xy');
		ternDrag(th.goto).makeDraggable({
			type : 'item',
			handle : 'ternCal_alk',
			axis : 'xy'
		});
		//
		ternEvents.addEvent(th.gtd,function () { th.focusGTD(); },'focus',false);
		ternEvents.addEvent(th.gtd,function () { th.blurGTD(); },"blur",false);
		ternEvents.addEvent(th.gtd,function (e) { th.fixDate(th.gtd); },"keyup",false);
		ternEvents.addEvent("ternCal_gdgo",function () { th.goGTD(); },"click",false);
		//
		var d = ternStyle("ternCal_goto").getDimensions(),w = ternStyle().getWindowSize();
		ternStyle("ternCal_goto").setStyle({
			'top' : (w[1]-d[1])/2,
			left : (w[0]-d[0])/2
		});
	},
	closeGTD :
	function () {
		ternDrag(document.getElementById('ternCal_goto').getElementsByTagName('a')[1]).killDrag();
		ternEvents.removeAllItemEvents([this.gtd,'ternCal_gdgo']);
		this.goto.parentNode.removeChild(this.goto);
	},
	focusGTD :
	function () {
		this.fv = this.iv = this.gtd.value;
	},
	blurGTD :
	function () {
		if(!this.isValid(this.gtd.value)) {
			this.gtd.value = this.fv;
		}
		this.fv = this.iv = false;
	},
	goGTD :
	function () {
		this.close('ternCal_goto');
		this.getToDay(this.gtd.value);
	},
	getToDay :
	function (d) {
		var l = d ? "l"+this.dateNum(d) : "l"+this.dateNum(this.todayStamp());
		var d = d ? this.dateArray(d) : this.todayArray();
		if(this.mMonth == d[1] && this.mYear == d[2]) {
			var d = document.getElementById(l);
			this.selectDay(d);
		}
		else {
			this.its = l;
			this.getToMonth(d[1],d[2],true);
		}
	},
	selectDay :
	function (e) {
		if(e) {
			ternStyle(this.cells).removeClass('ternCal_tday');
			var s = e.nodeName ? e : ternEvents.eventSource(e);
			while(s.parentNode.parentNode != this.grid) {
				s = s.parentNode;
			}
			this.td = s.getElementsByTagName('ul')[0];
			this.sd = this.numToStamp(this.td.id.replace('d',''));
			ternStyle(s).addClass('ternCal_tday');
		}
	}
});
/*-----------------------
	EVENT FUNCTIONS
-----------------------*/
ternCal.extend({
	showEvent :
	function (i) {
		var th = this;
		if(th.se) {
			if(th.mode) { th.addToQueue(th.saveEvent); }
			th.addToQueue(th.closeEvent);
			if(th.mode) { 
				th.addToQueue(th.emptyCache);
				th.addToQueue(th.closeDraw);
			}
		}
		//event info
		this.addToQueue(function () {
			ternStyle('ternCal').elapsor({
				image : th.elap,
				color : '#fff',
				opacity : 85,
				func : function () {
					ternAjax('ternCal').ajax({
						type : 'post',
						func : function (r) {
							//alert(r);
							th.se = true;
							if(th.mode) { th.initDraw(); }
							ternStyle('ternCal').hideElapsor();
							th.removeFromQueue();
						},
						pass : true,
						node : 'ternCal_draw',
						empty : true,
						url : '/ternstyle/plugins/ternCal/calendar/event/',
						post : 'event='+i+'&'+th.q
					});	
				},
				text : 'Loading event...'
			});
		});
	},
	closeEvent :
	function () {
		if(this.se) {
			//reset variables
			this.eo = this.ed = this.fv = this.iv = this.se = this.te = null;
		}
		this.removeFromQueue();
	}
});
/*-----------------------
	EVENT CALENDAR
-----------------------*/
ternCal.extend({
	fixDate :
	function (i) {
		var th = this,i = i ? i : th.ed;
		var c = th.caret(i),v = i.value.substr(c-1,1);
		i.value = i.value.replace(/[^0-9\/]+/,"");
		var d = i.value.split("/");
		//fix if not even close
		var s = i.value.match(/\//g);
		if((s && s.length != 2) || (d.length != 3)) {
			i.value = th.iv;
			th.fixCursor(c,i);
			return;
		}
		//format month, day, year
		var f = th.iv.split("/");
			//year
		y = th.clean(d[2]);
		var yn = parseInt(y);
			//month
		var m = th.fixMD(true,d[0],d[1],d[2],f[0],v,12);
		var mn = parseInt(m[0].replace(/^[0]/,""));
		c = m[1] ? m[1] : c;
			//day
		var dt = th.getLength(d[0]-1,d[2]);
		var d = th.fixMD(false,d[0],d[1],d[2],f[1],v,dt);
		var dn = parseInt(d[0].replace(/^[0]/,""));
		c = d[1] ? d[1] : c;
		//set dates
		i.value = m[0] + "/" + d[0] + "/" + y;
		th.fixCursor(c,i);
		th.iv = i.value;
	},
	fixMD :
	function (w,m,d,y,o,v,z) {
		var th = this,t = o,d = w ? m : d,c = false;
		if(d != o) {
			t = d != "" && d != "0" ? parseInt(d.replace(/^[0]/,"")) : "";
			t = w == "min" && d == "0" ? 0 : t;
			if(d.length >= 2 && t > z) {
				t = v != 0 || (v == 0 && w == "min") ? "0" + v : ""+o;
				c = w ? 2 : 5;
			}
			else if(d.length > 2 && t <= z) {
				t = t.toString().length == 1 ? "0"+t : ""+t;
				c = w ? 2 : 5;
			}
			else if(d.length == 2 && t.toString().length == 1) {
				t = "0" + t;
			}
			else if(t == "") {
				c = w ? 0 : 3;
			}
			else if(d.length == 1) {
				t = "0" + t;
				c = w ? 2 : 5;
			}
		}
		return [t.toString(),c];
	}
});
/*-----------------------
	LEGEND
-----------------------*/
ternCal.extend({
	legend :
	function () {
		var th = this;
		th.loadWin('th.ll','ternCal_legend','/ternstyle/plugins/ternCal/calendar/legend/',function () {
			ternAjax('ternCal').ajax({
				script : true,
				scripts : {
					'js' : ['/ternstyle/plugins/ternColor/ternColor.js']
				},
				func : function () {
					var l = ternStyle('ternCal_legend').getElementsByClass('ternCal_acl',false,1)[0];
					if(th.mode) {
						ternEvents.addEvent(l,function () { th.saveLegend(); },'click',false);
						th.colors();
					}
				}
			});
		});
	},
	closeLegend :
	function () {
		if(this.ll) {
			this.closeWin('ternCal_legend');
			if(this.ilc) {
				this.saveLegend();
			}
			this.ilc = this.ll = false;
			if(this.mode) {
				this.closeColors();	
			}
		}
	}
});
/*-----------------------
	ABOUT
-----------------------*/
ternCal.extend({
	about :
	function () {
		this.loadWin('th.abl','ternCal_about','/ternstyle/plugins/ternCal/calendar/about/');
	},
	closeAbout :
	function () {
		if(this.abl) {
			this.closeWin('ternCal_about');
		}
	}
});
/*-----------------------
	DATE FUNCTIONS
-----------------------*/
ternCal.extend({
	month :
	function (m,y) {
		var th = this,a,f,d,l,w;
		//month length
		a = th.getLength(m,y);
		//first day of month UNIX
		f = th.timestamp(1,m,y);
		//first day of month week index
		d = (new Date(f)).getDay();
		//last day of the month UNIX
		l = th.timestamp(th.getLength(m,y),m,y);
		//last day of the month week index
		w = (new Date(l)).getDay()+1;
		//	length, first day unix, first day index, last day unix, last day index 
		return [a,f,d,l,w];
	},
	fixMonth :
	function (m) {
		var ms = ["january","february","march","april","may","june","july","august","september","october","november","december"];
		for(var i=0;i<ms.length;i++) {
			if(m.toLowerCase() == ms[i]) {
				return i+1;
			}
		}
		return false;
	},
	monthAbbrv :
	function (i) {
		var m = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
		return m[i];
	},
	getMY :
	function (w,m,y) {
		m = parseInt(m);y = parseInt(y);
		if(w == 1) {
			m = m + 1;
			if(m == 13) { m = 1;y = y+1; }
		}
		else {
			m = m - 1;
			if(m == 0) { m = 12;y = y-1; }
		}
		return [m,y]
	},
	getLength :
	function (m,y) {
		var l = 32-new Date(y,m,32).getDate();
		return l;
	},
	timestamp :
	function (h,m,s,d,mo,y) {
		if(arguments.length > 3) {
			return Date.UTC(y,mo,d,h,m,s,0);
		}
		else {
			return Date.UTC(s,m,h);
		}	
	},
	todayStamp :
	function () {
		var d = new Date();
		return Date.UTC(d.getFullYear(),d.getMonth(),d.getDate());
	},
	todayArray :
	function () {
		var d = new Date();
		return [d.getDate(),d.getMonth()+1,d.getFullYear()];
	},
	dateToStamp :
	function (v) {
		v = this.dateArray(v,true);
		return this.timestamp(v[0],v[1],v[2]);
	},
	dateArray :
	function (v,i) {
		v = v.split("/");
		v[1] = i ? parseInt(this.clean(v[1])) : v[1];
		v[0] = i ? parseInt(this.clean(v[0]))-1 : v[0];
		v[2] = i ? parseInt(v[2]) : v[2];
		return [v[1],v[0],v[2]];
	},
	stampArray :
	function (s,i) {
		s = new Date(s);
		var d = i ? s.getUTCDate() : s.getUTCDate().toString();
		var m = i ? s.getUTCMonth() : (s.getUTCMonth()+1).toString();
		var y = i ? s.getUTCFullYear() : s.getUTCFullYear().toString();
		return [d,m,y];
	},
	valuesToStamp :
	function (d,t,m) {
		d = this.dateArray(d,true);
		t = t.split(":");
		t[0] = parseInt(t[0]);
		if(m == "pm" && t[0] != 12) {
			t[0] = t[0]+12;
		}
		else if(m == "am" && t[0] == 12) {
			t[0] = 0;
		}
		return this.timestamp(t[0],t[1],0,d[0],d[1],d[2]);
	},
	dateNum :
	function (v) {
		if(v.toString().indexOf("/") != -1) {
			v = this.dateArray(v);
			return v[2]+v[1]+v[0];
		}
		else {
			v = this.stampArray(v);
			v[0] = v[0].length == 1 ? "0"+v[0] : v[0];
			v[1] = v[1].length == 1 ? "0"+v[1] : v[1];
			return v[2]+v[1]+v[0];
		}
	},
	numToStamp :
	function (v) {
		var y = v.substr(0,4),m = v.substr(4,2),d = v.substr(6);
		return this.timestamp(this.clean(d),parseInt(this.clean(m))-1,y);
	},
	isValid :
	function (v) {
		var v = v.split("/"),d = this.getLength(v[0]-1,v[2]);
		for(k in v) {
			v[k] = parseInt(v[k].replace(/^[0]/,""));
		}
		if(v[0] > 0 && v[0] < 13 && v[1] > 0 && v[1] <= d && v[2].toString().length == 4 && v[2] > 1000) {
			return true;
		}
		return false;
	},
	timeValid :
	function (v) {
		var v = v.split(":");
		for(k in v) {
			v[k] = v[k] == "00" ? 0 : parseInt(v[k].replace(/^[0]/,""));
		}
		if(v[0] > 0 && v[0] < 13 && v[1] >= 0 && v[1] <= 59) {
			return true;
		}
		return false;
	},
	clean :
	function (n) {
		return n.replace(/^(0)+/,"").toString();
	},
	startStamp :
	function (i,w,f,b) {
		var th = this,d,t,a;
		d = i.getElementsByTagName("input")[4].value;
		t = i.getElementsByTagName("input")[5].value;
		a = i.getElementsByTagName("a")[1].childNodes[0].nodeValue;
		return th.valuesToStamp(d,t,a);
	}
});
/*-----------------------
	MISC. FUNCTIONS
-----------------------*/
ternCal.extend({
	font :
	function (b) {
		this.fsize = this.fsize ? this.fsize : 0;
		this.fsize = b ? this.fsize+1 : (this.fsize-1);
		this.fsize = this.fsize > 3 ? 3 : this.fsize;
		this.fsize = this.fsize < 0 ? 0 : this.fsize;
		document.getElementById('ternCal_month').className = '';
		ternStyle('ternCal_month').addClass('ternCal_fsize'+this.fsize);
	},
	caret :
	function (i) {
		if(document.selection) {
			var c = document.selection.createRange().duplicate();
		}
		else {
			var c = i ? i.selectionStart : this.ed.selectionStart;
		}
		return c;
	},
	fixCursor :
	function (p,i) {
		var i = i ? i : this.ed;
		if(document.selection) {
			var r = i.createTextRange();
			r.move("character",p);
			r.select();
		}
		else {
			i.setSelectionRange(p,p);
		}
	}
});