String.prototype.trim = function() { return this.replace(/^\s+|\s+$/, ''); };

/* Register form function */
function noParticipate(chkID, hideID){
	var el = $(chkID);
	var hidden = $(hideID);
	hidden.value = el.checked;
	var isSponsor = $('is_sponsor_yes').checked;
	if(!isSponsor){
		$('btnContinue1').style.display = (el.checked ? 'none' : 'block');
		$('btnUpdateOnly').style.display = (el.checked ? 'block' : 'none');
	}
}

function validateTab(tabNum){
	var form = $('mainform');
	var isSponsor = $('is_sponsor_yes').checked;
	var sponsorPlaying = $('sponsor_playing').checked;
	var isSponsoredPlayer = $('is_sponsored_player_yes').checked;
	var isFemale = $('gender_female').checked;
	switch(tabNum){
		case 1:
			$('fname').className = empty(Form.Element.getValue('fname')) ? 'error': 'input';
			$('lname').className = empty(Form.Element.getValue('lname')) ? 'error': 'input';
			$('rank').className = empty(Form.Element.getValue('rank')) ? 'error': 'input';
			$('company').className = empty(Form.Element.getValue('company')) ? 'error': 'input';
			$('co_address').className = empty(Form.Element.getValue('co_address')) ? 'error': 'input';
			$('co_city').className = empty(Form.Element.getValue('co_city')) ? 'error': 'input';
			$('co_state').className = empty(Form.Element.getValue('co_state')) ? 'error': 'input';
			$('co_zip').className = empty(Form.Element.getValue('co_zip')) ? 'error': 'input';
			$('bus_phone').className = empty(Form.Element.getValue('bus_phone')) ? 'error': 'input';
			$('email').className = empty(Form.Element.getValue('email')) ? 'error': 'input';
			//$('home_phone').className = !usphone(Form.Element.getValue('home_phone')) ? 'error' : 'input';
			//$('bus_phone').className = !usphone(Form.Element.getValue('bus_phone'),false) ? 'error' : 'input';
			//$('cell_phone').className = !usphone(Form.Element.getValue('cell_phone')) ? 'error' : 'input';
			$('email').className = !isEmail(Form.Element.getValue('email'), false) ? 'error' : 'input';
			
			
			if(isSponsor | isSponsoredPlayer){
				$('sponsor_co').className = empty(Form.Element.getValue('sponsor_co')) ? 'error': 'input';
				var sponsorAmt = Form.Element.getValue('sponsor_amt');
				if(sponsorAmt == ''){
					$('sponsor_amt').className = 'error';
					$('sponsor_amt').onblur = function(){this.className = '';};
				}
			}
			
			if($('classification').value == 'S' | $('classification').value == 'PS'){
				if(!isSponsor & !isSponsoredPlayer){
					alert('Your profile has been flagged as a sponsor or sponsored player.  Please register as either a sponsor or sponsored player.\n If you have any concerns please contact one of the H.O.T.T. Contacts.  Thank You!');
					return false;
				}
			}
			
			break;
		case 2:
			if(!isFemale){
				var mendbl = (!empty($('mendbl_fname').value) & !empty($('mendbl_lname').value));
				var mendbl_assign = $('mendbl_assign').checked;
				$('mendbl_fname').className = (!mendbl & !mendbl_assign) ? 'error' : 'input';
				$('mendbl_lname').className = (!mendbl & !mendbl_assign) ? 'error' : 'input';
				$('mendbl_expander').effect.hide();
				$('mendbl_expander').effect.toggle();
			}else{
				var mixdbl = (!empty($('mixdbl_fname').value) & !empty($('mixdbl_lname').value));
				var mixdbl_assign = $('mixdbl_assign').checked;
				$('mixdbl_fname').className = (!mixdbl & !mixdbl_assign) ? 'error' : 'input';
				$('mixdbl_lname').className = (!mixdbl & !mixdbl_assign) ? 'error' : 'input';
				$('mixdbl_expander').effect.hide();
				$('mixdbl_expander').effect.toggle();
			}
			break;
		case 3:
			//removed because sponsor comments field removed from db by request
			/*
			if(empty(Form.Element.getValue('sponsor_comments'))){
				alert('Please enter comments');
				return false;
			}
			* */
			break;
		case 4:
			//var cc_expander = $('cc_expander');
			//var cc_div = $('cc_div');
			
			if(!(isSponsor && $('nopay_inkind').checked) & !isSponsoredPlayer){
				//cc_expander.effect.hide();
				//cc_expander.effect.toggle();
				var payByCheck = $('pay_check');
				var payByCC = $('pay_creditcard');
				if(!payByCheck.checked && !payByCC.checked){
					alert('Please select a payment option');
					return false;
				}
				if(payByCC.checked){
					$('cc_type').className = empty(Form.Element.getValue('cc_type')) ? 'error': 'input';
					$('cc_name').className = empty(Form.Element.getValue('cc_name')) ? 'error': 'input';
					$('cc_num').className = empty(Form.Element.getValue('cc_num')) ? 'error': 'input';
					$('cc_zip').className = empty(Form.Element.getValue('cc_zip')) ? 'error': 'input';
					$('cc_exp_month').className = empty(Form.Element.getValue('cc_exp_month')) ? 'error': 'input';
					$('cc_exp_year').className = empty(Form.Element.getValue('cc_exp_year')) ? 'error': 'input';
				}
			}
			break;
	}
	
	var elements = Form.getElements(form);
	var errors = elements.findAll(function(el){
		return (el.className == 'error');
	});
	var tabs = document.getElementsByClassName('tab'); //excludes the currently selected tab...
	if(errors.length == 0){
		calculateFee();
		switch(tabNum){
			case 1:  //profile page
				//tabs[0] is participation
				//tabs[1] is sponsorship
				//tabs[2] is payment
				//new user
				if($('btnContinue1').value =='Submit Registration'){
					$('btnContinue1').type = 'submit';
					$('btnContinue1').name = 'update_type';
					$('mainform').submit();
					return true;
				}
				//existing user who will be participating this year
				if($('btnUpdateOnly').style.display == 'none'){
					
					if(isSponsor){
						if(sponsorPlaying){
							openTab(tabs[0]);
						}else{
							openTab(tabs[1]);
						}
					}else{
						openTab(tabs[0]);
					}
					
					//openTab(tabs[(isSponsor? 1 : 0)]); //either player participation or sponsor
				}
				sendFormData();
				break;
			case 2:  //participation page
				//tabs[0] is registration
				//tabs[1] is sponsorship
				//tabs[2] is payment
				openTab(tabs[(isSponsor ? 1 :2)]);
				sendFormData();
				break;
			case 3: //sponsor page
				//tabs[0] is registration
				//tabs[1] is participation
				//tabs[2] is payment
				if($('nopay_inkind').checked){
					$('btnRegister').click();
					return false;
				}
				openTab(tabs[2]); //payment
				sendFormData();
				break;		
				
		}//end switch
		return true;
	}else{
		
		return false;
	}

}


