function spiConstr() {
	
	initQuerystring();

	initBrowser();

	initDialog();

	initForm();

	initButtons();

	initCalendars();

	// v1.5 override fees
	var regex = /^[A-Za-z\-]+/;
	if ((_REQUEST['fref'])&&(regex.test(_REQUEST['fref']))) {
		_FEE_REF = _A_REF = _REQUEST['fref'];
	}

	// updated to allow for customized fee
	_FEE_REF ? initFees(_FEE_REF) : initFees('pop-warner');

	window.setTimeout(checkAutoload,1000);
}
function checkAutoload() {
	if (_REQUEST['autoload'] == 'true') {
		$('modal-submit').show();
	}
}
function initQuerystring() {

	_REQUEST = new Array();

	var arrQs = location.href.split('?');

	// if there is a querystring
	if (arrQs.length > 1) {
		
		// split the pairs
		var arrPairs = arrQs[1].split('&');
		
		// for each pair
		for (var i=0; i<arrPairs.length; i++) {
			
			arrNameValue = arrPairs[i].split('=');
			
			// save name value
			if (arrNameValue.length>1) {
				_REQUEST[arrNameValue[0]] = arrNameValue[1];
			}
		}
	}
}
function initFees(name) {
	_FEES_REQ = name;
	var d = new Date();
	_FEES_URI += '?'+d.getTime();
	var ajaxOrder = new Ajax.Request(_FEES_URI, {

		method: 'get',
		onSuccess: function(transport) {
			var xmlDoc = transport.responseXML.documentElement;
			var xmlFees = xmlDoc.getElementsByTagName("fees");
			var found = false;
			for (var i=0; i<xmlFees.length; i++) {
				if (xmlFees[i].getAttribute("name") == _FEES_REQ) {
					$('fee-set-up').innerHTML = xmlFees[i].getElementsByTagName('set-up')[0].childNodes[0].nodeValue;
					$('fee-credit-card-processing').innerHTML = xmlFees[i].getElementsByTagName('credit-card-processing')[0].childNodes[0].nodeValue;
					$('fee-per-player-registration').innerHTML = xmlFees[i].getElementsByTagName('per-player-registration')[0].childNodes[0].nodeValue;

					// 1.1 - add another field
					$('fee-check-processing').innerHTML = xmlFees[i].getElementsByTagName('check-processing')[0].childNodes[0].nodeValue;

					if (xmlFees[i].getElementsByTagName('discounts').length > 0) {
						var xmlDiscounts = xmlFees[i].getElementsByTagName('discounts')[0];
						var innerfind = false;
						if (xmlDiscounts.getElementsByTagName('set-up').length > 0) {
							$('fee-set-up').className = 'linethrough';
							$('fee-discounted-set-up').innerHTML = xmlDiscounts.getElementsByTagName('set-up')[0].childNodes[0].nodeValue;
							innerfind = true;
						}
						else {
							$('fee-discounted-set-up').className = 'fee-inactive';
						}
						if (xmlDiscounts.getElementsByTagName('credit-card-processing').length > 0) {
							$('fee-credit-card-processing').className = 'linethrough';
							$('fee-discounted-credit-card-processing').innerHTML = xmlDiscounts.getElementsByTagName('credit-card-processing')[0].childNodes[0].nodeValue;
							innerfind = true;
						}
						else {
							$('fee-discounted-credit-card-processing').className = 'fee-inactive';
						}
						if (xmlDiscounts.getElementsByTagName('per-player-registration').length > 0) {
							$('fee-per-player-registration').className = 'linethrough';
							$('fee-discounted-per-player-registration').innerHTML = xmlDiscounts.getElementsByTagName('per-player-registration')[0].childNodes[0].nodeValue;
							innerfind = true;
						}
						else {
							$('fee-discounted-per-player-registration').className = 'fee-inactive';
						}
						// 1.1 - add another field 
						// <![CDATA[
						if (xmlDiscounts.getElementsByTagName('check-processing').length > 0) {
							$('fee-check-processing').className = 'linethrough';
							$('fee-discounted-check-processing').innerHTML = xmlDiscounts.getElementsByTagName('check-processing')[0].childNodes[0].nodeValue;
							innerfind = true;
						}
						else {
							$('fee-discounted-check-processing').className = 'fee-inactive';
						}
						// ]]>
						innerfind ? '' : $('fee-discounts').style.display = 'none';
					}
					else {
						$('fee-discounts').style.display = 'none';
					}
					found = true;
				}
			}
			// 1.1 - add fee-check-processing
			found ? '' : $('fee-set-up').innerHTML = $('fee-credit-card-processing').innerHTML = $('fee-per-player-registration').innerHTML = $('fee-check-processing').innerHTML = 'xxx';
		},
		onFailure: function(transport) {
			alert('Unable to load fees for '+name);
		}
	});

}

