/*** @name QDNG Combines QuickForm, DatePicker, Notify & Grid & strips comments */
var Grid = new Class({
table: false, headers: [], 	data: [], 
initialize: function(table){
this.table = table;
this.getHeaders();
this.getData();
this.stripe();
return this;	}, 
getHeaders: function(){
if (!this.table.getFirst('thead')) return false;
this.headers = this.table.getFirst('thead').getElements('tr th');
this.headers.each(function(h, index){
h.store('asc', false);
if (h.hasClass('sort')) h.addEvent('click', function(){
this.headers.each(function(h2){ h2.removeClass('asc').removeClass('desc'); });
if (h.retrieve('asc')){
h.store('asc', false);
h.addClass('desc');
} else {
h.store('asc', true);
h.addClass('asc');
}
this.sort(index);
}.bind(this));}, this);}, 
getData: function(){
this.data = [];
rows = this.table.getFirst('tbody').getChildren();
for (j = 0; j < rows.length; j++){
if (rows[j + 1] && rows[j + 1].hasClass('row-child')){
rows[j].store('child', rows[j + 1]);
this.data.push(rows[j]);
j++;
} else this.data.push(rows[j].store('child', false));}}, 
sort: function(index){
data = [];
sortType = this.headers[index].getProperty('axis');
asc = this.headers[index].retrieve('asc');
if (this.data.length > 0) this.data.each(function(row, i){
cells = row.getElements('td');
if (cells.length < this.headers.length) return false;
value = (cells[index].getProperty('axis') ? cells[index].getProperty('axis') : cells[index].get('text'));
if (sortType == 'int' || sortType == 'float'){
if (value.contains('$') || value.contains(',')) value = value.replace(/\$/g, '').replace(/,/g, '').toFloat();
else value = value.toFloat();
} else if (sortType == 'date'){
if (value.contains('-')){
str = value.split('-');
value = str[1] + '/' + str[2] + '/' + str[0];}
value = Date.parse(value);}
data.push({'index': i, 'value': value, 'row': row});}, this);
if (sortType == 'int' || sortType == 'float' || sortType == 'date') data.sort(this.sortNumeric);
else data.sort(this.sortCaseInsensitive);
if (!asc) data.reverse();
this.data = [];
data.each(function(d, i){
this.data.push(d.row);}, this);
this.stripe();}, 
sortNumeric: function(a, b){
if ($type(a.value) != 'number') a.value = 0;
if ($type(b.value) != 'number') b.value = 0;
return a.value - b.value;}, 
sortCaseInsensitive: function(a, b){
a.value = a.value.toLowerCase();
b.value = b.value.toLowerCase();
if (a.value == b.value) return 0;
if (a.value < b.value) return -1;
return 1;}, 
stripe: function(){
this.data.each(function(row, i){
row.removeClass('r1').removeClass('r2');
this.table.getElement('tbody').adopt(row.addClass((i % 2 == 0 ? 'r1' : 'r2')));
if (row.retrieve('child')) this.table.getElement('tbody').adopt(row.retrieve('child'));
}, this);}});
window.addEvent('domready', function(){
$$('div.grid').getElement('table').each(function(t){
new Grid(t);});});
/** * @name DatePicker */
var DatePicker = new Class({
options: {
onShow: function(dp){
dp.setStyle('visibility', 'visible');}, 
onHide: function(dp){
dp.setStyle('visibility', 'hidden');}, 
className: 'DatePicker', 
monthNames: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], 
daysInMonth: [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31], 
dayNames: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], 
format: 'mm/dd/yyyy', 
yearStart: new Date().getFullYear(), 
yearRange: 10, 
yearOrder: 'asc', 
width: 155, 
position: 'absolute', 
offsets: {'x':0, 'y':20}, 
delay: 100, 
zIndex: 1000}, 
initialize: function(el, options){
if (!el || el.retrieve('active')) return false;
el.store('active', true);
if (!$('DATEPICKER_CSS')) new Asset.css('/js/widgets/DatePicker/css/DatePicker.css', {id: 'DATEPICKER_CSS'});
if (options) this.setOptions(options);
else if (el.alt) this.setOptions(JSON.decode(el.alt));
this.active = false;
if (el.value.length > 9){
switch (this.options.format){
case 'mm/dd/yyyy': d = el.value.split('/'); this.year = d[2].toInt(); (this.month = d[0].toInt() - 1); this.day = d[1].toInt(); break;
case 'yyyy-mm-dd': d = el.value.split('-'); this.year = d[0].toInt(); (this.month = d[1].toInt() - 1); this.day = d[2].toInt(); break;
case 'yyyy.mm.dd': d = el.value.split('.'); this.year = d[0].toInt(); (this.month = d[1].toInt() - 1); this.day = d[2].toInt(); break;
case 'mm.dd.yyyy': d = el.value.split('.'); this.year = d[2].toInt(); (this.month = d[0].toInt() - 1); this.day = d[1].toInt(); break;
default: d = new Date(); this.year = d.getFullYear(); this.month = d.getMonth(); this.day = d.getDate(); break;}
} else {
d = new Date(); this.year = d.getFullYear(); this.month = d.getMonth(); this.day = d.getDate();}
this.dp =  new Element('div', {
'class': this.options.className + '-Container', 
'styles': {
				'position':this.options.position, 
				'top':'0px', 
				'left':'0px', 
				'z-index':this.options.zIndex, 
				'visibility':'hidden'
			}
		}).injectInside(document.body);
		this.wrapper = new Element('div', {
			'class':this.options.className + '-Wrapper', 
			'styles': {
				'position':'absolute', 
				'width':this.options.width + 'px'
			}
		}).injectInside(this.dp);
		this.setup(el);
	},
	setup: function(el){
		el.addEvent('click', function(){
			this.position(el);
			this.build(el);
		}.bind(this));
		var destroy = this.destroy.bind(this);
		this.wrapper.addEvent('mouseleave', destroy);
	}, 
	build: function(el){
		this.wrapper.empty();
		date = new Date();
		date.setFullYear(this.year, this.month, 1);
		this.year % 4 == 0 ? this.options.daysInMonth[1] = 29 : this.options.daysInMonth[1] = 28;
		var firstDay = 1 - date.getDay();
		monthSel = new Element('select', {'class':this.options.className + '-monthSelect'});
		for (var m = 0; m < this.options.monthNames.length; m++){
			monthSel.options[m] = new Option(this.options.monthNames[m], m);
			if (this.month == m) monthSel.options[m].selected = true;
		}
		yearSel = new Element('select', {'class':this.options.className + '-yearSelect'});
		i = 0;
		if (this.options.yearOrder == 'desc'){
			for (var y = this.options.yearStart; y > (this.options.yearStart - this.options.yearRange - 1); y--){
				yearSel.options[i] = new Option(y, y);
				if (this.year == y) yearSel.options[i].selected = true;
				i++;
			}
		} else {
			for (var y = this.options.yearStart; y < (this.options.yearStart + this.options.yearRange + 1); y++){
				yearSel.options[i] = new Option(y, y);
				if (this.year == y) yearSel.options[i].selected = true;
				i++;
			}
		}
		calTable = new Element('table', {'styles':{'width':'100%'}}).injectInside(this.wrapper);
		calTableTbody = new Element('tbody').injectInside(calTable);
		new Element('tr').adopt(new Element('td', {'class':'nav', 'styles':{'text-align':'center'}, 'colspan':'7'}).adopt(monthSel).adopt(yearSel)).injectInside(calTableTbody);
		calDayNameRow = new Element('tr').injectInside(calTableTbody);
		for (var i = 0; i < this.options.dayNames.length; i++){
			calDayNameCell = new Element('td', {'class':'dayName', 'styles':{'text-align':'center', 'width':'14%'}}).set('text', this.options.dayNames[i].substr(0, 1)).injectInside(calDayNameRow);
		}
		date2 = new Date();
		while (firstDay <= this.options.daysInMonth[this.month]){
			calDayRow = new Element('tr').injectInside(calTableTbody);
			for (i = 0; i < 7; i++){
				if ((firstDay <= this.options.daysInMonth[this.month]) && (firstDay > 0)){
					calDayCell = new Element('td', {'class':'day', 'styles':{'cursor':'pointer', 'text-align':'center'}, 'axis':this.year + '-' + (this.month + 1) + '-' + firstDay}).set('text', firstDay).injectInside(calDayRow);
					if (date2.getFullYear() == this.year && date2.getMonth() == this.month && date2.getDate() == firstDay) calDayCell.addClass('current');
				} else {
					calDayCell = new Element('td', {'class':'empty'}).set('text', ' ').injectInside(calDayRow);
				}
				firstDay++;	}}
		$$('div.DatePicker-Wrapper td.day').each(function(d){
			d.onclick = function(){
				ds = d.axis.split('-');
				el.value = this.formatValue(ds[0], ds[1], ds[2]);
				this.hide();
			}.bind(this);
		}.bind(this));
		monthSel.onfocus = function(){ this.active = true; }.bind(this);
		monthSel.onblur = function(){ this.active = false; }.bind(this);
		monthSel.onchange = function(){
			this.month = monthSel.value.toInt();
			this.year = yearSel.value.toInt();
			el.value = this.formatValue(this.year, this.month + 1, 1);
			this.active = false;
			this.build(el);
		}.bind(this);
		yearSel.onfocus = function(){ this.active = true; }.bind(this);
		yearSel.onblur = function(){ this.active = false; }.bind(this);
		yearSel.onchange = function(){
			this.month = monthSel.value.toInt();
			this.year = yearSel.value.toInt();
			el.value = this.formatValue(this.year, this.month + 1, 1);
			this.active = false;
			this.build(el);
		}.bind(this);
		this.timer = this.show.delay(this.options.delay, this);
	}, 
	destroy: function(event){
		$clear(this.timer);
		this.timer = this.hide.delay(this.options.delay, this);
	}, 
	position: function(el){
		this.coords = el.getCoordinates();
		this.dp.setStyles({'top':this.coords.top + 'px', 'left':(this.coords.left + this.options.offsets.x) + 'px', 'width':this.coords.width + 'px', 'padding-top': this.coords.height + 'px'});
	}, 
	show: function(){
		this.fireEvent('onShow', [this.dp]);
	}, 
	hide: function(){
		if (!this.active) this.fireEvent('onHide', [this.dp]);
	}, 
	formatValue: function(year, month, day){
		var dateStr = '';
		if (day < 10) day = '0' + day;
		if (month < 10) month = '0' + month;
		dateStr = this.options.format.replace( /dd/i, day ).replace( /mm/i, month ).replace( /yyyy/i, year );
		this.month = month.toInt() - 1;
		this.year = year.toInt();
		return dateStr;
	}
});
DatePicker.implement(new Events);
DatePicker.implement(new Options);
window.addEvent('domready', function(){
	$each($$('input.DatePicker'), function(el){
		new DatePicker(el);
	});
});