/* home functions */


var gold_sponsors = new Array();
var gold_sponsors_link = new Array();
gold_sponsors[0] ='/images/sponsors/tetra.jpg';
gold_sponsors_link[0] = 'http://www.tetratec.com/';
gold_sponsors[1] ='/images/sponsors/SES.jpg';
gold_sponsors_link[1] = 'http://www.superiorenergy.com';
gold_sponsors[2] ='/images/sponsors/BlackWarrior.gif';
gold_sponsors_link[2] = 'http://www.warriorenergyservices.com';



var silver_sponsors = new Array();
var silver_sponsors_link = new Array();
silver_sponsors[0] ='/images/sponsors/halliburton.gif';
silver_sponsors_link[0] = 'http://www.halliburton.com';
silver_sponsors[1] ='/images/sponsors/bakerhughes.gif';
silver_sponsors_link[1] = 'http://www.bakerhughes.com';
silver_sponsors[2] ='/images/sponsors/ees.png';
silver_sponsors_link[2] = 'http://eeslp.net';
silver_sponsors[3] ='/images/sponsors/oilwell.jpg';
silver_sponsors_link[3] = 'http://www.nov.com/';
//silver_sponsors[2] ='/images/sponsors/burlington_resources_logo.jpg';
//silver_sponsors_link[2] = 'http://www.conocophillips.com';

var sponsors = new Array();
sponsors['gold_sponsor'] = gold_sponsors;
sponsors['gold_sponsor_link'] = gold_sponsors_link;
sponsors['silver_sponsor'] = silver_sponsors;
sponsors['silver_sponsor_link'] = silver_sponsors_link;