function initCalendars() {
	
	_FN_UPDATE_FIELD = function(d) {
		$(_CALENDAR_CURRENT_INPUT).value = d.format('mm/dd/yyyy');
		calendar.toggleCalendar();
	}

    var imgCalendar_Click = function(e, input)
    {
        showCalendar("calendar", input, "calendar-container", Event.element(e));
    };

	Event.observe("billing-start", "click", imgCalendar_Click.bindAsEventListener(this, "billing-start"));
	Event.observe('billing-start', 'blur', function(event) { checkValid($('billing-rep')) } );

}
function validateDate() {
	return isDate($('billing-start').value);
}
function addFee(fee) {
	// 1.1 - include other fee
	_FEES_VAL.length < 4 ? _FEES_VAL.push(fee) : '';
}

function initButtons() {
	Event.observe('next-0', 'click', function(event) {
		var e = new Effect.Fade($('modal-content-form'), { from: 1.0, to: 0.0, queue: 'end', duration: 1.0 });
		var f = new Effect.Appear($('modal-content-billing'), { from: 0.0, to: 1.0, queue: 'end', duration: 1.0 });
	});

	Event.observe('previous-1', 'click', function(event) {
		var e = new Effect.Fade($('modal-content-billing'), { from: 1.0, to: 0.0, queue: 'end', duration: 1.0 });
		var f = new Effect.Appear($('modal-content-form'), { from: 0.0, to: 1.0, queue: 'end', duration: 1.0 });
	});

	Event.observe('next-1', 'click', function(event) {
		loadContract();
		var arrCells = $$('tbody#final-fee-discounts td');

		for (var i=0; i<arrCells.length; i++) {
			arrCells[i].getElementsByTagName('h4')[0].innerHTML = $$('tbody#fee-actual td')[i].innerHTML;
			if ($$('tbody#fee-discounts td')[i].innerHTML != '') {
				arrCells[i].getElementsByTagName('h3')[0].innerHTML = $$('tbody#fee-discounts td')[i].innerHTML;
				addFee($$('tbody#fee-discounts td')[i].innerHTML);
			}
			else {
				arrCells[i].getElementsByTagName('h3')[0].style.display = 'none';
				arrCells[i].getElementsByTagName('h4')[0].className = 'normal';
				addFee($$('tbody#fee-actual td')[i].innerHTML);
			}
		}
		var e = new Effect.Fade($('modal-content-billing'), { from: 1.0, to: 0.0, queue: 'end', duration: 1.0 });
		var f = new Effect.Appear($('modal-content-contract'), { from: 0.0, to: 1.0, queue: 'end', duration: 1.0 });
		var g = new Effect.Fade($('pre-pricing'), { from: 1.0, to: 0.0, queue: 'end', duration: 0.5 });
		var h = new Effect.Appear($('final-pricing'), { from: 0.0, to: 1.0, queue: 'end', duration: 0.5 });
	});
	
	Event.observe('previous-2', 'click', function(event) {
		var g = new Effect.Fade($('final-pricing'), { from: 1.0, to: 0.0, queue: 'end', duration: 0.5 });
		var h = new Effect.Appear($('pre-pricing'), { from: 0.0, to: 1.0, queue: 'end', duration: 0.5 });


		var e = new Effect.Fade($('modal-content-contract'), { from: 1.0, to: 0.0, queue: 'end', duration: 1.0 });
		var f = new Effect.Appear($('modal-content-billing'), { from: 0.0, to: 1.0, queue: 'end', duration: 1.0 });
	});

	Event.observe('print-2', 'click', function(event) {
		previewContract();
	});
	Event.observe('submit-2', 'click', function(event) {
		submitOrder();
	});

	Event.observe('agree', 'click', function(event) {
		$('submit-2').disabled = !$('agree').checked;
	});
}
function submitOrder() {
	var values = new Array();

	// build data
	$$('input').each(function(objInput) {
		if (objInput.type == 'checkbox') {
			values.push({ id: objInput.id, value: objInput.checked ? objInput.value : 'false' });
		}
		else {
			objInput.type != 'button' ? values.push({ id: objInput.id, value: objInput.value }) : '';
		}
	});
	$$('select').each(function(objDropDown) {
		values.push({ id: objDropDown.id, value: objDropDown.options[objDropDown.selectedIndex].text });
	});
	values.push({ id: 'fee-setup', value: _FEES_VAL[0] });
	values.push({ id: 'fee-cc', value: _FEES_VAL[1] });
	values.push({ id: 'fee-registration', value: _FEES_VAL[2] });

	// 1.1 - add to template
	values.push({ id: 'fee-check', value: _FEES_VAL[3] });

	// 1.1 - add referer
	values.push({ id: 'agreement-ref', value: _A_REF ? _A_REF : '-' });
	
	// build querystring
	var querystring = '?';
	for (var i=0; i<values.length; i++) {
		querystring += values[i].id + '=' + escape(values[i].value.replace(/\+/,'&#43;').replace(/\-/,'&#45;')) + '&';
	}
	var d = new Date();
	querystring += d.getTime();

	// submit
	$('submit-2').disabled = $('agree').disabled = true; 
	var ajaxOrder = new Ajax.Request(_ORDER_PROCESSING_URI+querystring, {
		method: 'get',
		onSuccess: function(transport) {
			var xmlDoc = transport.responseXML.documentElement;
			if (xmlDoc.getElementsByTagName("success")[0].childNodes[0].nodeValue == "true") {
				alert('Thank you for your submission! You will receive a confirmation email shortly.');
				$('modal-submit').hide();
			}
			else {
				var errMessage = xmlDoc.getElementsByTagName("errormsg")[0].childNodes[0].nodeValue;
				var errLine = xmlDoc.getElementsByTagName("errormsg")[0].getAttribute("trace");
				alert("Line " + errLine + ": "+ errMessage);
			}
		},
		onFailure: function(transport) {
			alert('HTTP Request Failure! Please check your email and try again.');
			$('submit-2').disabled = $('agree').disabled = false;
		}
	});
	var t='';
	for (var i=0; i<values.length; i++) {
		t += values[i].id+',';
	}
}
function previewContract() {
	var winOptions='';
	for (var name in _WINDOW_OPTIONS) {
		winOptions += name+'='+_WINDOW_OPTIONS[name]+',';
	}
	var winContract = window.open('contract.htm','contractWindow',winOptions.substring(0,winOptions.length-1));
	winContract.document.open();
	winContract.document.write('<link href="css/pricing.css" rel="stylesheet" type="text/css" />');
	winContract.document.write('<div id="final-pricing">' + $('final-pricing').innerHTML + '</div>');
	winContract.document.write($('contract-content').innerHTML);
	winContract.window.print();
	winContract.document.close();
}
function loadContract() {
	if (_CONTRACT == '') {
		var ajaxContract = new Ajax.Request(_CONTRACT_URI, {
			method: 'get',
			onSuccess: function(transport) {
				_CONTRACT = transport.responseText;
				$('contract-content').innerHTML = _CONTRACT;
				updateContractInformation();
			},
			onFailure: function(transport) {
				alert('Error: Unable to load contract');
			}

		});
	}
	else {
		updateContractInformation();
	}

}
function updateContractInformation() {
	var startDate = new Date();
	$('ajaxStartDate').innerHTML = _DATES_MONTHS[startDate.getMonth()] + ' ' + startDate.getDate() + ', ' + startDate.getFullYear();
	$('ajaxOrg').innerHTML = $('org-name').value; 

}
function initBrowser() {

	var nav = navigator.userAgent;

	// opera doesnt like scrollbars in divs
	if (nav.indexOf('Opera') != -1) {
		$('form-container').className = 'form-container-opera';
	}

}

