function isset(varname) {
	return(typeof(window[varname]) != 'undefined');
}

function redirect(url) {
	setTimeout("window.location = '" + url + "';", 4000);
}
		
function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft;
		curtop = obj.offsetTop;
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		}
	}
	return [curleft,curtop];
}

function is_all_ws(nod)
{
	return !(/[^\t\n\r ]/.test(nod.data));
}

function is_ignorable(nod)
{
	return (nod.nodeType == 8) || ((nod.nodeType == 3) && is_all_ws(nod));
}

function stripTextNodes(element) {
	for (x = 0; x < element.childNodes.length; x++) {
		if (is_ignorable(element.childNodes[x])) {
			element.removeChild(element.childNodes[x]);
		}
	}
	
	return element.childNodes;
}

function isArray(testObject) {   
	return testObject && !(testObject.propertyIsEnumerable('length')) && typeof testObject === 'object' && typeof testObject.length === 'number';
}

function randomString(numbersonly) {
	var chars = numbersonly ? "0123456789" : "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
	var randomstring = '';
	for (var i = 0; i < 8; i++) {
		var rnum = Math.floor(Math.random() * chars.length);
		randomstring += chars.substring(rnum,rnum+1);
	}
	
	return randomstring;
}

function timeRemaining(starttime, endstamp, longDisplay) {
	var starttime	= parseInt(starttime);
	var endtime 	= parseInt(endstamp);
	var timediff 	= endtime - starttime;

	var days 		= parseInt(timediff / 86400);
	var remain 		= timediff % 86400;
	var hours 		= parseInt(remain / 3600);
	var remain 		= remain % 3600;
	var mins 		= parseInt(remain / 60);
	var secs 		= remain % 60;
	
	var arr			= [];

	if (timediff > 0) {
		if (!longDisplay) {
			var remain = [days+'d', hours+'h', mins+'m', secs+'s'];
		} else {
			var remain = [days+' day(s)', hours+' hour(s)', mins+' minute(s)', secs+' second(s)'];
		}
		
		remain.each(function(r, k) {
			if (r.split('')[0] == 0) {
				delete remain[k];
			}
		});
		
		var remaintime = remain.compact().join(', ');
	} else {
		var remaintime = '';
	}
	
	return remaintime;
}

ProgressBar = Class.create({
	initialize: function(element, pct, image) {
		this.bar = new JS_BRAMUS.jsProgressBar(element, pct, {
			barImage: image ? image : 'percentImage_back.png'
		});
	},
	
	set: function(pct) {
		this.bar.setPercentage(pct);
	},
	
	get: function() {
		return this.bar.getPercentage();
	}
});

Button = Class.create({
	initialize: function(element, func) {
		element.setAttribute('onclick', func);
		element.makeUnselectable();
		element.setStyle({'cursor': 'pointer'});
	}
});

Debug = Class.create();

Object.extend(Debug, {
	alt: 0,
	add: function(text) {
		var newln = new Element('div', {
			'class': 'border rounded',
			'style': 'padding: 3px; margin-top: 5px;'
		});
		
		$('debug').appendChild(newln).update('&raquo;'+text);
		$('debug').scrollTop = $('debug').scrollHeight;
		
		if (this.alt == 0) {
			newln.addClassName('darkpanel');
			this.alt = 1;
		} else {
			this.alt = 0;
		}
		
	}
});

Login = Class.create();

Object.extend(Login, {
	login: function() {
		$('login').hide();
		new Ajax.Request('ajax/login.php?do=login', {
			asynchronous: true,
			parameters: {
				username: $F('login_username'),
				password: $F('login_password')
			},
			onComplete: function(response) {
				Debug.add(response);
				var response = response.responseText.evalJSON();
				
				if (response.success == true) {
					$('login').hide();
					$('loggedin').show();
				} else {
					Control.Modal.open(response.error);
					$('login').show();
				}
			}
		});
	},
	
	logout: function() {
		$('loggedin').hide();
		
		new Ajax.Request('ajax/login.php?do=logout', {
			asynchronous: true,
			onComplete: function(response) {
				$('login').show();
			}
		});
	}
});

M_WINDOW_OPEN = false;

