
// add a trim function to strings
String.prototype.trim = function(){
	return this.replace(/(?:(?:^|\n)\s+|\s+(?:$|\n))/g,"");
}

// Use this to add functions to be called when the body loads
function onLoad(func) { 
	
	var old = window.onload;
	
	if (typeof window.onload != 'function') { 
		window.onload = func; 
	} else { 
		window.onload = function() { 
			old(); 
			if (func) func(); 
		} 
	} 
}
 
function preloadImages() {
  var d=document; if(d.images){ if(!d.p) d.p=new Array();
    var i,j=d.p.length,a=preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.p[j]=new Image; d.p[j++].src=a[i];}}
}

function restoreImage() {
  var i,x,a=document.sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function findObj(n, d) {
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function swapImage() {
  var i,j=0,x,a=swapImage.arguments; document.sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=findObj(a[i]))!=null&&(a[i+2]==2||!x.p)){if(a[i+2]){document.sr[j++]=x;x.p=false;}else{x.p=true;} if(!x.oSrc) x.oSrc=x.src; x.src=a[i+1];}
}

function setDisplay(n, d){
	var e;
	if(e = findObj(n)){
		e = (e.style ? e.style : e);
		e.display = d;
	}
}

function show(n){
	setDisplay(n, 'block');
}

function hide(n){
	setDisplay(n, 'none');
}

function changeClass(obj, className){
	obj.className = className;
}

function findOffset(object){
	var data = new Array();

	data['left'] = object.offsetLeft;
	data['top'] = object.offsetTop;
	
	var parent = object.offsetParent;

	if (!parent)
		return data;

	while(parent && parent.tagName.toUpperCase() != "BODY" ){
		data['left']  += parent.offsetLeft;
		data['top']   += parent.offsetTop;
		parent = parent.offsetParent;
	}

	data['bottom'] = data['top'] + object.offsetHeight;
	data['right'] = data['left'] + object.offsetWidth;

	return data;

}
function toggleSelects(e){

	if (!e)
		return;
		
	var s = (e.style ? e.style : e);
	
	var data = findOffset(e);
	
	var selects = document.form.getElementsByTagName('select');
	
	for (var i = 0; i < selects.length; i++){
		var data2 = findOffset(selects[i]);
		
		if ( s.display == 'block' &&
			((data['left'] <= data2['left'] && data['right'] >= data2['left']) || (data['left'] <= data2['right'] && data['right'] >= data2['right']))
			&&
			((data['top'] <= data2['top'] && data['bottom'] >= data2['top'] ) || (data['top'] <= data2['bottom'] && data['bottom'] >= data2['bottom']))
			)
		{
		
			selects[i].style.visibility = 'hidden';
		}else{
			selects[i].style.visibility = 'visible';
		}
		
	}
	
}

function createXMLHTTPObject(){
	// Create XML HTTP Request Object
	var xmlhttp=false;
	/*@cc_on @*/
	/*@if (@_jscript_version >= 5)
	// JScript gives us Conditional compilation, we can cope with old IE versions.
	// and security blocked creation of the objects.
	try {
		xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
	} catch (e) {
		try {
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		} catch (E) {
			xmlhttp = false;
		}
	}
	@end @*/
	if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
		xmlhttp = new XMLHttpRequest();
	}
	// END Create
	
	return xmlhttp;
}

function showHelp(button, help_file){
	// load the help box
	var e = findObj('HelpBox');
	var s;
	
	// if it doesn't exist, create it 
	if (!e){
		
		// add the div to the page
		e = document.createElement('div');
		e.setAttribute('id', 'HelpBox');
		e.setAttribute('name', 'HelpBox');
		
		var b = document.getElementsByTagName('body');
		b[0].appendChild(e);
		
		// make it hidden
		s = (e.style ? e.style : e);
		s.display = 'none';
	}
	
	if (e){
		s = (e.style ? e.style : e);
		
		if (s.display == 'none'){
			var xmlhttp = createXMLHTTPObject();
			
			// get the help file
			xmlhttp.open("GET", "/ther_shared/help/" + help_file + '.html',true);
			xmlhttp.onreadystatechange=function() {
				if (xmlhttp.readyState==4) {
					if (xmlhttp.responseText.substring(0,2) != '<!'){
						e.innerHTML = xmlhttp.responseText;
					}else{
						e.innerHTML = 'Sorry, the help file could not be found.';
					}
				}
			};
			xmlhttp.send(null);
			
			var offsets = findOffset(button);
			s.top = offsets['top'] + 'px';
			s.left = (offsets['left'] - button.offsetParent.offsetWidth + 20) + "px";
			s.width = (button.offsetParent.offsetWidth - 75) + "px";			
		}
		
		// toggle the display
		s.display = (s.display == 'none' ? 'block' : 'none');
		
		// hide/show the select boxes (required by IE)
		toggleSelects(e);
		
	}
}