function checkValid(obj) {

	// check validity
	var v = true;
	for (var i=0; i<_VALIDATION.length; i++) {
		if (_VALIDATION[i].step == _VALIDATION[obj.offset].step) {
			if (!_VALIDATION[i].valid) {
				v = false;
			}
		}
	}

	if ((_VALIDATION[obj.offset].step == 1)&&(v)) {
		v = validateDate();
	}
	$('next-'+_VALIDATION[obj.offset].step).disabled = !v;
}
function initForm() {

	// update country
	Event.observe('org-country', 'change', function(event) {
		if ($('org-country').selectedIndex == 0) { // US

			// update labels
			$('org-zip-label').innerHTML = 'Zip Code:';

			// load US states
			removeOptions($('org-state'));
			populateOptions($('org-state'), _STATES, false);
		}
		else { // CANADA
			// update labels
			$('org-zip-label').innerHTML = 'Postal Code:';

			// load provinces
			removeOptions($('org-state'));
			populateOptions($('org-state'), _PROVINCES, false);
		}
	});

	removeOptions($('org-state'));
	populateOptions($('org-state'), _STATES, false);
	removeOptions($('billing-state'));
	populateOptions($('billing-state'), _STATES, false);

	// attach validations
	for (var i=0; i<_VALIDATION.length; i++) {
		$(_VALIDATION[i].name).offset = i;
		$(_VALIDATION[i].name).value = '';
		Event.observe(_VALIDATION[i].name, 'blur', function(event) {
			// invalid
			if (!_VALIDATION[event.element().offset].regex.test(event.element().value)) {
	
				// show error
				showError(_VALIDATION[event.element().offset]);

			}
			else {
				event.element().className = '';
				_VALIDATION[event.element().offset].valid = true;
				$(_VALIDATION[event.element().offset].name+'-err').className = 'err modal-hidden';
			}
			checkValid(event.element());

		});
		$(_VALIDATION[i].name+'-err').title = _VALIDATION[i].errormsg;
		$$('img#'+_VALIDATION[i].name+'-err').each(function(input) {
				new Tooltip(input, {backgroundColor: "#333", borderColor: "#333", textColor: "#FFF", textShadowColor: "#000", mouseFollow: false, opacity: 1, format: _VALIDATION[i].format});
		});
	}


	Event.observe('billing-prefill', 'click', function(event) {
		if (event.element().checked) {

			// update country and state
			$('billing-country').selectedIndex = $('org-country').selectedIndex;
			removeOptions($('billing-state'));
			if ($('billing-country').selectedIndex == 0) {
				populateOptions($('billing-state'), _STATES, false);
			}
			else {	
				populateOptions($('billing-state'), _PROVINCES, false);
				$('billing-zip-label').innerHTML = 'Postal Code:'; 
			}
			$('billing-state').selectedIndex = $('org-state').selectedIndex;

			// update text fields
			$('billing-rep').value = $('org-rep').value;
			$('billing-checks').value = $('org-name').value;
			$('billing-email').value = $('org-email').value;
			$('billing-phone').value = $('org-phone').value;
			$('billing-fax').value = $('org-fax').value;
			$('billing-address').value = $('org-address').value;
			$('billing-city').value = $('org-city').value;
			$('billing-zip').value = $('org-zip').value;

			// turn off errors and validate
			for (var i=0; i<_VALIDATION.length; i++) {
				if (_VALIDATION[i].step == 1) {
					$(_VALIDATION[i].name).className = '';
					$(_VALIDATION[i].name+'-err').className = 'err modal-hidden';
					_VALIDATION[i].valid = true;
				}
			}

		}
		else {
		}
	});
}
function showError(objValidation) {
	if (objValidation.required) {
		$(objValidation.name).className = 'invalid';
		$(objValidation.name+'-err').className = 'err';
		objValidation.valid = false;
		
	}
}
function populateOptions(e, val, nv) {
	for (var i=0; i<val.length; i++) {
		if (nv) {
			e.options[i] = new Option(val[i].name, val[i].value);
		}
		else {
			e.options[i] = new Option(val[i], val[i]);
		}
	}
}
function removeOptions(e) {
	var i = e.options.length;

	for (var j=0; j<i; j++) {
		e.options[0] = null;
	}
}