Message = Class.create({
	initialize: function(text, textonly, locked) {
		Debug.add('Opening Message');
		this.window = false;
		
		if (textonly) {
			this.textOnly(text, locked);
		} else {
			this.normal(text, locked);
		}
		
		M_WINDOW_OPEN = true;
	},
	
	normal: function(text, locked) {
		this.window = Control.Modal.open(text, {
			fade: true,
			fadeDuration: 0.35,
			opacity: 0.8,
			overlayCloseOnClick: (locked == true ? false : true)
		});
	},
	
	textOnly: function(text, locked) {
		this.window = Control.Modal.open(text, {
			fade: true,
			fadeDuration: 0.35,
			containerClassName: 'modaltext',
			opacity: 0.8,
			overlayCloseOnClick: (locked == true ? false : true)
		});
	},
	
	close: function() {
		Debug.add('Closing Message');
		
		this.window.close();
		M_WINDOW_OPEN = false;
	}
});

LAST_TEXT 	= '';
CONS		= 0;

Info = Class.create({
	initialize: function(className, text, type, permanent) {
		var type 		= (type == 'error' ? 'err' : 'msg');
		var container 	= $(type+'_'+className);
		
		if (type == 'err') {
			if (text == LAST_TEXT) {
				CONS++;
				if (CONS >= 5) new Info('grid', 'That\'s getting annoying, stop it.', 'error');
			} else {
				LAST_TEXT = text;
				CONS = 0;
			}
		}
		
		var thismsg		= new Element('div', {
			'class':	'inlinemsg rounded '+type,
			'id':		randomString(),
			'style':	'display: none;'
		});
		
		thismsg.appendChild(document.createTextNode(text));
		
		$('msg_'+className).appendChild(thismsg);
		
		new Effect.toggle(thismsg, 'appear', {
			duration: 0.5,
			queue: 'end'
		});
		
		if (!permanent) {
			setTimeout("new Effect.toggle($('"+thismsg.id+"'), 'appear', {duration: 0.5, queue: 'front'})", 5000);
			setTimeout("$('"+thismsg.id+"').remove();", 6000);
		}
	}
});

JSMessage = Class.create();

Object.extend(JSMessage, {
	open: function(text) {
		this.win = new Element('div', {
			'id':	'JSmessage_'+randomString()
		}).addClassName('JSMessage-outer').makeUnselectable().hide();
		
		this.win.setAttribute('onclick', 'JSMessage.close();');
		
		$('win').appendChild(this.win);
		
		this.txt = new Element('div', {}).addClassName('JSMessage-inner').update(text).hide();
		$('win').appendChild(this.txt).makeUnselectable();
		
		this.txt.setAttribute('onclick', 'JSMessage.close();');
		
		new Effect.Appear(this.win, {
			duration: 0.2
		});
		
		new Effect.Appear(this.txt, {
			duration: 0.2
		});
	},
	
	close: function() {
		this.win.remove();
		this.txt.remove();
	}
});

JSDrops = Class.create();

Object.extend(JSDrops, {
	current: false,
	obsFunc: function(evt) {
		var dropObj = JSDrops.current;
		
		if (dropObj.open) {
			if (!$(dropObj.drop).mouseWithin(evt) && !$(dropObj.anchor).mouseWithin(evt)) {
				dropObj.collapse();
			}
		}
	}
});

JSDrop = Class.create({
	initialize: function(links, anchor, objID, options) {
		
		var anchor	= this.anchor = $(anchor);
		var id		= 'drop_' + anchor.id;
		var options	= options || {};
		var pos		= anchor.cumulativeOffset();
		var drop 	= this.drop = new Element('div', {
			'id': 			id,
			'class':		'JSDrop_outer panel rounded'
		});
		
		this.objID	= objID;
		this.open	= false;
		
		if (typeof links == 'object') {
			links.each(function(link) {
				var thislink = new Element('div', {
					'class': 	'JSDrop_link darkpanel',
					'title':	link.title
				});
				
				var a = new Element('a', {
					'href':		(typeof link.href != undefined && link.href != undefined) ? link.href : '#',
					'onclick':	(typeof link.onclick != undefined && link.onclick != undefined) ? link.onclick : false,
					'title':	link.title
				}).update(link.title);
				
				thislink.appendChild(a);
				drop.appendChild(thislink);
			});
		} else {
			drop.update(links);
		}
		
		$('win').appendChild(drop);
		
		drop.setStyle({
			'position':		'absolute',
			'left':			parseInt(pos.left) + 'px',
			'top':			parseInt(pos.top) + parseInt(anchor.getHeight()) + 'px',
			'zIndex':		5000,
			'display':		'none',
			'width':		options.width || 'auto',
			'max-width':	'150px'
		});
		
		drop.addClassName('shadow');
		
		anchor.setStyle({
			'cursor':	'pointer'
		});
		
		Event.observe(window, 'click', JSDrops.obsFunc);
	},
	
	expand: function() {
		if (this.open == true) {
			this.drop.setStyle({display: 'none'});
			this.open = false;
		} else {
			JSDrops.current = this;
			
			this.drop.setStyle({display: 'block'});
			this.open = true;
		}
	},
	
	collapse: function() {
		this.drop.setStyle({display: 'none'});
		this.open = false;
	}
});

