/*jslint evil: true */
/*global ActiveXObject, XMLHttpRequest, prompt, alert, confirm, document, location, window, navigator, escape */
var FASTREP = {
	debug: (location.href.toLowerCase().indexOf('debug') !== -1),
	reinited: false,
	fr_up: 38,
	fr_down: 40,
	fr_left: 37,
	fr_right: 39,
	fr_escape: 27,
	fr_enter: 13,
	fr_tab: 9,
	fr_months_long: [
		'January',
		'February',
		'March',
		'April',
		'May',
		'June',
		'July',
		'August',
		'September',
		'October',
		'November',
		'December'
	],
	fr_months_short: [
		'Jan',
		'Feb',
		'Mar',
		'Apr',
		'May',
		'Jun',
		'Jul',
		'Aug',
		'Sep',
		'Oct',
		'Nov',
		'Dec'
	],
	fr_days_long: [
		'Sunday',
		'Monday',
		'Tuesday',
		'Wednesday',
		'Thursday',
		'Friday',
		'Saturday'
	],
	fr_days_short: [
		'Sun',
		'Mon',
		'Tue',
		'Wed',
		'Thu',
		'Fri',
		'Sat'
	],
	remedial: function() {
//		String.prototype.supplant = function (o) {
//			return this.replace(/{([^{}]*)}/g,
//				function (a, b) {
//					var r = o[b];
//					return typeof r === 'string' || typeof r === 'number' ? r : a;
//				}
//			);
//		};
		String.prototype.trim = function () {
			return this.replace(/^\s+|\s+$/g, "");
		};
	}(),
	init: function() {
		var scripts = document.getElementsByTagName('script'),
			scripts_len = scripts.length,
			scripts_cnt = 0,
			frscript,
			runonload = true;
		for(scripts_cnt = 0; scripts_cnt < scripts_len; scripts_cnt++) {
			if(scripts[scripts_cnt].src.indexOf('fastrep.js') !== -1) {
				if(scripts[scripts_cnt].parentNode.nodeName.toLowerCase() === 'body') {
					runonload = false;
					frscript = scripts[scripts_cnt];
				}
			}
		}
		if(runonload) {
			if(window.addEventListener) {
				window.addEventListener(
					'load', 
					function(){FASTREP.initChildren();}, 
					false
				);
			} else if(window.attachEvent) {
				window.attachEvent(
					'onload', 
					function(){FASTREP.initChildren();}
				);
			}
		} else {
			if(window.addEventListener) {
				frscript.addEventListener(
					'load', 
					function(){FASTREP.initChildren();}, 
					false
				);
			} else if(window.attachEvent) {
				window.attachEvent(
					'onload', 
					function(){FASTREP.initChildren();}
				);
			}
		}
	}(),
	initChildren: function() {
		var cnt = '';
		for(cnt in FASTREP) {
			if(FASTREP[cnt] && FASTREP[cnt].init) {
				FASTREP[cnt].init();
			}
		}
	},
	reinit: function() {
		FASTREP.reinited = true;
		FASTREP.initChildren();
	}
};

FASTREP.dom = {
	prevent: function(e) {
		try {
			e.preventDefault();
			e.stopPropagation();
		} catch(err) {
			window.event.returnValue = false;
			window.event.cancelBubble = true;
		}
	},
	addEvent: function(el, evnt, meth) {
		if(!el) {
			return false;
		}
		if(window.addEventListener) {
			el.addEventListener(evnt, meth, false);
		} else if(window.attachEvent) {
			el.attachEvent('on' + evnt, meth);
		}
	},
	removeEvent: function(el, evnt, meth) {
		if(!el) {
			return false;
		}
		if(window.removeEventListener) {
			el.removeEventListener(evnt, meth, false);
		} else if(window.detachEvent) {
			el.detachEvent('on' + evnt, meth);
		}
	},
	create: function(el, attrs, evnts) {
		var attr,
			evnt;
		if(!el) {
			return false;
		}
		el = document.createElement(el);
		if(!attrs || typeof attrs !== 'object') {
			attrs = {};
		}
		if(attrs instanceof Array) {
			attrs = {};
		}
		if(!evnts || typeof evnts !== 'object' || !evnts instanceof Array) {
			evnts = [];
		}
		for(attr in attrs) {
			if(attrs.hasOwnProperty(attr)) {
				if(attr.indexOf('style.') !== -1) {
					el.style[attrs.replace('style.', '')] = attrs[attr];
				} else if(attr === 'innerHTML') {
					el.innerHTML = attrs[attr];
				} else if(attr === 'class') {
					el.className += ' ' + attrs[attr];
				} else if(attr === 'id') {
					el.id = attrs[attr];
				} else {
					el.setAttribute(attr, attrs[attr]);
				}
			}
		}
		for(evnt in evnts) {
			if(evnts.hasOwnProperty(evnt)) {
				if(evnts[evnt].hasOwnProperty('on') && 
					evnts[evnt].hasOwnProperty('method') && 
					typeof evnts[evnt].method === 'function') {
				}
				FASTREP.dom.addEvent(el, evnts[evnt].on, evnts[evnt].method);
			}
		}
		return el;
	}
};

FASTREP.xss = {
	get: function(url) {
		document.body.appendChild(FASTREP.dom.create('script', {'id': 'fr-xss-' + Math.round(Math.random()*1000) + '-' + new Date().getTime(), 'src': url}));
	}
}

FASTREP.ajax = {
	connections: [],
	get: function(url, vars, callback, method, spinner) {
		if(spinner !== false) {
			spinner = true;
		}
		var conn_len = this.connections.length;
		this.connections[conn_len] = new this.ajax(url, vars, callback, method, spinner);
		this.connections[conn_len].index = conn_len;
		return this.connections[conn_len];
	},
	ajax: function(url, vars, callback, method, spinner) {
		var self = this;
		this.index = 0;
		this.url = url;
		this.vars = vars;
		this.callback = callback || false;
		this.method = method === 'GET' ? 'GET' : 'POST';
		this.contentType = '';
		this.responseText = '';
		this.responseJSON = false;
		this.responseXML = false;
		this.locked = true;
		this.error = false;
		this.phperror = false;
		this.spinner = spinner;
		this.success = function() {
			if(self.xhr.readyState === 4 && (self.xhr.status ? self.xhr.status > 0 : true)) {
				if(self.xhr.status === 200) {
					self.responseText = self.xhr.responseText;
					switch(self.xhr.getResponseHeader('Content-type')) {
						case 'text/xml':
							self.contentType = 'xml';
							break;
						case 'application/json':
							self.contentType = 'json';
							break;
						case 'text/plain':
							self.contentType = 'text';
							break;
						default:
							self.contentType = 'text';
							break;
					}
					if(self.responseText.toLowerCase().indexOf('<b>parse error</b>: ') !== -1 || self.responseText.toLowerCase().indexOf('<b>fatal error</b>: ') !== -1 || self.responseText.toLowerCase().indexOf('<b>notice</b>: ') !== -1 || self.responseText.toLowerCase().indexOf('<b>warning</b>: ') !== -1) {
						if(confirm('An error was encountered on the server.  It is possible that your request did not complete.  You may be able to try your request again by clicking "OK" or you may ignore this message by clicking "Cancel."  If you click "OK" and your request did complete, you may inadvertently duplicate your request.')) {
							self.error = true;
							if(self.callback) {
								self.callback.call(self);
							}
						}
						if(window.FASTREP && window.FASTREP.debug && FASTREP.debug) {
							self.phperror = /Parse.*\d+/.exec(self.responseText.replace(/\n/g, '').replace(/(<([^>]+)>)/ig, ''));
							alert('The following PHP error was thrown from ' + self.url + '?' + self.vars + ': \n\n' + self.phperror + '\n\n' + self.responseText);
						}
					}
					if(self.contentType === 'xml') {
						self.responseXML = self.xhr.responseXML;
					}
					if(self.contentType === 'json') {
						try {
							self.responseJSON = eval('(' + self.responseText + ')');
						}
						catch(error) {
							if(confirm('An error was encountered on the server.  It is possible that your request did not complete.  You may be able to try your request again by clicking "OK" or you may ignore this message by clicking "Cancel."  If you click "OK" and your request did complete, you may inadvertently duplicate your request.\n\n' + error)) {
								self.error = true;
								if(self.callback) {
									self.callback.call(self);
								}
							}
							if(window.FASTREP && window.FASTREP.debug && FASTREP.debug) {
								alert('There was an error in the server output from ' + self.xhr.url + '?' + self.xhr.vars + '.  The following string was issued:\n\n' + self.xhr.responseText);
							}
						}
					}
					if(self.callback) {
						self.callback.call(self);
						if(document.getElementById('fr-ajax-load')) {
							document.getElementById('fr-ajax-load').parentNode.removeChild(document.getElementById('fr-ajax-load'));
						}
					}
				} else {
					if(self.xhr.responseText.toLowerCase().indexOf('<b>parse error</b>: ') !== -1 || self.xhr.responseText.toLowerCase().indexOf('<b>fatal error</b>: ') !== -1 || self.xhr.responseText.toLowerCase().indexOf('<b>notice</b>: ') !== -1 || self.xhr.responseText.toLowerCase().indexOf('<b>warning</b>: ') !== -1) {
						if(confirm('An error was encountered on the server.  It is possible that your request did not complete.  You may be able to try your request again by clicking "OK" or you may ignore this message by clicking "Cancel."  If you click "OK" and your request did complete, you may inadvertently duplicate your request.')) {
							self.error = true;
							if(self.callback) {
								self.callback.call(self);
							}
						}
						if(window.FASTREP && window.FASTREP.debug && FASTREP.debug) {
							alert('The following error was issued:\n\n' + self.xhr.responseText);
						}
					} else {
						alert('There was a problem reaching the server.  Please check your Internet connection or try your request later.\n\nIf an error follows, please complete a bug request form including the error.\n\n' + self.xhr.responseText);
						self.error = true;
						if(self.callback) {
							self.callback.call(self);
						}
						if(window.FASTREP && window.FASTREP.debug && FASTREP.debug) {
							alert('The following error was issued:\n\n' + self.xhr.responseText);
						}
					}
				}
				self.locked = false;
			}
		};
		this.xhr = function() {
			var retxhr;
			try {
				retxhr = new XMLHttpRequest();
			} catch(err1) {
				try {
					retxhr = new ActiveXObject('Msxml2.XMLHTTP');
				} catch(err2) {
					try {
						retxhr = new ActiveXObject('Microsoft.XMLHTTP');
					} catch(err3) {
						retxhr = false;
						if(window.FASTREP && window.FASTREP.debug && FASTREP.debug) {
							alert('The XMLHttpRequest object is not available on this browser.');
						}
					}
				}
			}
			return retxhr;
		}();
		this.get = function() {
			if(!self.xhr) {
				self.error = true;
				return false;
			}
			if(self.method.toLowerCase() === 'get') {
				if(self.url.indexOf('?') === -1) {
					self.url += '?';
				}
				self.url += self.vars;
				self.vars = null;
			}
			self.xhr.onreadystatechange = self.success;
			
			self.xhr.open(self.method, self.url, true);
			
			if(self.method.toLowerCase() === 'get') {
				self.xhr.setRequestHeader('If-Modified-Since', 'Tue, 1 Jan 1980 00:00:00 GMT');
			} else {
				self.xhr.setRequestHeader('If-Modified-Since', 'Tue, 1 Jan 1980 00:00:00 GMT');
				self.xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
			}
			
			if(!document.getElementById('fr-ajax-load') && self.spinner) {
				document.body.appendChild(FASTREP.dom.create('div', {'id': 'fr-ajax-load'}));
			}
			self.xhr.send(self.vars);
			return true;
		}();
	}
};