function changeSponsors(id, phase){
	if( typeof phase == 'undefined') phase = 'fadeout';
	if( typeof $(id).effect == 'undefined'){
		$(id).effect = new fx.Opacity(id);
	}
	switch(phase){
		case 'fadeout':
			$(id).effect.toggle();
			setTimeout('changeSponsors("'+id+'","rotate")', 2000);
			break;
		case 'rotate':
			var imgSrc = sponsors[id].shift();
			var linkSrc = sponsors[id + '_link'].shift();
			var img = $(id).getElementsByTagName('img')[0];
			var a = $(id).getElementsByTagName('a')[0];
			img.src = imgSrc;
			a.href = linkSrc;
			sponsors[id].push(imgSrc);
			sponsors[id + '_link'].push(linkSrc);
			setTimeout('changeSponsors("'+id+'","fadein")',30);
			break;
		case 'fadein':
			$(id).effect.toggle();
			setTimeout('changeSponsors("'+id+'")', 2000);
			break;
	}
	
}


function addEvent(obj, evType, fn){ 
 if (obj.addEventListener){ 
   obj.addEventListener(evType, fn, false); 
   return true; 
 } else if (obj.attachEvent){ 
   var r = obj.attachEvent("on"+evType, fn); 
   return r; 
 } else { 
   return false; 
 } 
}

addEvent(window, 'load', function(){
	//we define two arrays, containing our toggles and divs.
	var myDivs = document.getElementsByClassName('expandable');
	var myLinks = document.getElementsByClassName('expander');
	for(var i = 0; i < myDivs.length; i++){
		myLinks[i].effect = new fx.Height(myDivs[i], {duration: 400});
		myLinks[i].onclick = function(){this.effect.toggle()};
		if(i > 0){
			myLinks[i].effect.toggle();
		}
	}
	
	if($('rank')) $('rank').options[0] = null;
	if($('is_sponsor_yes') != null){
		toggleSponsor(($('is_sponsor_yes').checked ? $('is_sponsor_yes') : $('is_sponsor_no')));
		if(!$('is_sponsor_yes').checked){
			toggleSponsoredPlayer(($('is_sponsored_player_yes').checked ? $('is_sponsored_player_yes') : $('is_sponsored_player_no')));
		}
	}
	
	//then we create the effect.
	//var myAccordion = new fx.Accordion(myLinks, myDivs, {opacity: true, duration: 400});
	//openTab(document.getElementsByClassName('tab')[1]);
	//myAccordion.showThisHideOpen(myDivs[0]);
	//openTab(document.getElementsByClassName('tab')[0]);
	if($('mainform')){
		if($('mendbl_expander')) updateFeeLabels();
		var elements = Form.getElements('mainform');
		elements.each(function(el){
			//addEvent(el, 'blur', calculateFee);
		});
	}
});

function calculateFee(){
	var fee = 0;
	//Event.stop(window.event);
	var itemization = '';
	var isSponsor = $('is_sponsor_yes').checked;
	var isSponsoredPlayer = $('is_sponsored_player_yes').checked;
	var isFemale = $('gender_female').checked;
	if(isSponsor){ //calc sponsor fee
		var sponsorAmt = Form.Element.getValue('sponsor_amt');
		switch(sponsorAmt){
			case '-1':
				itemization = 'Sponsoring a Player- $0<br/>';
				fee = 0;
				break;
			case '0':
				itemization = 'Sponsoring with Gift in Kind- $0<br/>';
				fee = sponsorAmt;
				break;
			default:
				itemization = 'Selected Sponsor Amount- $' + sponsorAmt + '<br/>';
				fee = sponsorAmt;
		}
	}else if(isSponsoredPlayer){
		itemization = 'Sponsored Player - No Fee';
	}else{ //calc normal registrant fee
		itemization = 'Primary Player Entry Fee - $185<br/>';
		if($('no_participate').checked == false){
			itemization = 'Primary Player Entry Fee - $185<br/>';
			fee = 185;
			var mixdbl = !isFemale & (!empty($('mixdbl_fname').value) | !empty($('mixdbl_lname').value) | $('mixdbl_assign').checked);
			if(mixdbl){ fee+= 60; itemization += 'Mixed Doubles - $60<br/>';}
			var wmdbl = (!empty($('wmdbl1_fname').value) | !empty($('wmdbl1_lname').value) | $('wmdbl_assign').checked);
			if(wmdbl) {fee+= 35; itemization += 'Women\'s Doubles - $35<br/>';}
			var guest = isFemale & (!empty($('guest1_fname').value) | !empty($('guest1_lname').value));
			if(guest) {fee+= 60; itemization += 'Guest or Spouse Men\'s Doubles - $60<br/>';}
			var noplay = (!empty($('noplay_fname').value) | !empty($('noplay_lname').value));
			if(noplay) {fee+= 35; itemization += 'Non-playing Spouse or Guest - $35<br/>';}
			itemization += '<hr/>Total - $' + fee;
		}else{
			itemization = 'Thank You for updating your profile!  We look forward to seeing you next year!<br/>';
		}
		
	}
	//alert(itemization);
	$('itemization').innerHTML = itemization;
	$('fee').value = fee;
	
	if(fee <= 0){
		Form.disable('payment_info');
	}else{
		Form.enable('payment_info');
	}
	
}