function initDialog() {
	new Dialog.Box('modal-submit');
	$('modal-submit').hide();
	$('modal-submit').className = '';
	$('modal-content-contract').hide();

	window.onresize = function() {
		var modHeight = $('modal-submit').getHeight();
		var bodyHeight = document.viewport.getHeight();
		var vOffset = (bodyHeight - modHeight) / 2;

		if (vOffset < 0) {
			vOffset = 0;
		}
		var modWidth = $('modal-submit').getWidth();
		var bodyWidth = document.viewport.getWidth();
		var hOffset = (bodyWidth - modWidth) / 2;

		if (hOffset < 0) {
			hOffset = 0;
		}
		$('modal-submit').setStyle({ top: vOffset + 'px', left: hOffset + 'px' });

		$('dialog_overlay').setStyle({ height: bodyHeight + 'px' });
	}
	
	Event.observe('modal-close','click',function(evt) {
		$('modal-submit').hide();
	});
}


function debug(fn, msg) {
	$('debug').value = fn+': '+msg+"\n"+$('debug').value;
}

function isDate(dateStr) {

	var datePat = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
	var matchArray = dateStr.match(datePat); // is the format ok?

	if (matchArray == null) {
		return false;
	}

	month = matchArray[1];
	day = matchArray[3];
	year = matchArray[5];

	if (month < 1 || month > 12) { // check month range
		return false;
	}

	if (day < 1 || day > 31) {
		return false;
	}

	if ((month==4 || month==6 || month==9 || month==11) && day==31) {
		return false;
	}

	if (month == 2) { // check for february 29th
		var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
		if (day > 29 || (day==29 && !isleap)) {
			return false;
		}
	}
	return true; // date is valid
}