FASTREP.form = {
	init: function() {
		var frm = document.forms,
			frm_len = frm.length,
			frm_cnt,
			frm_cur,
			frm_cur_els,
			frm_cur_els_len,
			frm_cur_els_cnt,
			frm_cur_els_cur,
			frdom = FASTREP.dom,
			frform = FASTREP.form;
		for(frm_cnt = 0; frm_cnt < frm_len; frm_cnt++) {
			frm_cur = frm[frm_cnt];
			for(frm_cur_els_cnt = 0, frm_cur_els = frm_cur.elements, frm_cur_els_len = frm_cur_els.length; frm_cur_els_cnt < frm_cur_els_len; frm_cur_els_cnt++) {
				frm_cur_els_cur = frm_cur_els[frm_cur_els_cnt];
				if(frm_cur_els_cur.nodeName.toLowerCase() === 'select' && frm_cur_els_cur.className.toLowerCase().indexOf('fr-drilldown-') > -1) {
					frform.setDrilldown(frm_cur_els_cur);
				}
				if(frm_cur_els_cur.nodeName.toLowerCase() === 'input' && (frm_cur_els_cur.className.indexOf('integer') > -1 || frm_cur_els_cur.className.indexOf('decimal') > -1)) {
					frdom.addEvent(frm_cur_els_cur, 'keyup', frform.numbers);
					frdom.addEvent(frm_cur_els_cur, 'blur', frform.formatNumber);
				}
				if(frm_cur_els_cur.nodeName.toLowerCase() === 'input' && frm_cur_els_cur.className.indexOf('money') > -1) {
					frdom.addEvent(frm_cur_els_cur, 'keyup', frform.money);
				}
				if(frm_cur_els_cur.nodeName.toLowerCase() === 'input' && frm_cur_els_cur.className.indexOf('time') > -1) {
					frdom.addEvent(frm_cur_els_cur, 'keyup', frform.time);
				}
				if(frm_cur_els_cur.nodeName.toLowerCase() === 'input' && frm_cur_els_cur.className.indexOf('date') > -1) {
					frdom.addEvent(frm_cur_els_cur, 'keyup', frform.dates);
					frdom.addEvent(frm_cur_els_cur, 'blur', frform.dateFormat);
					frform.addDatePicker(frm_cur_els_cur);
				}
				if(frm_cur_els_cur.nodeName.toLowerCase() === 'button') {
					frdom.addEvent(frm_cur_els_cur, 'dblclick', function(){alert('Please do not double click submit buttons.  This can result in multiple submissions!');});
				}
			}
			if(frm_cur.enctype.toLowerCase() !== 'multipart/form-data') {
				if((frm_cur_els_cur.nodeName.toLowerCase() === 'input' && frm_cur_els_cur.getAttribute('type').toLowerCase() === 'submit') || frm_cur_els_cur.nodeName.toLowerCase() === 'button') {
					frdom.addEvent(frm_cur_els_cur, 'click', frform.buttons);
				}
				frdom.addEvent(frm_cur, 'submit', frdom.prevent);
				frdom.addEvent(frm_cur, 'submit', frform.hijack);
			}
		}
	},
	setDrilldown: function(el) {
		var cns = el.className.split(' '),
			cns_len = cns.length,
			cns_cnt = 0,
			cns_cur = false,
			cns_cur_t = false,
			cns_cur_t_len = 0,
			cns_cur_t_cnt = 0;
		if(window.opera) {
			return false;
		}
		for(cns_cnt = 0; cns_cnt < cns_len; cns_cnt++) {
			cns_cur = cns[cns_cnt];
			if(cns_cur.indexOf('fr-drilldown-') > -1) {
				cns_cur = cns_cur.split('fr-drilldown-')[1];
				cns_cur_t = document.getElementById(cns_cur);
				if(cns_cur_t) {
					el.drilldownto = cns_cur_t;
					el.drilldown = [];
					el.drilldown[0] = cns_cur_t.getElementsByTagName('option')[0].parentNode.removeChild(cns_cur_t.getElementsByTagName('option')[0]);
					for(cns_cur_t = cns_cur_t.getElementsByTagName('optgroup'), cns_cur_t_cnt = cns_cur_t.length-1; cns_cur_t_cnt >= 0; cns_cur_t_cnt--) {
						el.drilldown[cns_cur_t[cns_cur_t_cnt].getAttribute('label')] = cns_cur_t[cns_cur_t_cnt].parentNode.removeChild(cns_cur_t[cns_cur_t_cnt]);
					}
				}
				FASTREP.dom.addEvent(el, 'change', FASTREP.form.doDrilldown);
				FASTREP.form.doDrilldown(el);
			}
		}
	},
	doDrilldown: function(el) {
		var cnt = 0;
		if(typeof el.className === 'undefined') {
			el = this;
		}
		if(typeof el.className === 'undefined' && window.event) {
			el = window.event.srcElement;
		}
		for(cnt = el.drilldownto.childNodes.length-1; cnt >= 0; cnt--) {
			el.drilldownto.removeChild(el.drilldownto.childNodes[cnt]);
		}
		if(el.value === "0" || el.value === '') {
			el.drilldownto.appendChild(el.drilldown[0]);
		} else {
			el.drilldownto.appendChild(el.drilldown[el.options[el.selectedIndex].text]);
		}
	},
	addDatePicker: function(el) {
		var today = new Date(),
			tFY = today.getFullYear(),
			tM = (today.getMonth()+1) > 9 ? (today.getMonth()+1) : '0' + (today.getMonth()+1),
			tD = today.getDate() > 9 ? today.getDate() : '0' + today.getDate(),
			cdiv = FASTREP.dom.create('div', {'class': 'calbutton'}, [{'on': 'click', 'method': FASTREP.form.showDatePicker}]);
		FASTREP.dom.addEvent(document.body, 'keyup', function(e) {if(e.keyCode == '27'){FASTREP.form.hideDatePicker(e)}});
		if(el.value === '' && el.className.indexOf('date-no-default') === -1) {
			el.value = tM + '/' + tD + '/' + tFY;
		}
		el.parentNode.parentNode.className += ' fr-cal';
		el.parentNode.style.position = 'relative';
		cdiv.parentInput = el;
		el.parentNode.appendChild(cdiv);
	},
	showDatePicker: function(e) {
		var el = e.target || e.srcElement;
		document.body.className += ' overlay';
		var overlay = FASTREP.dom.create('div', {'id': 'fr-date-overlay'}, [{'on': 'click', 'method': FASTREP.form.hideDatePicker}]),
			picker = FASTREP.dom.create('div', {'id': 'fr-date-picker'}, [{'on': 'click', 'method': FASTREP.form.hideDatePicker}]),
			closer = FASTREP.dom.create('img', {'id': 'fr-date-close', 'src': 'http://files.fastrep.com/images/actions-close-32.png', 'alt': 'Close', 'title': 'Close'}, [{'on': 'click', 'method': FASTREP.form.hideDatePicker}]),
			cdate = new Date();
		if(el.parentInput && el.parentInput.value.split('/').length === 3) {
			cdate = new Date(
					el.parentInput.value.split('/')[2],
					Number(el.parentInput.value.split('/')[0]) - 1,
					el.parentInput.value.split('/')[1]
				);
		}
		picker.parentInput = el.parentInput;
		overlay.appendChild(picker);
		overlay.appendChild(closer);
		document.body.appendChild(overlay);
		FASTREP.form.setDatePickerPosition();
		FASTREP.form.populateDatePicker(cdate.getFullYear(), cdate.getMonth(), cdate.getDate());
		FASTREP.dom.addEvent(window, 'scroll', FASTREP.form.setDatePickerPosition);
	},
	hideDatePicker: function(e) {
		var el = e.target || e.srcElement;
		document.body.className = document.body.className.replace(' overlay', '');
		var overlay = document.getElementById('fr-date-overlay');
		if(el.nodeName.toLowerCase() !== 'span') {
			FASTREP.dom.removeEvent(window, 'scroll', FASTREP.form.setDatePickerPosition);
			if(overlay) {
				overlay.parentNode.removeChild(overlay);
			}
		}
	},
	setDatePickerPosition: function() {
		var offsetLeft = window.pageXOffset ? window.pageXOffset : document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft,
			offsetTop = window.pageYOffset ? window.pageYOffset : document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop,
			overlay = document.getElementById('fr-date-overlay');
		if(overlay) {
			overlay.style.top = offsetTop + 'px';
			overlay.style.left = offsetLeft + 'px';
		}
	},
	populateDatePicker: function(year, month, day) {
		var picker = document.getElementById('fr-date-picker'),
			cdate = new Date(year, month, day),
			day_count = 1,
			start_on_weekday = 0,
			weekday_count = 0,
			els1 = FASTREP.dom.create('h1'),
			els2 = FASTREP.dom.create('ol'),
			els3;
		picker.innerHTML = '';
		els3 = FASTREP.dom.create('span', {'id': 'fr-date-picker-prev-year', 'innerHTML': '&laquo;'}, [{'on': 'click', 'method': FASTREP.form.movePickerRange}]);
		els3.setAttribute('dir', -1);
		els3.affect = 'year';
		els1.appendChild(els3);
		els3 = FASTREP.dom.create('span', {'id': 'fr-date-picker-prev-month', 'innerHTML': '&lsaquo;'}, [{'on': 'click', 'method': FASTREP.form.movePickerRange}]);
		els3.setAttribute('dir', -1);
		els3.affect = 'year';
		els1.appendChild(els3);
		els3 = FASTREP.dom.create('span', {'id': 'fr-date-picker-current', 'innerHTML': FASTREP.fr_months_long[month] + ' ' + year});
		els3.cdate = cdate;
		els1.appendChild(els3);
		els3 = FASTREP.dom.create('span', {'id': 'fr-date-picker-next-month', 'innerHTML': '&rsaquo;'}, [{'on': 'click', 'method': FASTREP.form.movePickerRange}]);
		els3.setAttribute('dir', 1);
		els3.affect = 'month';
		els1.appendChild(els3);
		els3 = FASTREP.dom.create('span', {'id': 'fr-date-picker-next-year', 'innerHTML': '&raquo;'}, [{'on': 'click', 'method': FASTREP.form.movePickerRange}]);
		els3.setAttribute('dir', 1);
		els3.affect = 'month';
		els1.appendChild(els3);
		picker.appendChild(els1);
		for(day_count = 1; month === new Date(year, month, day_count).getMonth(); day_count++) {
			if(day_count === 1) {
				start_on_weekday = new Date(year, month, day_count).getDay();
				while(weekday_count < start_on_weekday) {
					els2.appendChild(FASTREP.dom.create('li'));
					weekday_count++;
				}
			}
			els1 = FASTREP.dom.create('li', {'innerHTML': day_count, 'class': day_count === day ? 'fr-date-picker-current' : '', 'title': ((month+1) > 9 ? (month+1) : '0'+(month+1)) + '/' + (day_count > 9 ? day_count : '0'+day_count) + '/' + year}, [{'on': 'click', 'method': FASTREP.form.setPickerValue}]);
			els2.appendChild(els1);
		}
		picker.appendChild(els2);
	},
	movePickerRange: function(e) {
		var el = e.target || e.srcElement,
			tdate = false,
			cdate = document.getElementById('fr-date-picker-current').cdate,
			year = cdate.getFullYear(),
			month = cdate.getMonth(),
			day = cdate.getDate();
		switch(el.id) {
			case 'fr-date-picker-prev-year':
				tdate = new Date(Number(year)-1, month, day);
			break;
			case 'fr-date-picker-next-year':
				tdate = new Date(Number(year)+1, month, day);
			break;
			case 'fr-date-picker-prev-month':
				tdate = new Date(year, Number(month)-1, day);
			break;
			case 'fr-date-picker-next-month':
				tdate = new Date(year, Number(month)+1, day);
			break;
			default:
				tdate = new Date();
			break;
		}
		FASTREP.form.populateDatePicker(
			tdate.getFullYear(),
			tdate.getMonth(),
			tdate.getDate()
		);
	},
	setPickerValue: function(e) {
		var inp = e.target || e.srcElement,
			picker;
		picker = document.getElementById('fr-date-picker');
		picker.parentInput.value = inp.title;
	},
	buttons: function(e) {
		var bttn = e.target || e.srcElement;
		bttn.form.clicked = bttn;
	},
	formatNumber: function(e) {
		var inp = e.target || e.srcElement;
		inp.value = inp.value.replace(/[^\d\.]/g, '');
	},
	dateFormat: function(e) {
		var inp = e.target || e.srcElement,
			parts = inp.value.split('/');
		if(inp.value != '') {
			if(parts[0].length < 2) {
				parts[0] = '0' + parts[0];
			}
			if(parts[1].length < 2) {
				parts[1] = '0' + parts[1];
			}
			if(parts[2].length < 4) {
				parts[2] = '20' + parts[2];
			}
		}
		inp.value = parts.join('/');
	},
	dates: function(e) {
		var inp = e.target || e.srcElement,
			parts = inp.value.split('/'),
			cdate = new Date(),
			parts_length = parts.length,
			parts_count = 0,
			useArrows = false;
		if(parts_length === 3) {
			for(parts_count = 0; parts_count < parts_length; parts_count++) {
				parts[parts_count] = Number(parts[parts_count]);
			}
			switch(e.keyCode) {
				case FASTREP.fr_up:
					parts[1] += 1;
					useArrows = true;
				break;
				case FASTREP.fr_down:
					parts[1] -= 1;
					useArrows = true;
				break;
				case FASTREP.fr_right:
					parts[0] += 1;
					useArrows = true;
				break;
				case FASTREP.fr_left:
					parts[0] -= 1;
					useArrows = true;
				break;
				default:
					return;
				break;
			}
			if(useArrows) {
				cdate = new Date(parts[2], parts[0]-1, parts[1]);
				inp.value = (cdate.getMonth()+1) > 9 ? (cdate.getMonth()+1) : '0' + (cdate.getMonth()+1);
				inp.value += '/';
				inp.value += cdate.getDate() > 9 ? cdate.getDate() : '0' + cdate.getDate();
				inp.value += '/';
				inp.value += cdate.getFullYear();
				if(inp.value.indexOf('NaN') !== -1) {
					inp.value = '01/01/1970';
				}
			}
		}
	},
	numbers: function(e) {
		var inp = e.target || e.srcElement,
			isInt = inp.className.indexOf('integer') > -1,
			isDec = inp.className.indexOf('decimal') > -1,
			isUnsigned = inp.className.indexOf('unsigned') > -1,
			isNegative = inp.className.indexOf('negative') > -1,
			tofixed = 2,
			tofixedreg = /tofixed-(\d+)/;
		if(inp.className.indexOf('tofixed-') !== -1) {
			tofixed = tofixedreg.exec(inp.className)[1];
		}
		switch(e.keyCode) {
			case FASTREP.fr_up:
				if(isInt) {
					if(!isNegative || isNegative && Number(inp.value) + 1 <= 0) {
						inp.value = Number(inp.value) + 1;
					}
				} else {
					if(!isNegative || isNegative && Number(inp.value) + 0.1 <= 0) {
						inp.value = Number(inp.value) + 0.1;
						inp.value = Number(inp.value).toFixed(tofixed);
					}
				}
			break;
			case FASTREP.fr_down:
				if(isInt) {
					if(!isUnsigned || isUnsigned && Number(inp.value) - 1 >= 0) {
						inp.value = Number(inp.value) - 1;
					}
				} else {
					if(!isUnsigned || isUnsigned && Number(inp.value) - 0.1 >= 0) {
						inp.value = Number(inp.value) - 0.1;
						inp.value = Number(inp.value).toFixed(tofixed);
					}
				}
			break;
			case FASTREP.fr_right:
				return;
//				if(isInt) {
//					if(!isNegative || isNegative && Number(inp.value) + 10 <= 0) {
//						inp.value = Number(inp.value) + 10;
//					}
//				} else {
//					if(!isNegative || isNegative && Number(inp.value) + 1 <= 0) {
//						inp.value = Number(inp.value) + 1;
//						inp.value = Number(inp.value).toFixed(tofixed);
//					}
//				}
			break;
			case FASTREP.fr_left:
				return;
//				if(isInt) {
//					if(!isUnsigned || isUnsigned && Number(inp.value) - 10 >= 0) {
//						inp.value = Number(inp.value) - 10;
//					}
//				} else {
//					if(!isUnsigned || isUnsigned && Number(inp.value) - 1 >= 0) {
//						inp.value = Number(inp.value) - 1;
//						inp.value = Number(inp.value).toFixed(tofixed);
//					}
//				}
			break;
			default:
				return;
			break;
		}
		if(inp.value.indexOf('NaN') !== -1) {
			inp.value = 0;
		}
	},
	time: function(e) {
		var inp = e.target || e.srcElement,
			val_str = inp.value.trim().toLowerCase(),
			val_arr = [],
			d = new Date();
		d.setTime(Date.parse('Jan 1, 2008 ' + val_str));
		switch(e.keyCode) {
			case FASTREP.fr_up:
				// +Hour
				d.setHours(d.getHours()+1);
			break;
			case FASTREP.fr_down:
				// -Hour
				d.setHours(d.getHours()-1);
			break;
			case FASTREP.fr_right:
				// +Min
				d.setMinutes(d.getMinutes()+1);
			break;
			case FASTREP.fr_left:
				// -Min
				d.setMinutes(d.getMinutes()-1);
			break;
			default:
				return;
			break;
		}
		val_arr[0] = d.getHours();
		val_arr[1] = d.getMinutes();
		val_arr[2] = '';
		
		if(val_arr[0] > 12) {
			val_arr[0] = val_arr[0]-12;
			val_arr[2] = 'pm';
		} else if(val_arr[0] == 12) {
			val_arr[2] = 'pm';
		} else if(val_arr[0] == 0) {
			val_arr[0] = 12;
			val_arr[2] = 'am';
		} else {
			val_arr[2] = 'am';
		}
		
		if(val_arr[1] < 10) {
			val_arr[1] = '0' + val_arr[1].toString();
		}
		if(val_arr[0] < 10) {
			val_arr[0] = '0' + val_arr[0].toString();
		}		
		inp.value = val_arr[0] + ':' + val_arr[1] + ' ' + val_arr[2];
	},
	money: function(e) {
		var inp = e.target || e.srcElement,
			tofixed = 2,
			isUnsigned = inp.className.indexOf('unsigned') > -1,
			isNegative = inp.className.indexOf('negative') > -1,
			val = inp.value.replace('$', '');
		switch(e.keyCode) {
			case FASTREP.fr_up:
				if(!isNegative || isNegative && Number(val) + 0.1 <= 0) {
					val = Number(val) + 0.1;
					val = Number(val).toFixed(tofixed);
				}
			break;
			case FASTREP.fr_down:
				if(!isUnsigned || isUnsigned && Number(val) - 0.1 >= 0) {
					val = Number(val) - 0.1;
					val = Number(val).toFixed(tofixed);
				}
			break;
			case FASTREP.fr_right:
				return;
//				if(!isNegative || isNegative && Number(val) + 1 <= 0) {
//					val = Number(val) + 1;
//					val = Number(val).toFixed(tofixed);
//				}
			break;
			case FASTREP.fr_left:
				return;
//				if(!isUnsigned || isUnsigned && Number(val) - 1 >= 0) {
//					val = Number(val) - 1;
//					val = Number(val).toFixed(tofixed);
//				}
			break;
			default:
				return;
			break;
		}
		if(val.indexOf('NaN') !== -1) {
			val = 0.00;
		}
		if(val.indexOf('-') !== -1) {
			val = val.replace('-', '-$');
		} else {
			val = '$' + val;
		}
		inp.value = val;
	},
	hijack: function(e) {
		var frm = e.target || e.srcElement,
			frm_cnt,
			fmr_els,
			fmr_els_len,
			frm_els_cur,
			frm_els_cur_val,
			frm_els_cur_type,
			frm_els_cur_name,
			query = 'ajax=true',
			tmp,
			xhr;
		if(frm.nodeName.toLowerCase() !== 'form') {
			frm = frm.form;
		}
		window.scrollTo(0, frm.parentNode.offsetTop + frm.parentNode.parentNode.offsetTop);
		if(frm.clicked && frm.clicked.nodeName.toLowerCase() == 'button') {
			frm.clicked.insertBefore(FASTREP.dom.create('div', {'id': 'fr-ajax-load', 'innerHTML': '&nbsp;'}), frm.clicked.firstChild);
		}
		for(frm_cnt = 0, fmr_els = frm.elements, fmr_els_len = fmr_els.length; frm_cnt < fmr_els_len; frm_cnt++) {
			frm_els_cur = fmr_els[frm_cnt];
			try {
				frm_els_cur_type = frm_els_cur.type.toLowerCase();
			} catch(err) {
				frm_els_cur_type = frm_els_cur.nodeName.toLowerCase();
			}
			frm_els_cur_name = frm_els_cur.name;
			frm_els_cur_val = frm_els_cur.value;
			if(frm_els_cur_name) {
				switch(frm_els_cur_type) {
					case 'submit':
						if(frm.clicked === frm_els_cur) {
							query += '&' + frm_els_cur_name + '=' + escape(frm_els_cur_val);
						}
					break;
					case 'hidden':
					case 'text':
					case 'password':
					case 'textarea':
						query += '&' + frm_els_cur_name + '=' + escape(frm_els_cur_val);
					break;
					case 'select':
					case 'select-one':
					case 'select-multiple':
						if(frm_els_cur.multiple) {
							for(tmp = 0; tmp < frm_els_cur.options.length; tmp++) {
								if(frm_els_cur.options[tmp].selected) {
									query += '&' + frm_els_cur_name + '=' + escape(frm_els_cur.options[tmp].value);
								}
							}
						} else {
							query += '&' + frm_els_cur_name + '=' + escape(frm_els_cur_val);
						}
					break;
					case 'radio':
					case 'checkbox':
						if(frm_els_cur.checked) {
							if(frm_els_cur_val) {
								query += '&' + frm_els_cur_name + '=' + escape(frm_els_cur_val);
							} else {
								query += '&' + frm_els_cur_name + '=on';
							}
						}
					break;
				}
			}
			frm_els_cur.disabled = true;
		}
		setTimeout(
			function() {
				xhr = FASTREP.ajax.get(frm.action, query, FASTREP.form.hijackCallback, frm.method.toUpperCase());
				xhr.form = frm;
				if(xhr.error) {
					FASTREP.form.hijackCallback.call(xhr);
				}
			}, 50);
	},
	hijackCallback: function() {
		var frm = this.form,
			frm_cnt,
			fmr_els,
			fmr_els_len,
			rtext = this.responseText,
			rjson = this.responseJSON,
			slideup = false,
			slidedown = false,
			error,
			palert,
			t = 0,
			evnt = false,
			reloadWait = function() {
				if(t == 0) {
					t++;
					setTimeout(reloadWait, 5000);
				} else {
					location.href = rjson.geturl;
				}
			};
		try {
			for(frm_cnt = 0, fmr_els = frm.elements, fmr_els_len = fmr_els.length; frm_cnt < fmr_els_len; frm_cnt++) {
				fmr_els[frm_cnt].disabled = false;
			}
			if(this.error) {
				frm.submit();
				return false;
			}
		} catch(err) {}
		if(rjson) {
			if(rjson.status === 1) {
				if(rjson.alert) {
					palert = document.getElementById('fr-system-message');
					if(palert) {
						document.body.removeChild(palert);
					}
					palert = FASTREP.dom.create('div', {'id': 'fr-system-message', 'innerHTML': '<h1>Complete</h1>' + rjson.alert.replace(/(\r\n|\r|\n)/, '<br>') + '<p class="fr-button-cont"><a href="javascript:void(0);" onclick="document.body.removeChild(this.parentNode.parentNode);" onkeypress="document.body.removeChild(this.parentNode.parentNode);" class="fr-ui-close" id="fr-ui-close">Close</a></p>', 'class': 0});
					palert.style.top = '-200px'
					document.body.appendChild(palert);
					document.getElementById('fr-ui-close').focus();
					slidedown = function() {
						palert = document.getElementById('fr-system-message');
						if(palert) {
							if(parseFloat(palert.style.top) < 0) {
								palert.style.top = (parseFloat(palert.style.top) + 10) + 'px';
								setTimeout(slidedown, 1);
							} else {
								palert.style.top = '0px';
							}
						}
					};
					slidedown();
					
					slideup = function() {
						palert = document.getElementById('fr-system-message');
						if(palert) {
							if(parseInt(palert.className) > 5) {
								if(parseFloat(palert.style.top) > -200) {
									palert.style.top = (parseFloat(palert.style.top) - 10) + 'px';
									palert.className = parseInt(palert.className)+1;
									setTimeout(slideup, 10);
								} else {
									document.body.removeChild(palert);
								}
							} else {
								palert.className = parseInt(palert.className)+1;
								setTimeout(slideup, 1000);
							}
						}
					};
					slideup();
				}
				if(rjson.update && document.getElementById('status')) {
					document.getElementById('status').innerHTML = rjson.update;
				}
				if(rjson.reset) {
					frm.reset();
					window.scrollTo(0,0);
				}
				if(rjson.body) {
					setTimeout(
						function() {
							document.body.innerHTML = rjson.body;
							setTimeout(FASTREP.reinit, 50);
						}
						, 50);
				}
				if(rjson.geturl) {
					if(rjson.alert) {
						reloadWait();
					} else {
						location.href = rjson.geturl;
					}
				}
			} else if(rjson.status === 'confirm') {
				if(confirm(rjson.status_message)) {
					document.getElementById(frm.id).appendChild(FASTREP.dom.create('input', {type: 'hidden', 'name': 'override', 'value': 'true'}));
					try {
						rtext = document.createEvent('HTMLEvents');
						rtext.initEvent('submit', true, true);
						document.getElementById(frm.id).dispatchEvent(rtext);
					} catch(err) {
						document.getElementById(frm.id).fireEvent('onsubmit');
					}
					return;
				}
			} else {
				if(rjson.errors.length > 0) {
//					for(error in rjson.errors) {
//						if(rjson.errors.hasOwnProperty(error)) {
							palert = document.getElementById('fr-system-message');
							if(palert) {
								document.body.removeChild(palert);
							}
							palert = FASTREP.dom.create('div', {'id': 'fr-system-message', 'class': 'fr-system-message-error', 'innerHTML': '<h1>Error!</h1>' + rjson.errors[0].replace(/(\r\n|\r|\n)/, '<br>') + '<p class="fr-button-cont"><a href="javascript:void(0);" onclick="document.body.removeChild(this.parentNode.parentNode);" onkeypress="document.body.removeChild(this.parentNode.parentNode);" class="fr-ui-close" id="fr-ui-close">Close</a></p>'});
							palert.count = 0;
							palert.style.opacity = 1;
							palert.style.top = '-200px'
							document.body.appendChild(palert);
							document.getElementById('fr-ui-close').focus();
							slidedown = function() {
								palert = document.getElementById('fr-system-message');
								if(palert) {
									if(parseFloat(palert.style.top) < 0) {
										palert.style.top = (parseFloat(palert.style.top) + 10) + 'px';
										setTimeout(slidedown, 1);
									} else {
										palert.style.top = '0px';
										slideup();
									}
								}
							};
							slidedown();
							
							slideup = function() {
								palert = document.getElementById('fr-system-message');
								if(palert) {
									if(parseInt(palert.count) > 5) {
										if(parseFloat(palert.style.top) > -200) {
											palert.style.top = (parseFloat(palert.style.top) - 10) + 'px';
											palert.count = parseInt(palert.count)+1;
											setTimeout(slideup, 10);
										} else {
											document.body.removeChild(palert);
										}
									} else {
										palert.count = parseInt(palert.count)+1;
										setTimeout(slideup, 1000);
									}
								}
							};
//						}
//					}
				}
			}
		} else {
			if(rtext.substring(0, 6).toLowerCase() === 'alert:') {
				alert(rtext.substring(6, rtext.length));
			}
			if(rtext.toLowerCase().indexOf('<b>parse error</b>: ') !== -1 || rtext.toLowerCase().indexOf('<b>fatal error</b>: ') !== -1 || rtext.toLowerCase().indexOf('<b>warning</b>: ') !== -1 || rtext.toLowerCase().indexOf('<b>notice</b>: ') !== -1) {
				if(confirm('An error was encountered on the server.  Click "OK" to complete a bug report or "Cancel" to ignore this error.')) {
					document.getElementById('footer').appendChild(FASTREP.dom.create('span', {innerHTML: '<br><b>XHR Response: </b>' + rtext}));
					if(document.createEvent) {
						evnt = document.createEvent('HTMLEvents');
						evnt.initEvent('click', true, true);
						document.getElementById('fr-report-bug').dispatchEvent(evnt);
					} else {
						try {
							document.getElementById('fr-report-bug').fireEvent('onclick');
						} catch(err) {
							document.getElementById('fr-report-bug').onclick();
						}
					}
				}
				if(window.FASTREP && window.FASTREP.debug && FASTREP.debug) {
					alert('The following error was issued:\n\n' + rtext);
				}
			}
		}
	}
};