/** * @name Notify */
var Notify = new Class({
	options: {
		text: '', 
		classes: [], 
		delay: 4000
	}, 
	initialize: function(options){
		if (!options) return false;
		else this.setOptions(options);
		if (!$('NOTIFY_CSS')) new Asset.css('/js/widgets/Notify/css/Notify.css', {id: 'NOTIFY_CSS'});
		(function(){
			this.timer = false;
			this.build();
		}.bind(this)).delay(100);
	}, 
	build: function(){
		this.id = 'notify_' + $random(0, 10000);
		this.msg = new Element('div', {'id': this.id, 'class':'Notify', 'styles': {'visibility': 'hidden'}}).adopt(this.smTitle = new Element('div', {'class': 'sm-title'})).adopt(this.smMessage = new Element('div', {'class': 'sm-text'})).inject(document.body);
		if (this.timer) $clear(this.timer);
		this.msg.setStyle('opacity', 1);
		this.smTitle.removeProperty('class').addClass('sm-title');
		this.smTitle.set('text', '');
		this.smMessage.set('text', '');
		this.text = this.options.text.split('::');
		if (this.text.length > 1){
			this.smTitle.set('text', this.text[0]);
			this.smMessage.set('html', this.text[1]);
		} else this.smTitle.set('text', this.text[0]);
		if (this.options.classes && this.options.classes.length > 0) this.options.classes.each(function(c){ this.smTitle.addClass(c); }.bind(this));
		this.height = this.msg.getCoordinates().height;
		$$('.Notify').each(function(n){
			if (n.get('id') != this.id) n.setStyle('bottom', (n.getStyle('bottom').toInt() + this.height + 10));
		}.bind(this));
		this.msg.setStyle('visibility', 'visible');
		this.timer = (function(){ this.msg.fade('out'); }.bind(this)).delay(this.options.delay);
	}
});
Notify.implement(new Options);
/** * @name Grid  */
var Grid = new Class({
	table: false, 
	headers: [], 
	data: [], 
	initialize: function(table){
		this.table = table;
		this.getHeaders();
		this.getData();
		this.stripe();
		return this;
	}, 
	getHeaders: function(){
		if (!this.table.getFirst('thead')) return false;
		this.headers = this.table.getFirst('thead').getElements('tr th');
		this.headers.each(function(h, index){
			h.store('asc', false);
			if (h.hasClass('sort')) h.addEvent('click', function(){
				this.headers.each(function(h2){ h2.removeClass('asc').removeClass('desc'); });
				if (h.retrieve('asc')){
					h.store('asc', false);
					h.addClass('desc');
				} else {
					h.store('asc', true);
					h.addClass('asc');
				}
				this.sort(index);
			}.bind(this));
		}, this);
	}, 
	getData: function(){
		this.data = [];
		rows = this.table.getFirst('tbody').getChildren();
		for (j = 0; j < rows.length; j++){
			if (rows[j + 1] && rows[j + 1].hasClass('row-child')){
				rows[j].store('child', rows[j + 1]);
				this.data.push(rows[j]);
				j++;
			} else this.data.push(rows[j].store('child', false));
		}
	}, 
sort: function(index){
data = [];
sortType = this.headers[index].getProperty('axis');
asc = this.headers[index].retrieve('asc');
if (this.data.length > 0) this.data.each(function(row, i){
cells = row.getElements('td');
if (cells.length < this.headers.length) return false;
value = (cells[index].getProperty('axis') ? cells[index].getProperty('axis') : cells[index].get('text'));
if (sortType == 'int' || sortType == 'float'){
if (value.contains('$') || value.contains(',')) value = value.replace(/\$/g, '').replace(/,/g, '').toFloat();
else value = value.toFloat();
} else if (sortType == 'date'){	if (value.contains('-')){str = value.split('-');
value = str[1] + '/' + str[2] + '/' + str[0];}
value = Date.parse(value);}
data.push({'index': i, 'value': value, 'row': row});}, this);
if (sortType == 'int' || sortType == 'float' || sortType == 'date') data.sort(this.sortNumeric);
else data.sort(this.sortCaseInsensitive);
if (!asc) data.reverse();
this.data = [];
data.each(function(d, i){this.data.push(d.row);}, this);
this.stripe();}, 
sortNumeric: function(a, b){
if ($type(a.value) != 'number') a.value = 0;
if ($type(b.value) != 'number') b.value = 0;
return a.value - b.value;}, 
sortCaseInsensitive: function(a, b){
a.value = a.value.toLowerCase();
b.value = b.value.toLowerCase();
if (a.value == b.value) return 0;
if (a.value < b.value) return -1;
return 1;}, 
stripe: function(){
this.data.each(function(row, i){
row.removeClass('r1').removeClass('r2');
this.table.getElement('tbody').adopt(row.addClass((i % 2 == 0 ? 'r1' : 'r2')));
if (row.retrieve('child')) this.table.getElement('tbody').adopt(row.retrieve('child'));	}, this);}});
window.addEvent('domready', function(){	$$('div.grid').getElement('table').each(function(t){new Grid(t);});});