function showInfo(source, info){
	
	if (typeof(loaded) == 'undefined' || !loaded)
		return false;
	
	var div = findObj('InfoBox');
	
	if (!div){
	
		div = document.createElement('div');
		div.setAttribute('id', 'InfoBox');
		document.body.appendChild(div);
	}
	
	div.innerHTML = info;
	
	var offsets = findOffset(source);
	
	var old_div = div;
	div = (div.style ? div.style : div);
	
	div.left = (offsets['left'] + source.offsetWidth + 5) + 'px';
	div.top = (offsets['top'] - 20) +  'px';
	
	show('InfoBox');
	
	// hide/show the select boxes (required by IE)
	//toggleSelects(old_div);
	
	
}
function sendData(){

	var args = sendData.arguments;
	
	if (args.length >= 3){
		var xmlhttp = createXMLHTTPObject();
		
		var parameters = '';
		for(var i = 2; i < args.length; i++){
				parameters += encodeURI('v[' + (i - 1) + ']=' + args[i]) + '&';
		}
		
		var checksum = 0;
		for(var i = 2; i < args.length; i++){

			if (parseInt(args[i]) == args[i])
				args[i] = parseInt(args[i]);

			if (!args[i].length)
				checksum += (args[i] ? args[i] : 0);
			else
				for(var j = 0; j < args[i].length; j++)
					checksum += args[i].charCodeAt(j);
		}
		
		parameters += encodeURI('v[0]=' + checksum);
		
		xmlhttp.open("POST", "/ther_shared/ajax/" + args[0] + '.php',true);
		xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		xmlhttp.setRequestHeader("Content-length", parameters.length);
		xmlhttp.setRequestHeader("Connection", "close");
		
		xmlhttp.onreadystatechange=function() {
			if (xmlhttp.readyState==4) {
				if (typeof(args[1]) == 'function'){
					args[1](xmlhttp.responseText);
				}else{
					if (xmlhttp.responseText.substring(0,2) != '<!'){
						if (args[1])
							args[1].value = xmlhttp.responseText;
					}else{
						window.alert('An error occurred while trying to save your changes. Please try again.');
					}
				}
			}
		};
		xmlhttp.send(parameters);
		
		
	}
}