JSWins = Class.create();
JSWins = Object.extend(JSWins, {
	current: false
});

JSWindow = Class.create({
	initialize: function(content, pos, id, options) {
		if (!id) id = randomString();
		
		this.options = {
			'overlay': 	false,
			'zIndex': 	'9999',
			'center':	false,
			'autoOpen': true
		};
		
		Object.extend(this.options, options || {});
		
		var win = new Element('div', {
			'id':	'jswindow_'+id
		});
		
		if (typeof content == 'object') {
			var c = $(content);//.cloneNode(true);
			
			c.setStyle({'display': 'block'});
			win.appendChild(c);
		} else {
			win.update(content);
		}
		
		$('win').appendChild(win);
		
		win.setStyle({
			'position':	'absolute',
			'display':	'none',
			'left':		pos[0] + 'px',
			'top':		pos[1] + 'px'
		}).setStyle({'zIndex': this.options.zIndex});
		
		this.win = win;
		
		if (this.options.autoOpen) this.open(); 
	},
	
	open: function(pos) {
		if (pos) {
			this.win.style.position 	= 'absolute';
			this.win.style.left 		= pos[0] + 'px';
			this.win.style.top 			= pos[1] + 'px';			
		}
		
		JSWins.current = this;
		
		Debug.add('Opening window');
		
		if (this.options.overlay) {
			$('modal_overlay').appear({'duration': '0.4', 'to': '0.75'});
			if (this.options.overlayClick) $('modal_overlay').setAttribute('onclick', this.options.overlayClick);
			$('modal_overlay').setStyle({'zIndex':this.options.zIndex-1});
		}
		
		if (this.options.center) this.center();
		this.win.appear({'duration': 0.4});
	},
	
	update: function(content) {
		if (typeof content == 'object') {
			this.win.update();
			
			var c = $(content);
			
			c.setStyle({'display': 'block'});
			this.win.appendChild(c);
		} else {
			this.win.update(content);
		}
	},
	
	rePosition: function(pos) {
		this.win.style.position 	= 'absolute';
		this.win.style.left 		= pos[0] + 'px';
		this.win.style.top 			= pos[1] + 'px';
	},
	
	center: function(){
		var element = this.win;
		
		if(!element._absolutized){
			element.setStyle({
				position: 'absolute'
			}); 
			element._absolutized = true;
		}
		var dimensions 	= element.getDimensions();
		Position.prepare();
		var offset_left = (Position.deltaX + Math.floor((this.getWindowWidth() - dimensions.width) / 2));
		var offset_top 	= (Position.deltaY + ((this.getWindowHeight() > dimensions.height) ? Math.floor((this.getWindowHeight() - dimensions.height) / 2) : 0));
		element.setStyle({
			top: ((dimensions.height <= this.getDocumentHeight()) ? ((offset_top != null && offset_top > 0) ? offset_top : '0') + 'px' : 0),
			left: ((dimensions.width <= this.getDocumentWidth()) ? ((offset_left != null && offset_left > 0) ? offset_left : '0') + 'px' : 0)
		});
	},
	
	close: function() {
		if (this.win != undefined) {
			this.win.fade({'duration': 0.25});
			if (this.options.overlay) {
				$('modal_overlay').setAttribute('onclick', '');
				$('modal_overlay').hide();
			}
			
			JSWins.current = false;
		}
	},
	
	destroy: function() {
		if (this.win != undefined) {
			this.close();
			this.win.remove();
		}
	},
	
	getWindowWidth: function(){
		return (self.innerWidth || document.documentElement.clientWidth || document.body.clientWidth || 0);
	},
	
	getWindowHeight: function(){
		return (self.innerHeight ||  document.documentElement.clientHeight || document.body.clientHeight || 0);
	},
	
	getDocumentWidth: function(){
		return Math.min(document.body.scrollWidth,Control.Modal.getWindowWidth());
	},
	
	getDocumentHeight: function(){
		return Math.max(document.body.scrollHeight,Control.Modal.getWindowHeight());
	}
});