function empty(s){
	return (s.trim() == '');
}

function toggleSection(sectionId, chk, enabledIDs){
	if(chk.checked){
		Form.disable(sectionId);
		Form.enable(chk.parentNode);
		if(typeof enabledIDs != 'undefined'){
			var ids = enabledIDs.split(',');
			for(var x = 0; x < ids.length; x++){
				Form.enable($(ids[x]).parentNode);
			}
		}
	}else{
		Form.enable(sectionId);
	}
}

function changeSponsorInstructions(){
	var sponsor_amt = Form.Element.getValue('sponsor_amt');
	var instructions;
	$('nopay_inkind').checked = false;
	switch(sponsor_amt){
		case "500":
			instructions = '<b>Tournament Sponsor</b><br/>$500 Entitles sponsor to enter ' + 
			'ONE PRIMARY PLAYER and Spouse or Mixed Guest. For an additional entry fee of $200, ' +
			'sponsor may invite a SECOND PRIMARY PLAYER, provided that player is in the oil '+
			'industry and has received a separate player invitation letter.  Additional ' +
			'sponsored players will be at $500 increments.';
			break;
		case "700":
			instructions = '<b>Tournament Sponsor</b><br/>$500 Entitles sponsor to enter ' + 
			'ONE PRIMARY PLAYER and Spouse or Mixed Guest. For an additional entry fee of $200, ' +
			'sponsor may invite a SECOND PRIMARY PLAYER, provided that player is in the oil '+
			'industry and has received a separate player invitation letter.  Additional ' +
			'sponsored players will be at $500 increments.';
			break;
		case "1000":
			instructions = '<b>Major Sponsor</b><br/>$1000 In Cash Entitles ' +
			'sponsor to enter TWO PRIMARY PLAYERS with Spouse or Mixed Guests. Major ' +
			'sponsors will be so recognized at all tournament functions and in the tournament '+
			'program.';
			break;
		case "3000":
			instructions = '<b>Silver Sponsor</b><br/>$3000 In Cash Entitles ' +
			'sponsor to enter SIX PRIMARY PLAYERS with Spouse or Mixed Guests. Silver '+
			'sponsors will be so recognized at all tournament functions and in the tournament '+
			'program.';
			break;
		case "5000":
			instructions = '<b>Gold Sponsor</b><br/>$5000 In Cash Entitles ' +
			'sponsor to enter TEN PRIMARY PLAYERS with Spouse or Mixed Guests. Gold ' +
			'sponsors will be so recognized at all tournament functions and in the tournament '+
			'program.';
			break;
		case "10000":
			instructions = '<b>Gold Sponsor</b><br/>$5000 In Cash Entitles ' +
			'sponsor to enter FIFTEEN PRIMARY PLAYERS with Spouse or Mixed Guests. Gold ' +
			'sponsors will be so recognized at all tournament functions and in the tournament '+
			'program.';
			break;
		case "-1": //sponsored player
			instructions = 'sponsored player instructions';
			break;
		case "0": //in-kind sponsor
			$('nopay_inkind').checked = true;
			$('btnContinue3').value = 'Complete Registration';
			instructions = 'Please enter a description of in-kind contributions. ' +
			'You will be contacted by a tournament representative on receipt of your entry.';
			break;
		default:
			
	}
	$('sponsor_instructions').innerHTML = instructions;
}

function updateFeeLabels(){
	var isFemale = $('gender_female').checked;
	if(isFemale){
		$('mendbl_expander').style.display='none';
		$('mendbl_div').style.display='none';
		$('guest_expander').style.display= 'block';
		$('guest_div').style.display= 'block';
		$('mixdbl_msg').innerHTML = 'Primary player covered by fee';
		$('wmdbl_msg').innerHTML = '$35';
	}else{
		$('mendbl_expander').style.display='block';
		$('mendbl_div').style.display='block';
		$('guest_expander').style.display= 'none';
		$('guest_div').style.display= 'none';
		$('mixdbl_msg').innerHTML = '$60';
		$('wmdbl_msg').innerHTML = '$35 - Primary Player\'s mixed partner';
	}
}