FASTREP.ui = {
	init: function() {
		FASTREP.ui.applyBugReport();
		FASTREP.ui.applyCollapse();
		FASTREP.ui.applyDetailsCollapse();
		FASTREP.ui.applyPagenate();
		FASTREP.ui.applySort();
		FASTREP.ui.applyTabs();
		FASTREP.ui.applyFontSize();
		FASTREP.ui.applyPrinterFilter();
		FASTREP.ui.applyAccountSelect();
		FASTREP.ui.applyToolTips();
		FASTREP.ui.applyRadioText();
		/* Specific UI Fixes */
		FASTREP.ui.applyMergeConfirm();
		FASTREP.ui.applySalesCallReport();
		FASTREP.ui.applyMultiChecks();
		FASTREP.ui.applyDemoPayeeSelect();
		FASTREP.ui.applyDemoPayable();
//		FASTREP.ui.applyView();
		FASTREP.ui.applySalesCallEmailHijack();
//		FASTREP.ui.applyOnResizeGraph();
		FASTREP.ui.applyDemoTotals();
//		FASTREP.ui.applyDemoHours();
		FASTREP.ui.applyDemoPayeeTotal();
		FASTREP.ui.applySalesCallConfirmDate();
		FASTREP.ui.applySalesCallDateChange();
	},
	storeActivated: function(res) {
		if(res.status == 1) {
			alert('The store was successfully activated. Please continue with your sales call.');
		} else {
			alert('The store was not activated.  Please find the store and manually edit it.');
		}
	},
	applyDetailsCollapse: function() {
		var all = [],
			t = document.getElementsByTagName('table'),
			d = document.getElementsByTagName('div'),
			len = t.length,
			cnt = 0,
			el = false;
		for(cnt=0; cnt < len; cnt++) {
			all[all.length] = t[cnt];
		}
		len = d.length;
		for(cnt=0; cnt < len; cnt++) {
			all[all.length] = d[cnt];
		}
		len = all.length;
		for(cnt=0; cnt < len; cnt++) {
			if(all[cnt].className.indexOf('fr-has-details') !== -1) {
				if(all[cnt].parentNode.className.indexOf('fr-hide-details') !== -1) {
					el = FASTREP.dom.create('div', {'class': 'screen-only', 'innerHTML': '<label><input type="checkbox" onclick="if(this.parentNode.parentNode.parentNode.className.indexOf(\'fr-hide-details\') !== -1) {this.parentNode.parentNode.parentNode.className = this.parentNode.parentNode.parentNode.className.replace(/fr-hide-details/g, \'\');} else {this.parentNode.parentNode.parentNode.className+=\' fr-hide-details\';}">Show Details</label>'});
				} else {
					el = FASTREP.dom.create('div', {'class': 'screen-only', 'innerHTML': '<label><input type="checkbox" onclick="checked" onclick="if(this.parentNode.parentNode.parentNode.className.indexOf(\'fr-hide-details\') !== -1) {this.parentNode.parentNode.parentNode.className = this.parentNode.parentNode.parentNode.className.replace(/fr-hide-details/g, \'\');} else {this.parentNode.parentNode.parentNode.className+=\' fr-hide-details\';}">Show Details</label>'});
				}
				all[cnt].parentNode.insertBefore(el, all[cnt]);
			}
		}
	},
	doPaginatedSelect: function(el) {
		var l = location.href.replace(/#.*$/, '');
		if(isNaN(l.split('/')[l.split('/').length-2])) {
			if(l.indexOf('?') === -1) {
				l = l.replace(/\#.*/, '') + el.value + '/?';
			} else {
				l = l.replace(/\?/, '/' + el.value + '/?');
			}
		} else {
			l = l.replace(/\/\d+\//, '/' + el.value + '/');
			if(l.indexOf('?') === -1) {
				l += '?';
			}
		}
		location.href=l;
	},
	applyRadioText: function() {
		var all = document.getElementsByTagName('input'),
			len = all.length,
			cnt = 0,
			cur = false;
		for(cnt = 0; cnt < len; cnt++) {
			cur = all[cnt];
			if(cur.className.indexOf('fr-ui-radio-') !== -1) {
				FASTREP.dom.addEvent(
					cur, 'focus',
					function(e) {
						var el = e.target ? e.target : e.srcElement,
							chk = el.className.replace('fr-ui-radio-', '');
						if(document.getElementById(chk)) {
							document.getElementById(chk).checked = true;
						}
					}
				);
			}
		}
	},
	applyToolTips: function() {
		var all = document.getElementsByTagName('*'),
			len = all.length,
			cnt = 0,
			cur = false;
		for(cnt = 0; cnt < len; cnt++) {
			cur = all[cnt];
			if(cur.getAttribute('title')) {
				cur.tooltip = cur.getAttribute('title');
				cur.setAttribute('title', '');
				switch(cur.nodeName.toLowerCase()) {
					case 'input':
					case 'textarea':
					case 'select':
						FASTREP.dom.addEvent(cur, 'focus', FASTREP.ui.showToolTipsBelow);
						FASTREP.dom.addEvent(cur, 'blur', FASTREP.ui.hideToolTipsBelow);
					break;
					default:
						FASTREP.dom.addEvent(cur, 'mouseout', FASTREP.ui.hideToolTipsHover);
						FASTREP.dom.addEvent(cur, 'mouseover', FASTREP.ui.showToolTipsHover);
					break;
				}
			}
		}
	},
	hideToolTipsHover: function() {
		if(document.getElementById('fr-ui-tool-tip-hover')) {
			document.getElementById('fr-ui-tool-tip-hover').parentNode.removeChild(document.getElementById('fr-ui-tool-tip-hover'));
		}
	},
	showToolTipsHover: function(e) {
		var el = e.target ? e.target : e.srcElement,
			append = false,
			d = FASTREP.dom.create('div', {id: 'fr-ui-tool-tip-hover', 'innerHTML': '<div id="fr-ui-tool-tip-hover-arrow"></div><div id="fr-ui-tool-tip-hover-arrow-overlay"></div><div id="fr-ui-tool-tip-hover-text">' + (el.tooltip ? el.tooltip.replace(/(\r|\n|\r\n)/g, '<br>') : el.parentNode.tooltip.replace(/(\r|\n|\r\n)/g, '<br>')) + '</div>'}),
			style = false,
			watchTitle = function() {
				if(document.getElementById('fr-ui-tool-tip-hover-text')) {
					if(el.parentNode.nodeName.toLowerCase() === 'a') {
						el = el.parentNode;
					}
					if(el.title != '' && el.title != el.tooltip) {
						el.tooltip = el.getAttribute('title');
						el.setAttribute('title', '');
						document.getElementById('fr-ui-tool-tip-hover-text').innerHTML = el.tooltip.replace(/(\r|\n|\r\n)/g, '<br>');
					}
					setTimeout(watchTitle, 100);
				}
			},
			fadeIn = function() {
				if(parseFloat(d.style.opacity) < 1) {
					d.style.opacity = parseFloat(d.style.opacity)+.1;
					setTimeout(fadeIn, 50);
				} else {
					d.style.opacity = 1;
				}
			};
		FASTREP.ui.hideToolTipsHover();
		switch(el.parentNode.nodeName.toLowerCase()) {
			default:
				if(el.nodeName.toLowerCase() == 'a') {
					append = el;
					break;
				}
			case 'a':
				append = el.parentNode;
			break;
			case 'td':
				append = el;
			break;
		}
		if(window.getComputedStyle) {
			style = window.getComputedStyle(append,null).getPropertyValue('position');
		} else {
			style = append.currentStyle.position;
		}
		if(style === 'static') {
			append.style.position = 'relative';
		}
		if(append.nodeName.toLowerCase() !== 'a') {
			d.style.left = el.offsetLeft + 'px';
			d.style.top = (el.offsetTop+25) + 'px';
		} else {
			d.style.top = '25px';
			d.style.left = '2px';
		}
		d.style.opacity = 0;
		append.appendChild(d);
		watchTitle();
		fadeIn();
	},
	hideToolTipsBelow: function() {
		if(document.getElementById('fr-ui-tool-tip-below')) {
			document.getElementById('fr-ui-tool-tip-below').parentNode.removeChild(document.getElementById('fr-ui-tool-tip-below'));
		}
	},
	showToolTipsBelow: function(e) {
		var el = e.target ? e.target : e.srcElement,
			d = FASTREP.dom.create('div', {id: 'fr-ui-tool-tip-below', 'innerHTML': el.tooltip.replace(/(\r|\n|\r\n)/g, '<br>')}),
			fadeIn = function() {
				if(parseFloat(d.style.opacity) < 1) {
					d.style.opacity = parseFloat(d.style.opacity)+.1;
					setTimeout(fadeIn, 50);
				} else {
					d.style.opacity = 1;
				}
			};
		FASTREP.ui.hideToolTipsBelow();
		d.style.width = (el.offsetWidth-10) + 'px';
		d.style.opacity = 0;
		el.parentNode.appendChild(d);
		fadeIn();
	},
	applyAccountSelect: function() {
		var all = document.getElementsByTagName('input'),
			len = all.length,
			cnt = 0,
			cur = false;
		for(cnt = 0; cnt < len; cnt++) {
			cur = all[cnt];
			if(
					cur.nodeName.toLowerCase() == 'input' && 
					cur.type.toLowerCase() == 'text' && 
					(
						cur.className.indexOf('fr-store_lookup') !== -1 ||
						cur.name == 'company_store_account_number' || 
						cur.name == 'store_number' || 
						cur.name == 'store_account_number'
					)
				) {
				cur.parentNode.style.position = 'relative';
				FASTREP.dom.addEvent(cur, 'keyup', FASTREP.ui.doAccountSelect);
			} else {
				FASTREP.dom.addEvent(cur, 'focus', FASTREP.ui.removeAccountSelect);
			}
		}
		FASTREP.dom.addEvent(document.body, 'click', FASTREP.ui.removeAccountSelect);
	},
	doAccountSelect: function(e) {
		e = e || event;
		var el = e.target ? e.target : e.srcElement,
			val = el.value,
			d_id = el.form.action.replace(/\W+/g, '') + '-' + el.name,
			d = document.getElementById(d_id) ? document.getElementById(d_id) : FASTREP.dom.create('div', {'id': d_id, innerHTML: '<a href="#"><img src="http://files.fastrep.com/images/ajax-load-small.gif" alt=""> Loading</a>', 'class': 'fr-account-picker'}),
			all = d.getElementsByTagName('a'),
			len = all.length,
			cnt = 0,
			hasAct = false,
			xhr = false,
			wait = function() {
				if(el.value === val) {
					if(val === '') {
						FASTREP.ui.removeAccountSelect();
					} else {
						d.ref = el;
						d.style.width = el.offsetWidth + 'px';
						d.style.top =  (el.offsetTop+el.offsetHeight) + 'px';
						d.style.left =  el.offsetLeft + 'px';
						// Potential IE issues here?
						try {
							if(!document.getElementById(d_id)) {
								el.parentNode.appendChild(d);
							}
							if(isNaN(el.value)) {
								xhr = FASTREP.ajax.get('/_ajax/getStoreByName.php', 'limit=0,10&store_name='+ escape(el.value) +'&store_name_modifier=%', FASTREP.ui.setAccountSelect, 'GET', false);
							} else {
								xhr = FASTREP.ajax.get('/_ajax/getStoreByAccountNumber.php', 'limit=0,10&company_store_account_number='+el.value+'&company_store_account_number_modifier=%', FASTREP.ui.setAccountSelect, 'GET', false);
							}
							xhr.form = d;
						} catch(err) {}
					}
				}
			};
			switch(e.keyCode) {
				case FASTREP.fr_up:
					all[len-1].className = 'active';
					all[len-1].focus();
					try {
						e.preventDefault();
						e.stopPropagation();
					} catch(err) {
						window.event.returnValue = false;
						window.event.cancelBubble = true;
					}
				break;
				case FASTREP.fr_down:
					all[0].className = 'active';
					all[0].focus();
					try {
						e.preventDefault();
						e.stopPropagation();
					} catch(err) {
						window.event.returnValue = false;
						window.event.cancelBubble = true;
					}
				break;
				case FASTREP.fr_escape:
					FASTREP.ui.removeAccountSelect();
				break;
				case FASTREP.fr_tab:
					FASTREP.ui.removeAccountSelect();
				break;				
				default:
					setTimeout(wait, 500);
				break;
			}
	},
	setAccountSelect: function() {
		var resp = this.responseJSON.response,
			cnt = 0,
			cur = false,
			a = false;
		this.form.innerHTML = '';
		this.form.style.height = '0px';
		for(cnt in resp) {
			cur = resp[cnt];
			a = FASTREP.dom.create('a', {'href': '#', 'tabindex': -1, 'innerHTML': cur.store_name + ' ('+ cur.company_store_account_number +')<br>&nbsp;&nbsp;&nbsp;' + cur.store_address + '<br>&nbsp;&nbsp;&nbsp;' + cur.store_city + ', ' + cur.store_state_abbr +' ' + cur.store_zip, 'accnum': cur.company_store_account_number}, [{'on': 'click', 'method': function(e) {var el = e.target? e.target : e.srcElement; el.parentNode.ref.value = el.getAttribute('accnum').replace(/\s+/g, ''); el.parentNode.ref.focus(); FASTREP.ui.removeAccountSelect();}}, {'on': 'click', 'method': FASTREP.dom.prevent}, {'on': 'keyup', 'method': FASTREP.ui.moveAccountSelect}]);
			this.form.appendChild(a);
			this.form.style.height = (parseInt(this.form.style.height) + a.offsetHeight) + 'px';
		}
	},
	removeAccountSelect: function() {
		var all = document.getElementsByTagName('div'),
			len = all.length,
			cnt = 0;
		for(cnt = 0; cnt < len; cnt++) {
			if(all[cnt] && all[cnt].className.indexOf('fr-account-picker') !== -1) {
				all[cnt].parentNode.removeChild(all[cnt]);
			}
		}
	},
	moveAccountSelect: function(e) {
		var el = e.target ? e.target : e.srcElement,
			pn = el.parentNode,
			all = pn.getElementsByTagName('a'),
			len = all.length,
			cnt = 0,
			nxt = false,
			prv = false;
		for(cnt = 0; cnt < len; cnt++) {
			if(all[cnt] == el) {
				if(cnt > 0) {
					prv = all[cnt-1];
				} else {
					prv = all[len-1];
				}
				if(cnt+1 < len) {
					nxt = all[cnt+1];
				} else {
					nxt = all[0];
				}
			} else {
				all[cnt].className = '';
			}
		}
		el.className = '';
		switch(e.keyCode) {
			case FASTREP.fr_up:
				prv.className = 'active';
				prv.focus();
			break;
			case FASTREP.fr_down:
				nxt.className = 'active';
				nxt.focus();
			break;
		}
		try {
			e.preventDefault();
			e.stopPropagation();
		} catch(err) {
			window.event.returnValue = false;
			window.event.cancelBubble = true;
		}
	},
	applyMergeConfirm: function() {
		var frm = document.getElementById('fr-merge-store-form');
		if(frm) {
			frm.elements['company_store_new_number'].onkeyup = FASTREP.ui.doMergeConfirm;
			frm.elements['company_store_old_number'].onkeyup = FASTREP.ui.doMergeConfirm;
			document.getElementById('fr-merge-store-form-submit').style.display = 'none';
			document.getElementById('fr-merge-store-form-submit').parentNode.insertBefore(FASTREP.dom.create('div', {'class': 'related related-2', 'innerHTML': '<label class="inline" id="fr-merge-store-s1"></label><label class="inline" id="fr-merge-store-s2"></label>'}), document.getElementById('fr-merge-store-form-submit'));
		}
	},
	doMergeConfirm: function(e) {
		var t = e ? e.target : window.event.srcElement,
			store = t.value,
			checkVals = function() {
				var stop = false;
				if(store !== false) {
					if(store && store.store_name) {
						if(t.name == 'company_store_new_number') {
							document.getElementById('fr-merge-store-s1').innerHTML = '<input type="checkbox" id="fr-merge-store-s1-confirm" onchange="FASTREP.ui.setMergeConfirm()" onclick="FASTREP.ui.setMergeConfirm()"> I want to <strong>keep</strong> the following store:<br><span class="preload-store-info" style="display: block">' + store.store_name + ' (' + store.company_store_account_number + ')<br>'+store.store_address+'<br>'+store.store_city+', '+store.store_state_abbr+' '+store.store_zip+'</span>';
						} else {
							document.getElementById('fr-merge-store-s2').innerHTML = '<input type="checkbox" id="fr-merge-store-s2-confirm" onchange="FASTREP.ui.setMergeConfirm()" onclick="FASTREP.ui.setMergeConfirm()"> I want to <strong>remove</strong> the following store:<br><span class="preload-store-info" style="display: block">' + store.store_name + ' (' + store.company_store_account_number + ')<br>'+store.store_address+'<br>'+store.store_city+', '+store.store_state_abbr+' '+store.store_zip+'</span>';
						}
						stop = true;
					}
					if(store && !stop) {
						setTimeout(checkVals, 5000);
					}
				}
			};
		if(store == ''){return;}
		if(t.timeout) {
			clearTimeout(t.timeout);
		}
		t.timeout = setTimeout(
				function() {
					if(t.name == 'company_store_new_number') {
						document.getElementById('fr-merge-store-s1').innerHTML = '<img src="http://files.fastrep.com/images/ajax-load-small.gif" alt=""> Searching';
					} else {
						document.getElementById('fr-merge-store-s2').innerHTML = '<img src="http://files.fastrep.com/images/ajax-load-small.gif" alt=""> Searching';
					}
					FASTREP.ajax.get('/_ajax/getStoreByAccountNumber.php', 'company_store_account_number='+store, function(){store = this.responseJSON.response ? this.responseJSON.response[0] : false;}, 'GET', false);
					checkVals();
				}, 1000);
	},
	setMergeConfirm: function() {
		var d = document.getElementById('fr-merge-store-form-submit'),
			c1 = document.getElementById('fr-merge-store-s1-confirm'),
			c2 = document.getElementById('fr-merge-store-s2-confirm');
		if(d && c1 && c2) {
			if(c1.checked && c2.checked) {
				d.style.display = 'block';
			} else {
				d.style.display = 'none';
			}
		}
	},
	applyDemoPayable: function() {
		var cb = document.getElementById('demo_is_payable');
		if(cb) {
			cb.onclick = FASTREP.ui.setDemoPayable;
			cb.onchange = FASTREP.ui.setDemoPayable;
			cb.onblur = FASTREP.ui.setDemoPayable;
			FASTREP.ui.setDemoPayable();
		}
	},
	setDemoPayable: function() {
		var cb = document.getElementById('demo_is_payable'),
			pay = document.getElementById('fr-demo-payee');
		if(cb.checked) {
			pay.className = pay.className.replace(' fr-non-payable', '');
		} else {
			pay.className += ' fr-non-payable';
		}
	},
	applySalesCallDateChange: function() {
		var dt = document.getElementById('fr-sales-call-date');
		if(dt) {
			dt.setAttribute('originalvalue', dt.value);
			FASTREP.dom.addEvent(dt, 'blur', FASTREP.ui.getSalesCallDateChange);
		}
	},
	getSalesCallDateChange: function() {
		var dt = document.getElementById('fr-sales-call-date'),
			dtf = document.getElementById('fr-sales-call-form');
		if(dt && dtf) {
			if(dt.value != dt.getAttribute('originalvalue')) {
//				if(confirm('You have changed the sales call date.  This may expose the call to new metrics.  Would you like to save and update the page now?')) {
					dtf.appendChild(FASTREP.dom.create('input', {'type':'hidden', 'name':'ajaxbody', 'value':'1'}));
					if(document.createEvent) {
						evnt = document.createEvent('HTMLEvents');
						evnt.initEvent('submit', true, true);
						dtf.dispatchEvent(evnt);
					} else {
						try {
							dtf.fireEvent('onsubmit');
						} catch(err) {
							dtf.submit();
						}
					}
//				}
			}
		}
	},
	applyPrinterFilter: function() {
		var all_filters = document.getElementById('filters'),
			print_filters = document.getElementById('ui-print-filters'),
			filter_len = 0,
			filter_cnt = 0,
			filter_cur = false,
			filter_cur_text = '',
			ful = FASTREP.dom.create('ul', {'class': 'csv'});
		if(all_filters && print_filters) {
			print_filters.innerHTML = '';
			all_filters = all_filters.elements;
			filter_len = all_filters.length;
			for(filter_cnt = 0; filter_cnt < filter_len; filter_cnt++) {
				filter_cur = all_filters[filter_cnt];
				if(filter_cur.value) {
					try {
						filter_cur_text = filter_cur.parentNode.firstChild.data.trim();
					} catch(err) {}
					if(filter_cur.nodeName.toLowerCase() === 'select') {
						ful.appendChild(FASTREP.dom.create('li', {'innerHTML': '<strong>' + filter_cur_text + '</strong>: ' + filter_cur[filter_cur.selectedIndex].text}));
					} else {
						ful.appendChild(FASTREP.dom.create('li', {'innerHTML': '<strong>' + filter_cur_text + '</strong>: ' + filter_cur.value}));
					}
				}
			}
			print_filters.appendChild(ful);
			print_filters.display = 'block';
		}
	},
	applySalesCallReport: function() {
		var all = document.getElementsByTagName('a'),
			all_len = all.length,
			all_cnt = 0,
			all_cur = false;
		for(all_cnt = 0; all_cnt < all_len; all_cnt++) {
			all_cur = all[all_cnt];
			if(all_cur.className.indexOf('fr-ui-sales-report-link') !== -1) {
				FASTREP.dom.addEvent(all_cur, 'mouseover', FASTREP.ui.getSalesCallReport);
				all_cur.setAttribute('oldtitle', all_cur.title);
			}
		}
	},
	getSalesCallReport: function(e) {
		var el = e.target || e.srcElement,
			xhr = false;
		if(el.title === el.getAttribute('oldtitle')) {
			el.title = 'Loading...';
			xhr = FASTREP.ajax.get('/_ajax/getSalesReport.php', el.href.split('?')[1], FASTREP.ui.setSalesCallReport, 'GET', false);
			xhr.form = el;
		}
	},
	setSalesCallReport: function() {
		var el = this.form,
			str = '',
			cnt = 0,
			len = 0,
			cur = false,
			ml = 0;
		if(this.responseJSON && this.responseJSON.response) {
			len = this.responseJSON.response.total.length;
			str = ' Sales Figures:\n\n';
			for(cnt in this.responseJSON.response.total) {
				cur = this.responseJSON.response.total[cnt];
				str += ' ' + cur.cases + '\t\t' + cnt + ' \n';
			}
			this.form.setAttribute('title', str);
		}
	},
	applySalesCallConfirmDate: function() {
		var hasConfirmDate = document.getElementById('fr-ui-sales-call-date-visited');
		if(hasConfirmDate) {
			setInterval(FASTREP.ui.updateSalesCallConfirmDate, 500);
			FASTREP.ui.updateSalesCallConfirmDate();
		}
	},
	updateSalesCallConfirmDate: function() {
		var hasConfirmDate = document.getElementById('fr-ui-sales-call-date-visited'),
			hasConfirmDateReg = document.getElementById('fr-ui-sales-call-date-visited-reminder'),
			dt = '',
			dtv = '';
		if(hasConfirmDate && hasConfirmDateReg) {
			dtv = hasConfirmDate.value.split('/');
			if(dtv[2].length < 4) {
				dtv[2] = '20' + dtv[2];
			}
			dt = new Date(dtv[2], dtv[0]-1, dtv[1]);
			hasConfirmDateReg.innerHTML = '<span>You are adding a sales call for ' + FASTREP.fr_days_long[dt.getDay()] + ', ' + FASTREP.fr_months_short[dt.getMonth()] + ' ' + dt.getDate() + ', ' + dt.getFullYear() + '.</span>';
		}
	},
//	applyDemoHours: function() {
//		var a = document.getElementById('fr-demo-hours'),
//			ac = false,
//			acc = 0;
//		if(a) {
//			a.className = a.className.replace('related-2', 'related-3');
//			a.appendChild(FASTREP.dom.create('label', {'innerHTML': 'Total<input type="text" id="fr-demo-hours-total" disabled="disabled">'}));
//			ac = a.getElementsByTagName('input');
//			for(acc = 0; acc < ac.length; acc++) {
//				FASTREP.dom.addEvent(ac[acc], 'keyup', FASTREP.ui.updateDemoHours);
//			}
//			FASTREP.ui.updateDemoHours();
//		}
//	},
//	updateDemoHours: function() {
//		
//		var v1 = parseFloat(document.getElementById('demo_pay_rate').value.replace('$', '')),
//			v2 = parseFloat(document.getElementById('demo_hours_worked').value),
//			o = document.getElementById('fr-demo-hours-total');
//		o.value = '$' + (v1*v2);
//		if(o.value.indexOf('.') === -1) {
//			o.value += '.00';
//		} else {
//			if(o.value.split('.')[1].substring(0,2).length < 2) {
//				o.value = o.value.split('.')[0] + '.' + o.value.split('.')[1].substring(0,2) + '0';
//			} else {
//				o.value = o.value.split('.')[0] + '.' + o.value.split('.')[1].substring(0,2);
//			}
//		}
//	},
	applyDemoTotals: function() {
		var all = document.getElementsByTagName('fieldset'),
			all_len = all.length,
			all_cnt = 0,
			all_cur = false,
			has = false,
			inpt = false,
			inpt_c = 0;
		for(all_cnt = 0; all_cnt < all_len; all_cnt++) {
			all_cur = all[all_cnt];
			if(all_cur.className.indexOf('fr-demo-stats') !== -1) {
				has = all_cur;
				inpt = all_cur.getElementsByTagName('input');
				for(inpt_c = 0; inpt_c < inpt.length; inpt_c++) {
					if(inpt[inpt_c].name.indexOf('[demo_product_units_sold]') !== -1) {
						inpt[inpt_c].style.display = 'none';
						inpt[inpt_c].parentNode.appendChild(FASTREP.dom.create('input', {'id': inpt[inpt_c].name.replace(/[\[|\]]/g, '-'), 'value': inpt[inpt_c].value, 'disabled': 'disabled'}));
					}
					FASTREP.dom.addEvent(inpt[inpt_c], 'keyup', FASTREP.ui.updateDemoTotals);
				}
			}
		}
		if(has) {
			has.parentNode.insertBefore(FASTREP.dom.create('fieldset', {'class': 'fr-demo-totals', 'innerHTML': '<legend><span>Totals</span></legend><div class="related related-7"><label><span>Facings</span><input type="text" id="demo_product_facings" value="0" disabled="disabled"></label><label style="visibility: hidden;"><span>Price</span><input type="text" id="demo_product_price" value="" disabled="disabled"></label><label><span>Units Before</span><input type="text" id="demo_product_units_start" value="0" disabled="disabled"></label><label><span>Units After</span><input type="text" id="demo_product_units_end" value="0" disabled="disabled"></label><label><span>Units Sampled</span><input type="text" id="demo_product_units_sampled" value="0" disabled="disabled"></label><label><span>Units Sold</span><input type="text" id="demo_product_units_sold" value="0" disabled="disabled"></label><label><span>People Sampled</span><input type="text" id="demo_product_people_sampled" value="0" disabled="disabled"></label></div>'}), has.nextSibling);
			FASTREP.ui.updateDemoTotals();
		}
	},
	updateDemoTotals: function() {
		var all = document.getElementsByTagName('fieldset'),
			all_len = all.length,
			all_cnt = 0,
			all_cur = false,
			has = false,
			inpt = false,
			inpt_c = 0,
			u_before = 0,
			u_after = 0,
			u_samp = 0,
			totals_c = 0,
			totals = {
				'demo_product_facings': 0,
				'demo_product_units_start': 0,
				'demo_product_units_end': 0,
				'demo_product_units_sampled': 0,
				'demo_product_units_sold': 0,
				'demo_product_people_sampled': 0
				};
		for(all_cnt = 0; all_cnt < all_len; all_cnt++) {
			all_cur = all[all_cnt];
			if(all_cur.className.indexOf('fr-demo-stats') !== -1) {
				has = all_cur;
				inpt = all_cur.getElementsByTagName('input');
				u_before = 0;
				u_after = 0;
				u_samp = 0;
				for(inpt_c = 0; inpt_c < inpt.length; inpt_c++) {
					for(totals_c in totals) {
						if(inpt[inpt_c].name.indexOf(totals_c) !== -1) {
							totals[totals_c] += parseFloat(inpt[inpt_c].value);
							if(totals_c == 'demo_product_units_start') {
								u_before = inpt[inpt_c].value;
							}
							if(totals_c == 'demo_product_units_end') {
								u_after = inpt[inpt_c].value;
							}
							if(totals_c == 'demo_product_units_sampled') {
								u_samp = inpt[inpt_c].value;
							}
							if(totals_c == 'demo_product_units_sold') {
								inpt[inpt_c].value = (u_before-u_after-u_samp);
								document.getElementById(inpt[inpt_c].name.replace(/[\[|\]]/g, '-')).value = (u_before-u_after-u_samp);
							}
						}
					}
				}
				for(totals_c in totals) {
					if(document.getElementById(totals_c)) {
						document.getElementById(totals_c).value = totals[totals_c];
					}
				}
			}
		}
	},
	applyDemoPayeeTotal: function() {
		var approval_div = document.getElementById('fr-sales-call-approval'),
			hours_worked = document.getElementById('demo_hours_worked'),
			pay_rate = document.getElementById('demo_pay_rate'),
			supplies_payable = document.getElementById('demo_supplies_payable'),
			other_payable = document.getElementById('demo_other_payable');
		if(approval_div) {
			approval_div.parentNode.insertBefore(FASTREP.dom.create('p', {'style': 'clear: both;', 'class': 'preload-store-info', 'id': 'fr-sales-call-payee-total', 'innerHTML': 'Total: $ 0.00; Total with Additional Costs: $0.00'}), approval_div);
		}
		if(hours_worked) {
			FASTREP.dom.addEvent(hours_worked, 'keyup', FASTREP.ui.updateDemoPayeeTotal);
		}
		if(pay_rate) {
			FASTREP.dom.addEvent(pay_rate, 'keyup', FASTREP.ui.updateDemoPayeeTotal);
		}
		if(supplies_payable) {
			FASTREP.dom.addEvent(supplies_payable, 'keyup', FASTREP.ui.updateDemoPayeeTotal);
		}
		if(other_payable) {
			FASTREP.dom.addEvent(other_payable, 'keyup', FASTREP.ui.updateDemoPayeeTotal);
		}
		FASTREP.ui.updateDemoPayeeTotal();
	},
	updateDemoPayeeTotal: function() {
		var payee_total = document.getElementById('fr-sales-call-payee-total'),
			hours_worked = document.getElementById('demo_hours_worked'),
			pay_rate = document.getElementById('demo_pay_rate'),
			supplies_payable = document.getElementById('demo_supplies_payable'),
			other_payable = document.getElementById('demo_other_payable'),
			total = 0.0, subtotal = 0.0;
		if(pay_rate && !isNaN(pay_rate.value.replace('$', ''))) {
			total += parseFloat(pay_rate.value.replace('$', ''));
			subtotal += parseFloat(pay_rate.value.replace('$', ''));
		}
		if(hours_worked && !isNaN(hours_worked.value.replace('$', ''))) {
			total = total*parseFloat(hours_worked.value.replace('$', ''));
			subtotal = subtotal*parseFloat(hours_worked.value.replace('$', ''));
		}
		if(supplies_payable && !isNaN(supplies_payable.value.replace('$', ''))) {
			total += parseFloat(supplies_payable.value.replace('$', ''));
		}
		if(other_payable && !isNaN(other_payable.value.replace('$', ''))) {
			total += parseFloat(other_payable.value.replace('$', ''));
		}
		if(payee_total) {
			payee_total.innerHTML = 'Total: $ ' + subtotal.toFixed(2) + '; Total with Additional Costs: $' + total.toFixed(2).toString();
		}
	},
	applyOnResizeGraph: function() {
		FASTREP.dom.addEvent(window, 'resize', FASTREP.ui.updateOnResizeGraph);
		FASTREP.ui.updateOnResizeGraph();
	},
	updateOnResizeGraph: function() {
		var all = document.getElementsByTagName('img'),
			all_len = all.length,
			all_cnt = 0,
			all_cur = false,
			chref = '';
		for(all_cnt = 0; all_cnt < all_len; all_cnt++) {
			all_cur = all[all_cnt];
			if(all_cur.className.indexOf('fr-graph') !== -1) {
				chref = all_cur.src;
				if(chref.indexOf('&w=') !== -1) {
					chref = chref.replace(/&w=.*?(&|$)/, '');
				}
				chref += '&w=' + all_cur.parentNode.offsetWidth;
				all_cur.src = chref;
				all_cur.onload = function() {
					this.style.width = this.parentNode.offsetWidth + 'px';
				}
			}
		}
	},
	applySalesCallEmailHijack: function() {
		var el = document.getElementById('fr-emailer');
		if(el) {
			FASTREP.dom.addEvent(el, 'click', FASTREP.ui.doSalesCallEmailHijack);
			FASTREP.dom.addEvent(el, 'click', FASTREP.dom.prevent);
		}
	},
	doSalesCallEmailHijack: function(e) {
		var el = e.target || e.srcElement;
		xhr = FASTREP.ajax.get(el.href, 'ajax=true', FASTREP.form.hijackCallback, 'GET');
	},
//	applyView: function() {
//		var all = false,
//			all_len = 0,
//			all_cnt = 0,
//			all_cur = false,
//			all_cur_pn = false,
//			all_val = false,
//			firstform = false;
//		if(location.href.indexOf('/view/') !== -1 && location.href.indexOf('/login/') === -1) {
//			all = document.getElementsByTagName('*');
//			all_len = all.length;
//			for(all_cnt = 0; all_cnt < all_len; all_cnt++) {
//				all_cur = all[all_cnt];
//				all_val = false;
//				if(
//					(all_cur.nodeName.toLowerCase() == 'input' && all_cur.getAttribute('type') && all_cur.getAttribute('type').toLowerCase() == 'text') ||
//					all_cur.nodeName.toLowerCase() == 'textarea'
//				) {
//					all_val = all_cur.value;
//				} else if(all_cur.nodeName.toLowerCase() == 'input') {
//					all_cur.disabled = true;
//				} else if(all_cur.nodeName.toLowerCase() == 'select') {
//					all_val = all_cur.options[all_cur.selectedIndex].innerHTML;
//				} else if(all_cur.nodeName.toLowerCase() == 'button') {
//					all_cur.parentNode.removeChild(all_cur);
//				} else if(all_cur.className.indexOf('form') !== -1) {
//					if(firstform === false) {
//						firstform = true;
//					} else {
//						all_cur.parentNode.removeChild(all_cur);
//					}
//				} else if(all_cur.className.indexOf('calbutton') !== -1) {
//					all_cur.parentNode.removeChild(all_cur);
//				}
//				if(all_val !== false) {
//					all_cur_pn = all_cur.parentNode;
//					all_cur_pn.removeChild(all_cur);
//					all_cur_pn.innerHTML = all_cur_pn.innerHTML.trim() + ':<br>' + all_val.replace(/\n/, '<br>');
//				}
//			}
//		}
//	},
	applyEmail: function() {
		var all = document.getElementsByTagName('div'),
			all_len = all.length,
			all_cnt = 0,
			all_cur = false,
			tables = '',
			f1 = false,
			f2 = false,
			b1 = false,
			b2 = false,
			buttons = false;
		for(all_cnt = 0; all_cnt < all_len; all_cnt++) {
			all_cur = all[all_cnt];
			if(all_cur.className.indexOf('table') !== -1) {
				tables += all_cur.innerHTML;
				if(buttons === false) {
					buttons = all_cur;
				}
			}
		}
		if(tables !== '') {
			f1 = FASTREP.dom.create('form', {'method': 'POST', 'action': '/email/', 'id': 'fr-email-3'});
			f1.appendChild(FASTREP.dom.create('input', {'type': 'hidden', 'name': 'to', 'value':'3'}));
			f1.appendChild(FASTREP.dom.create('textarea', {'name': 'page', 'innerHTML': escape(tables)}));
			f1.style.display = 'none';
			document.body.appendChild(f1);
			f2 = FASTREP.dom.create('form', {'method': 'POST', 'action': '/email/', 'id': 'fr-email-2'});
			f2.appendChild(FASTREP.dom.create('input', {'type': 'hidden', 'name': 'to', 'value':'2'}));
			f2.appendChild(FASTREP.dom.create('textarea', {'name': 'page', 'innerHTML': escape(tables)}));
			f2.style.display = 'none';
			document.body.appendChild(f2);
			all = document.getElementsByTagName('p');
			all_len = all.length;
			for(all_cnt = 0; all_cnt < all_len; all_cnt++) {
				all_cur = all[all_cnt];
				if(all_cur.className.indexOf('buttons') !== -1 && all_cur.parentNode.id === 'content') {
					buttons = true;
					b1 = FASTREP.dom.create('a', {'class': 'edit', 'title': 'E-mail To Sales Managers', 'innerHTML': 'E-mail To Sales Managers <img src="http://files.fastrep.com/images/actions-email.png" alt="E-mail To Sales Managers">'}, [{'on': 'click', 'method': function(){document.getElementById('fr-email-3').submit();}}]);
					b2 = FASTREP.dom.create('a', {'class': 'edit', 'title': 'E-mail To Company Administrators', 'innerHTML': 'E-mail To Company Administrators <img src="http://files.fastrep.com/images/actions-email.png" alt="E-mail To Company Administrators">'}, [{'on': 'click', 'method': function(){document.getElementById('fr-email-2').submit();}}]);
					all_cur.insertBefore(b1, all_cur.firstChild);
					all_cur.insertBefore(b2, all_cur.firstChild);
				}
			}
			if(buttons !== true && buttons !== false) {
				b1 = FASTREP.dom.create('a', {'class': 'edit', 'title': 'E-mail To Sales Managers', 'innerHTML': 'E-mail To Sales Managers <img src="http://files.fastrep.com/images/actions-email.png" alt="E-mail To Sales Managers">'}, [{'on': 'click', 'method': function(){document.getElementById('fr-email-3').submit();}}]);
				b2 = FASTREP.dom.create('a', {'class': 'edit', 'title': 'E-mail To Company Administrators', 'innerHTML': 'E-mail To Company Administrators <img src="http://files.fastrep.com/images/actions-email.png" alt="E-mail To Company Administrators">'}, [{'on': 'click', 'method': function(){document.getElementById('fr-email-2').submit();}}]);
				buttons = buttons.parentNode.insertBefore(FASTREP.dom.create('p', {'class': 'buttons', 'id': 'buttons'}), buttons);
				buttons.appendChild(b1);
				buttons.appendChild(b2);
			}
		}
	},
	applyFontSize: function() {
		var c = document.getElementById('content'),
			s = FASTREP.dom.create('div', {'class': 'fr-font-size'}, [{'on': 'click', 'method': FASTREP.ui.setFontSize}]),
			cv = document.cookie.split(';'),
			cvi = 0,
			cvc = false,
			datestr = new Date();
		datestr.setTime(datestr.getTime()+(30*24*60*60*1000));
		s.appendChild(FASTREP.dom.create('span', {'innerHTML': 'Text Size:'}));
		s.appendChild(FASTREP.dom.create('a', {'href': '#', 'class': 'edit fr-font-size-small', 'innerHTML': 'A', 'title': 'Small'}));
		s.appendChild(FASTREP.dom.create('a', {'href': '#', 'class': 'edit fr-font-size-medium', 'innerHTML': 'A', 'title': 'Medium'}));
		s.appendChild(FASTREP.dom.create('a', {'href': '#', 'class': 'edit fr-font-size-large', 'innerHTML': 'A', 'title': 'Large'}));
		c.insertBefore(s, c.firstChild);
		for(cvi in cv) {
			cvc = cv[cvi].split('=');
			if(cvc[0].trim() == 'fontsize') {
				c.style.fontSize = cvc[1] + 'em';
				document.cookie = 'fontsize=' + cvc[1] + '; expires=' + datestr.toGMTString() + '; path=/';
			}
		}
	},
	setFontSize: function(e) {
		var el = e.target || e.srcElement,
			c = document.getElementById('content'),
			fs = 1.3,
			datestr = new Date();
		datestr.setTime(datestr.getTime()+(30*24*60*60*1000));
		if(el.className.indexOf('fr-font-size-small') !== -1) {
			c.style.fontSize = '1em';
			fs = 1;
		}
		if(el.className.indexOf('fr-font-size-medium') !== -1) {
			c.style.fontSize = '1.3em';
			fs = 1.3;
		}
		if(el.className.indexOf('fr-font-size-large') !== -1) {
			c.style.fontSize = '1.6em';
			fs = 1.6;
		}
		document.cookie = 'fontsize=' + fs + '; expires=' + datestr.toGMTString() + '; path=/';
	},
	applyTabs: function() {
		var all = document.getElementsByTagName('dl'),
			all_len = all.length,
			all_cnt = 0,
			all_cur = false,
			dts = false,
			dts_cnt = 0,
			tot_left = 3,
			el = false;
		for(all_cnt = 0; all_len > all_cnt; all_cnt++) {
			all_cur = all[all_cnt];
			if(all_cur.className.indexOf('fr-tabs') !== -1) {
				all_cur.className += ' fr-has-tabs';
				dts = all_cur.getElementsByTagName('dt');
				dts[0].className += ' fr-open';
				if(navigator.userAgent.indexOf('MSIE')) {
					el = dts[0];
					while(el.nextSibling.nodeName.toLowerCase() != 'dd') {
						el = el.nextSibling;
					}
					el.nextSibling.style.display = 'block';
				}
				for(dts_cnt = 0; dts_cnt < dts.length; dts_cnt++) {
					FASTREP.dom.addEvent(dts[dts_cnt], 'click', FASTREP.ui.swapTabs);
					dts[dts_cnt].style.left = tot_left + 'px';
					tot_left += dts[dts_cnt].offsetWidth + 3;
				}
			}
		}
	},
	swapTabs: function(e) {
		var el = e.target || e.srcElement,
			all = el.parentNode.getElementsByTagName('dt'),
			all_len = all.length,
			all_cnt = 0,
			all_cur = false;
		for(all_cnt = 0; all_len > all_cnt; all_cnt++) {
			all_cur = all[all_cnt];
			all_cur.className = all_cur.className.replace('fr-open', '');
		}
		el.className += ' fr-open';
		if(navigator.userAgent.indexOf('MSIE') !== -1) {
			all = el.parentNode.getElementsByTagName('dd');
			all_len = all.length;
			for(all_cnt = 0; all_len > all_cnt; all_cnt++) {
				all_cur = all[all_cnt];
				all_cur.style.display = 'none';
			}
			while(el.nextSibling.nodeName.toLowerCase() != 'dd') {
				el = el.nextSibling;
			}
			el.nextSibling.style.display = 'block';
		}
	},
//	applyDemoPayeeSelect: function() {
//		var p = document.getElementById('fr-demo-payee'),
//			x = false;
//		if(p) {
//			p.className += ' fr-has-demo-payee';
//			x = FASTREP.ajax.get('/_ajax/getDemoPayee.php', '', FASTREP.ui.setDemoPayeeSelect, 'POST');
//		}
//	},
//	setDemoPayeeSelect: function() {
//		var i = 0,
//			p = document.getElementById('fr-demo-payee'),
//			rep = FASTREP.dom.create('select', {'class': 'fr-demo-payee'}, [{'on': 'change', 'method': FASTREP.ui.populateDemoPayee}]),
//			cur = false,
//			opt = false,
//			str = '',
//			strv = '';
//		opt = FASTREP.dom.create('option', {'innerHTML': 'Select an Existing Contact or Enter a New One Below', 'value': ''});
//		rep.appendChild(opt);
//		for(i in this.responseJSON.response) {
//			cur = this.responseJSON.response[i];
//			strv = cur.demo_payee + '|' + cur.demo_payee_phone + '|' + cur.demo_payee_address + '|' + cur.demo_payee_city + '|' + cur.state_id + '|' + cur.demo_payee_zip;
//			str = cur.demo_payee + ' (' + cur.demo_payee_phone + ') at ' + cur.demo_payee_address + ', ' + cur.demo_payee_city + ', ' + cur.state_abbr + ' ' + cur.demo_payee_zip;
//			opt = FASTREP.dom.create('option', {'innerHTML': str, 'value': strv});
//			rep.appendChild(opt);
//		}
//		p.insertBefore(rep, p.getElementsByTagName('legend')[0].nextSibling);
//	},
	applyDemoPayeeSelect: function() {
		var p = document.getElementById('fr-demo-payee'),
			x = false;
		if(p) {
			p.className += ' fr-has-demo-payee';
			x = FASTREP.ajax.get('/_ajax/getPayee.php', '', FASTREP.ui.setDemoPayeeSelect, 'POST');
		}
	},
	setDemoPayeeSelect: function() {
		var i = 0,
			p = document.getElementById('fr-demo-payee'),
			rep = FASTREP.dom.create('select', {'class': 'fr-demo-payee', 'id': 'fr-demo-payee-select'}, [{'on': 'change', 'method': FASTREP.ui.populateDemoPayee}]),
			cur = false,
			opt = false,
			str = '',
			strv = '';
		opt = FASTREP.dom.create('option', {'innerHTML': 'Select an Existing Contact or Enter a New One Below', 'value': ''});
		rep.appendChild(opt);
		for(i in this.responseJSON.response) {
			cur = this.responseJSON.response[i];
			strv = cur.payee_firstname + ' ' + cur.payee_lastname + '|' + cur.payee_phone + '|' + cur.payee_address + '|' + cur.payee_city + '|' + cur.payee_state_id + '|' + cur.payee_zip + '|' + cur.payee_is_payable + '|' + cur.payee_id;
			str = cur.payee_firstname + ' ' + cur.payee_lastname;
			if(cur.payee_phone != '000-000-0000') {
				str += ' (' + cur.payee_phone + ')';
			}
			if(cur.payee_address || (cur.payee_city && cur.state_abbr && cur.payee_zip)) {
				str += ' at ';
				if(cur.payee_address) {
					str += ' ' + cur.payee_address;
				}
				if(cur.payee_city && cur.state_abbr && cur.payee_zip) {
					str += ' ' + cur.payee_city + ', ' + cur.state_abbr + ' ' + cur.payee_zip;
				}
			}
			opt = FASTREP.dom.create('option', {'innerHTML': str, 'value': strv});
			rep.appendChild(opt);
		}
		p.insertBefore(rep, p.getElementsByTagName('legend')[0].nextSibling);
		FASTREP.ui.populateDemoPayee();
	},
	populateDemoPayee: function() {
		var el = document.getElementById('fr-demo-payee-select'),
			v = el.value.split('|'),
			update = FASTREP.dom.create('div', {'className': 'inline', 'id': 'fr-save-payee', 'innerHTML': '<label><input type="checkbox" name="fr-save-payee" value="' + (v[7] ? v[7] : '') + '" ' + (v[0] ? ' checked="checked"' : '') + '> ' + (v[0] ? ' Update Info For ' + v[0] : 'Save As New Payee') + '</label>'});
		if(el.value != '') {
			el.form.elements['demo_payee'].value = v[0];
			el.form.elements['demo_payee_phone'].value = v[1];
			el.form.elements['demo_payee_address'].value = v[2];
			el.form.elements['demo_payee_city'].value = v[3];
			el.form.elements['state_id'].value = v[4];
			el.form.elements['demo_payee_zip'].value = v[5];
			el.form.elements['demo_is_payable'].checked = (v[6] == 1 ? true : false);
			if(document.getElementById('fr-save-payee')) {
				document.getElementById('fr-save-payee').parentNode.replaceChild(update, document.getElementById('fr-save-payee'));
			} else {
				el.parentNode.appendChild(update);
			}
		} else {
			if(document.getElementById('fr-save-payee')) {
				document.getElementById('fr-save-payee').parentNode.replaceChild(update, document.getElementById('fr-save-payee'));
			} else {
				el.parentNode.appendChild(update);
			}
		}
		FASTREP.ui.setDemoPayable();
	},
	addMultiCheck: function(e) {
		var el = e.target || e.srcElement,
			append = document.getElementById(el.options[el.selectedIndex].value),
			pn = el.parentNode,
			evnt = false,
			cid = location.href.split('/')[location.href.split('/').length-1].replace(/#/g, '');
		if(append) {
			append.getElementsByTagName('input')[0].setAttribute('checked', 'checked');
			append.className = append.className.replace('fr-multicheck-hidden', '');
			el.removeChild(el.options[el.selectedIndex]);
			el.selectedIndex = 0;
			if(cid != '' && !isNaN(cid)) {
				while(pn.nodeName.toLowerCase() != 'form' && pn.nodeName.toLowerCase() != 'body') {
					pn = pn.parentNode;
				}
				if(pn.nodeName.toLowerCase() === 'form') {
					if(document.createEvent) {
						evnt = document.createEvent('HTMLEvents');
						evnt.initEvent('submit', true, true);
						pn.dispatchEvent(evnt);
					} else {
						try {
							pn.fireEvent('onsubmit');
						} catch(err) {
							pn.submit();
						}
					}
				}
			}
		}
	},
	removeMultiCheck: function(e) {
		var el = e.target || e.srcElement,
			pn = el.parentNode,
			cid = location.href.split('/')[location.href.split('/').length-1].replace(/#/g, '');
		if(cid != '' && !isNaN(cid)) {
			while(pn.nodeName.toLowerCase() != 'form' && pn.nodeName.toLowerCase() != 'body') {
				pn = pn.parentNode;
			}
			if(pn.nodeName.toLowerCase() === 'form') {
				if(document.createEvent) {
					evnt = document.createEvent('HTMLEvents');
					evnt.initEvent('submit', true, true);
					pn.dispatchEvent(evnt);
				} else {
					try {
						pn.fireEvent('onsubmit');
					} catch(err) {
						pn.submit();
					}
				}
			}
		}
	},
	applyMultiChecks: function() {
		var rep = false,
			all = document.getElementsByTagName('fieldset'),
			all_len = all.length,
			all_cnt = 0,
			all_cur = false,
			lab = false,
			lab_len = 0,
			lab_cnt = 0,
			lab_cur = false,
			check = false,
			str = false,
			opt = false,
			id = false;
		for(all_cnt = 0; all_len > all_cnt; all_cnt++) {
			all_cur = all[all_cnt];
			rep = FASTREP.dom.create('select', {'class': 'fr-multicheck-add'}, [{'on': 'change', 'method': FASTREP.ui.addMultiCheck}]);
			if(all_cur.className.indexOf('fr-multicheck') !== -1) {
				lab = all_cur.getElementsByTagName('label');
				for(lab_cnt = 0, lab_len = lab.length; lab_len > lab_cnt; lab_cnt++) {
					lab_cur = lab[lab_cnt];
					check = lab_cur.getElementsByTagName('input')[0];
					str = lab_cur.innerHTML.replace(/<.*?>/g, '').trim();
					lab_cur = lab[lab_cnt].parentNode;
					FASTREP.dom.addEvent(check, 'click', FASTREP.ui.removeMultiCheck);
					if(check.checked == false) {
						lab_cur.className += ' fr-multicheck-hidden';
						id = 'fr-' + str.toLowerCase().replace(/[^a-z0-9]/g, '');
						while(document.getElementById(id)) {
							id += Math.floor(Math.random()*9);
						}
						lab_cur.id = id;
						opt = FASTREP.dom.create('option', {'value': id, 'innerHTML': str});
						rep.appendChild(opt);
					}
				}
			}
			if(opt !== false) {
				rep.insertBefore(FASTREP.dom.create('option', {'value': 0, 'innerHTML': 'Add Classification (Select Below)', 'selected': 'selected'}), rep.firstChild);
				all_cur.className += ' fr-multicheck-hasopt';
				rep.selectedIndex = 0;
				all_cur.insertBefore(rep, all_cur.getElementsByTagName('legend')[0].nextSibling);
				opt = false;
			}
		}
	},
	applySort: function() {
		var all = document.getElementsByTagName('a'),
			all_len = all.length,
			all_cnt = 0,
			all_cur = false;
		for(all_cnt = 0; all_len > all_cnt; all_cnt++) {
			all_cur = all[all_cnt];
			if(all_cur.className.indexOf('orderby ') !== -1) {
				FASTREP.dom.addEvent(all_cur, 'click', FASTREP.ui.doSort);
				FASTREP.dom.addEvent(all_cur, 'click', FASTREP.dom.prevent);
			}
		}
	},
	doSort: function(e) {
		var el = e.target || e.srcElement;
		if(location.href.indexOf('sort=DESC') === -1) {
			location.href = "#sort=DESC";
			el.className += ' orderby-desc-loading';
		} else {
			location.href = "#sort=ASC";
			el.className += ' orderby-asc-loading';
		}
		xhr = FASTREP.ajax.get(el.href, 'ajaxbody=true', FASTREP.ui.bodySwap, 'POST');
	},
	applyPagenate: function() {
		var all = document.getElementsByTagName('a'),
			all_len = all.length,
			all_cnt = 0,
			all_cur = false;
		for(all_cnt = 0; all_len > all_cnt; all_cnt++) {
			all_cur = all[all_cnt];
			if((all_cur.className.indexOf('prev') !== -1 || all_cur.className.indexOf('next') !== -1 || all_cur.className.indexOf('direct') !== -1) && (all_cur.parentNode.className.indexOf('pagenate') !== -1 || all_cur.parentNode.parentNode.className.indexOf('pagenate') !== -1)) {
				FASTREP.dom.addEvent(all_cur, 'click', FASTREP.ui.doPagenate);
				FASTREP.dom.addEvent(all_cur, 'click', FASTREP.dom.prevent);
			}
		}
		if(FASTREP.reinited === false && location.href.indexOf('#last=') !== -1) {
			xhr = FASTREP.ajax.get(unescape(location.href.substring(location.href.indexOf('#last=')+6, location.href.length)), 'ajaxbody=true', FASTREP.ui.bodySwap, 'POST');
			location.href="#";
		}
	},
	doPagenate: function(e) {
		var el = e.target || e.srcElement,
			xhr = false,
			hr = el.href.substring(el.href.indexOf('.com')+4, el.href.length);
		location.href = '#last=' + escape(hr);
		xhr = FASTREP.ajax.get(el.href, 'ajaxbody=true', FASTREP.ui.bodySwap, 'POST');
	},
	bodySwap: function() {
		document.body.innerHTML = this.responseJSON.body;
		FASTREP.reinit();
	},
	applyBugReport: function() {
		var el = document.getElementById('fr-report-bug');
		FASTREP.dom.addEvent(el, 'click', FASTREP.ui.createBugReport);
		FASTREP.dom.addEvent(el, 'click', FASTREP.dom.prevent);
	},
	applyCollapse: function() {
		var all = document.getElementsByTagName('*'),
			all_cnt = 0,
			all_len = all.length,
			all_cur,
			new_a;
		for(all_cnt = 0; all_cnt < all_len; all_cnt++) {
			all_cur = all[all_cnt];
			if(all_cur.className.indexOf('fr-collapse-trigger') !== -1) {
				if(all_cur.nodeName.toLowerCase() !== 'a') {
					new_a = FASTREP.dom.create('a', {'innerHTML': all_cur.innerHTML, 'href': '#'});
					all_cur.innerHTML = '';
					all_cur.appendChild(new_a);
					all_cur = new_a;
				}
				FASTREP.dom.addEvent(all_cur, 'click', FASTREP.ui.setCollapse);
				FASTREP.dom.addEvent(all_cur, 'click', FASTREP.dom.prevent);
				do {
					all_cur = all_cur.parentNode;
				} while(all_cur.className.indexOf('fr-collapse-target') === -1 && all_cur !== document.body);
				if(all_cur.className.indexOf('fr-collapse-start-hidden') !== -1) {
					all_cur.className += ' fr-collapse-hidden';
				}
			}
		}
	},
	createBugReport: function(e) {
		var t = e.target || e.srcElement,
			subto = t.href,
			runrep = confirm('You have opted to submit a bug report where you will be asked three questions about the problem you experienced to help us better troubleshoot.\n\nClick "OK" to continue or "CANCEL" to stop this process.  If you click "CANCEL" on any prompt following this one, the process will be stopped.'),
			desc = runrep !== false ? prompt('1 of 3: What were you doing when you experienced the problem?  Describe the goal of what you were doing and any steps you took to achieve the goal on this page.', '') : false,
			events = runrep !== false && desc !== null ? prompt('2 of 3: What happened when things went wrong?  Describe any errors you may have received.', '') : false,
			expected = runrep !== false && desc !== null && events !== null ? prompt('3 of 3: What did you expect to happen?  If the problem had not occured, describe what should have happened.') : false,
			page = location.href,
			html = document.documentElement.innerHTML,
			ua = navigator.userAgent,
			time = new Date(),
			xhr = false,
			qs = '';
		if(runrep !== false && desc !== null && events !== null && expected !== null) {
			qs = 'page=' + escape(page) + '&' +
				'time=' + escape(time) + '&' +
				'ua=' + escape(ua) + '&' +
				'desc=' + escape(desc) + '&' +
				'events=' + escape(events) + '&' +
				'expected=' + escape(expected) + '&' +
				'html=' + escape(html);
			xhr = FASTREP.ajax.get(subto, qs, function(){alert('The bug report was successfully sent.  Thanks for your feedback.');}, 'POST');
		}
	},
	setCollapse: function(e) {
		var container = e.target || e.srcElement;
		while(container.className.indexOf('fr-collapse-target') === -1 && container !== document.body) {
			container = container.parentNode;
		}
		if(container.className.indexOf('fr-collapse-hidden') !== -1) {
			container.className = container.className.replace(' fr-collapse-hidden', '');
		} else {
			container.className += ' fr-collapse-hidden';
		}
	}
};