function currencyFormat(field, event, add_decimals, skip_commas){
	
	var dollars, cents;
	var valid_characters = '0123456789.';
	var input = (field.value ? field.value : field) + '';
	var decimal_found = false;
	var key_code = (event && window.Event ? event.which : event.keyCode);

	// return if tab key pressed
	if (key_code == 9)
		return;

	// strip unwanted characters
	for(var i = 0; i < input.length; i++){
		var check = input.substring(i, i+1);
		
		// if not in the list of valid characters, remove it
		if (valid_characters.indexOf(check) < 0 || (check == '.' && decimal_found)){
			input = (i > 0 ? input.substring(0, i) : '') + '' + (i < input.length - 1 ? input.substring(i + 1) : '');
			i--;
		}

		// if a decimal
		if (check == '.'){
			
			// set to true to only allow 1 decimal
			decimal_found = true;

			// if it's the first character of the input, add a 0 to the front
			if (i == 0){
				input = '0' + input;
				i++;
			}
		}

	}

	// make sure cents isn't greater than 2 digits in length, and pad with 0s if neccessary
	if (add_decimals || (decimal_found && input.length - input.indexOf('.') > 3)){
		
		if (decimal_found){
			dollars = input.substring(0, input.indexOf('.'));
			cents = input.substring(input.indexOf('.') + 1);
                        //cents = Math.round(cents / 100).toString();

			if (cents.length < 2)
				cents = cents.substring(0, cents.length);
			else if (cents.charAt(2) > 4)
				cents = (parseFloat(cents.substring(0, 2))+1).toString();
			else
				cents = cents.substring(0, 2);

		}else{
			dollars = input;
			cents = 0;
		}

		cents += '';

		// add 0s where necessary
		while(cents.length < 2)
			cents += '0';

		input = dollars + '.' + cents;

	}

	// add commas
	if (decimal_found || add_decimals){

		dollars = input.substring(0, input.indexOf('.'));
		cents = input.substring(input.indexOf('.') + 1);

		// add commas to the dollar amount (disabled since PHP 4.3.9 seems to interpret commas as decimals)
//		if (!skip_commas)
		if (false)
		for(var i = dollars.length - 3; i > 0; i = i - 3)
			dollars = dollars.substring(0, i) + ',' + dollars.substring(i);

		input = dollars + '.' + cents;

	}

	if (field.value){
		field.value = input;
	}else{
		return input;
	}
	
}

function syncDates(select_name, field_name){
	
	if (select_name.indexOf('start') >= 0 || select_name.indexOf('end') >= 0){
		
		monthBox = document.form.elements[select_name + '_month'];
		dayBox = document.form.elements[select_name + '_day'];
		yearBox = document.form.elements[select_name + '_year'];
		date = document.form.elements[field_name];
		
		var other = select_name.replace((select_name.indexOf('start') >= 0 ? 'start' : 'end'), (select_name.indexOf('start') >= 0 ? 'end' : 'start'));
		
		monthBox2 = document.form.elements[other + '_month'];
		dayBox2 = document.form.elements[other + '_day'];
		yearBox2 = document.form.elements[other + '_year'];	
		date2 = document.form.elements[field_name.replace(select_name, other)];
		
		if (monthBox2 && dayBox2 && yearBox2 && date2){
			var compare = 0;
			
			if (parseInt(yearBox.value) < parseInt(yearBox2.value))
				compare =  -1;
			else if (parseInt(yearBox.value) > parseInt(yearBox2.value))
				compare =  1;
				
			if (!compare && parseInt(monthBox.value) < parseInt(monthBox2.value))
				compare =  -1;
			else if (!compare && parseInt(monthBox.value) > parseInt(monthBox2.value))
				compare =  1;
				
			if (!compare && parseInt(dayBox.value) < parseInt(dayBox2.value))
				compare =  -1;
			else if (!compare && parseInt(dayBox.value) > parseInt(dayBox2.value))
				compare =  1;
				
			if ((select_name.indexOf('start') >= 0 && compare == 1) || (select_name.indexOf('end') >= 0 && compare == -1)){
				monthBox2.value = monthBox.value;	
				dayBox2.value = dayBox.value;
				yearBox2.value = yearBox.value;
				date2.value = date.value;
				
			}
			
		}
		
	}
	
}

function checkin(img, field, id, club_number, type){
	
	if (club_number)
		sendData('checkin', '', id, club_number);
	else
		sendData('checkin', '', id);
	//alert(field.value);
	field.value = (!field.value.length ? (type == 'checked' ? 'yes' : 'no') : '');
	//alert(field.value);
	swapImage(img, '/ther_shared/images/booking/checkbox' + (field.value.length ? '_' + type : '') + '.gif', 1);
}

function popup(file, base, width, height, field, scrolling){
	newWindow = window.open((base ? base : '') + file + (field ? '?field=' + field : ''), 'Roster', 'height=' + height + ',width=' + width + ',menubar=no,scrollbars=' + (scrolling ? 1 : 0) + ',status=no');
	newWindow.focus();
}

function showRoster(field, base){
	popup('roster.php', base, 330, 415, field);
}