JSTabs = Class.create({
	initialize: function(options) {
		Object.extend(this, options);
		
		Object.extend(this, {
			active: ($(this.pageGroup+'-'+options.defaultTab) ? options.defaultTab : false)
		});
		
		if ($(options.parent)) {
			var parent = $(options.parent);
			
			if (this.active == false) {
				if (parent.childElements().length) {
					this.active = parent.select('div')[0].getAttribute('id').split('-')[1];
					
					$(this.parent+'-'+this.active).addClassName('active');
					$(this.pageGroup+'-'+this.active).show();
				}
			}
			
			if (parent.childElements().length) {
				parent.childElements().invoke('makeUnselectable');
				parent.select('div').each(function(e) {
					e.setStyle({cursor: 'pointer'});
				});
			}
		}
	},
	
	change: function(tab) {
		var changeTo = tab.getAttribute('id').split('-')[1];
		
		$(this.pageGroup+'-'+this.active).setStyle({display: 'none'});
		$(this.pageGroup+'-'+changeTo).setStyle({display: this.displayType ? this.displayType : 'block'});
		
		$(this.parent+'-'+this.active).removeClassName('active');
		$(tab).addClassName('active');
		
		this.active = changeTo;
	}
});

Element.addMethods({
	limit: function(element, minValue, maxValue) {
		element = $(element);

		if (parseInt($F(element)) < parseInt(minValue)) element.update(minValue);
		if (parseInt($F(element)) > parseInt(maxValue)) element.value = maxValue;
	},
	
	hidden: function(element) {
		if (element.style.display == 'none') return true;
		return false;
	},
	
	mouseWithin: function(element, evt) {
		var mouse	= {'left': Event.pointerX(evt), 'top': Event.pointerY(evt)};
		var pos 	= element.cumulativeOffset();
		var range	= {
			'left':	$R(pos.left, parseInt(pos.left + element.getWidth())),
			'top': $R(pos.top, parseInt(pos.top + element.getHeight()))
		};
		
		if (range.left.include(mouse.left) && range.top.include(mouse.top)) return true;
	},
	
	makeClickable: function(element, func) {
		element.onclick = func;
		element.makeUnselectable();
		element.setStyle({'cursor': 'pointer'});
	},
	
	hasFocus: function(element) {
		if ($(document.focusedElement) == $(element)) return true;
		
		return false;
	}
});

String.prototype.elementize = function(makeElement) {
	var text 		= unescape(this);
	tDiv 			= new Element('div');
	tDiv.innerHTML 	= text;
	
	if (makeElement === undefined) {
		return tDiv.textContent;
	} else {
		$('temp').update(tDiv.textContent);
		return $('temp').childElements()[0].cloneNode(true);
	}
};

function onElementFocused(e) {
	if (e && e.target) {
		document.focusedElement = (e.target == document) ? null : e.target;
	}
}

if (document.addEventListener) {
	document.addEventListener('focus', onElementFocused, true);
	document.addEventListener('blur', function() {document.focusedElement = null;}, true);
}

function activateCaptions() {
	var inputs = $('body').select("input");
	for (var i = 0; i < inputs.length; i++) {
		if (inputs[i].getAttribute("type") == "text" && inputs[i].hasAttribute('caption')) {
			if (!inputs[i].getAttribute('id')) inputs[i].setAttribute('id', randomString());
			
			inputs[i].value = '';
			
			var cap = new Element('div', {'id': inputs[i].getAttribute('id')+'_caption'}).update(inputs[i].getAttribute("caption")).addClassName('smallfont').makeUnselectable();

			var pos = $(inputs[i]).positionedOffset();
			
			Debug.add(pos.toJSON());
			
			$('etc').appendChild(cap).setStyle({
				'position': 	'absolute',
				'top': 			(pos.top + 2) +'px',
				'left': 		(pos.left + 3) +'px',
				'color': 		'gray',
				'cursor': 		'text',
				'zIndex': 		50
			}).onclick = function() {
				$(this.getAttribute('id').sub('_caption', '')).focus();
			};

			inputs[i].onfocus = function() {
				if ($(this.id+'_caption')) $(this.id+'_caption').hide();
			};

			inputs[i].onblur = function() {
				if ($(this.id+'_caption') && this.value.length == 0) $(this.id+'_caption').show();	
			};
		}
	}
}

window.onload = function() {activateCaptions();};