function sendFormData(){
	var url = '/user/process';
	var pars = 'interimSave=true&' + Form.serialize($('mainform'));
	var myAjax = new Ajax.Request( 
		url, 
		{ method: 'get', 
		  parameters: pars, 
		  onComplete: interimSave
		}); 
}

function interimSave(originalRequest){
	//alert('saved data');
}

function toggleSponsor(rad){
	if(rad.id == 'is_sponsor_yes'){
		Form.disable($('sponsored_player_cell'));
		setSponsorAmtOptions('sponsor');
		Form.enable($('sponsor_co_cell'));
	}else{
		Form.enable($('sponsored_player_cell'));
		setSponsorAmtOptions();
		$('sponsor_co').className = 'input';
		$('sponsor_amt').className = 'input';
		Form.disable($('sponsor_co_cell'));
	}
}

function togglePaymentType(rad){
	if(rad.id == 'pay_check'){
		$('cc_type').className = 'input';
		$('cc_name').className = 'input';
		$('cc_num').className = 'input';
		$('cc_zip').className = 'input';
		$('cc_exp_month').className = 'input';
		$('cc_exp_year').className = 'input';
	}
}

function toggleSponsoredPlayer(rad){
	if(rad.id == 'is_sponsored_player_yes'){
		Form.disable($('sponsor_cell'));
		setSponsorAmtOptions('sponsored_player');
		Form.enable($('sponsor_co_cell'));
	}else{
		Form.enable($('sponsor_cell'));
		setSponsorAmtOptions();
		$('sponsor_co').className = 'input';
		$('sponsor_amt').className = 'input';
		Form.disable($('sponsor_co_cell'));
	}
}

function setSponsorAmtOptions(param){
	//wipe out whatever's there
	if(typeof param == 'undefined') param = '';
	var currentVal = $('sponsor_amt').options[$('sponsor_amt').selectedIndex].value;
	var options = $('sponsor_amt').options;
	$('sponsor_amt').options.length = 0;
	switch(param){
		case 'sponsor':
			$('sponsor_amt').options[0] = new Option('Please select from the list','');
			$('sponsor_amt').options[1] = new Option('$500','500');
			$('sponsor_amt').options[2] = new Option('$700','700');
			$('sponsor_amt').options[3] = new Option('$1000','1000');
			$('sponsor_amt').options[4] = new Option('$3000','3000');
			$('sponsor_amt').options[5] = new Option('$5000','5000');
			$('sponsor_amt').options[6] = new Option('$10000','10000');
			$('sponsor_amt').options[7] = new Option('In Kind - Specify on Sponsorship Tab','0');
			for(var o = 0; o < options.length; o++){		
				if(options[o].value == '') options[o].selected = false;
				if(options[o].value == currentVal) options[o].selected = true;
				//alert(currentVal + ' ' + options[o].value + ' ' + options[o].selected);
			}
			
			break;
		case 'sponsored_player':
			$('sponsor_amt').options[0] = new Option('$0 -- Sponsored Player','-1');
			break;
		default:
			$('sponsor_amt').options[0] = new Option('-- not applicable --','');	
	}
}

function usphone(s, eOK){  
	eOK = typeof eOK == 'undefined'? true: eOK;
	if(eOK){
		return s=='' ? true :/^[(\[]?\d{3}[)-\.\] ]*\d{3}[-\. ]?\d{4}$/.test(s);
	}else{
		return /^[(\[]?\d{3}[)-\.\] ]*\d{3}[-\. ]?\d{4}$/.test(s);
	}
}

function isEmail (s, eOK){   
	eOK = typeof eOK == 'undefined'? true: eOK;
	s = trim(s);
	if(eOK){
		return s=='' ? true :/^.+\@.+\..+$/.test(s);
	}else{
		return /^.+\@.+\..+$/.test(s);
	}
}

function printForm(){
        var print = open('about:blank',null,'height=600,width=600');
        print.document.write('testing');
        //print.focus();
        document.printWin = print;
        setTimeout('document.printWin.focus();',100);
}

function trim(str)
{
   return str.replace(/^\s*|\s*$/g,"");
}