function str2hex(str){
	
	if (!str)
		return;
		
	var digits = "0123456789ABCDEF";	
	var hex = '';
	
	for(var i = 0; i < str.length; i++){
		var d = str.charCodeAt(i);
		var h = digits.substr(d&15,1);
		while(d>15){d>>=4;h=digits.substr(d&15,1)+h;}	
		hex += h;
	}
	
	return hex;
		
}

function hex2str(hex){
	
	if (!hex)
		return;
		
	hex = hex.toString();
	var str = '';
	
	for(var i = 0; i < hex.length; i += 2)
		str += String.fromCharCode(parseInt(hex.charAt(i) + hex.charAt(i+1), 16));
		
	return str;		
}

function showVideo(file, width, height){
	
	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = windowWidth;
	} else {
		pageWidth = xScroll;
	}
	
	if (self.pageYOffset) {
		yScroll = self.pageYOffset;
	} else if (document.documentElement && document.documentElement.scrollTop){	 // Explorer 6 Strict
		yScroll = document.documentElement.scrollTop;
	} else if (document.body) {// all other Explorers
		yScroll = document.body.scrollTop;
	}
	
	
	var d = document.getElementById('Overlay');
	
	if (!d){
		d = document.createElement('div');
		d.setAttribute('id', 'Overlay');
		document.body.appendChild(d);
	}
	
	var c = document.getElementById('Close');
	
	if (!c){
		c = document.createElement('div');
		c.setAttribute('id', 'CloseVideo');
		c.innerHTML = '<div onClick="hide(\'Overlay\');hide(\'CloseVideo\');hide(\'Video\'); var v = document.getElementById(\'Video\'); document.body.removeChild(v); return false;">Close Video</a></div>';
		document.body.appendChild(c);		
	}
	
	var v = document.getElementById('Video');
	
	if (!v){
		v = document.createElement('div');
		v.setAttribute('id', 'Video');
		document.body.appendChild(v);
	}
		
	d.style.height = pageHeight + 'px';
	
	c.style.top = (yScroll + (windowHeight / 15) + height + 10) + 'px';
	
	
	v.style.top = yScroll + (windowHeight / 15) + 'px';
	
	show('Overlay');
	show('CloseVideo');
	show('Video');
	
	v.innerHTML = '<OBJECT CLASSID="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" WIDTH="' + width + '" HEIGHT="' + height + '" id=tutorial CODEBASE="http://active.macromedia.com/flash5/cabs/swflash.cab#version=5,0,0,0"><PARAM NAME=movie VALUE="../ther_shared/help/flash/' + file + '"><PARAM NAME=play VALUE=true><PARAM NAME=loop VALUE=false><PARAM NAME=quality VALUE=low><EMBED name="tutorial" SRC="../ther_shared/help/flash/' + file + '" WIDTH="' + width + '" HEIGHT="' + height + '" quality="high" loop="false" TYPE="application/x-shockwave-flash" PLUGINSPAGE="http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash"></EMBED></OBJECT>';
	
}

function clock(location, offset){
	
	if (offset){
		setTimeout("clock(" + location + ")", (60 - offset) * 1000);	
		return;	
	}
	
	process = function(data) {
		var d = document.getElementById('Clock');	
		
		if (d && data){
			var backup = d.innerHTML;
			data = data.split('|');
			d.innerHTML = (data[0].length > 8 ? backup : data[0]);
			setTimeout("clock(" + location + ")", (60 - (isNaN(data[1]) ? 0 : data[1])) * 1000);
		}
		
	}
		
	sendData('get_time', process, location);
		
}

function preload(){
	preloadImages('/ther_shared/images/buttons/button_login_over.gif', '/ther_shared/images/buttons/button_login_click.gif', '/ther_shared/images/buttons/button_add_over.gif', '/ther_shared/images/buttons/button_add_click.gif', '/ther_shared/images/buttons/button_delete_over.gif', '/ther_shared/images/buttons/button_delete_click.gif', '/ther_shared/images/buttons/button_submit_over.gif', '/ther_shared/images/buttons/button_submit_click.gif', '/ther_shared/images/buttons/button_next_over.gif', '/ther_shared/images/buttons/button_next_click.gif', '/ther_shared/images/buttons/button_save_over.gif', '/ther_shared/images/buttons/button_save_click.gif');
}

