/**
 *  Implements dynamic registration flow.
 *  By Cesar Gonzalez
 *  March 25, 2009
 */

window.addEvent('domready', function() {
	
	//can't edit AEC #
	try {
		$('cb_aecid').readOnly = true;
	}catch(err) { }

	function lookupaecidEvent(e) { 
		//alert('called');
		// Prevent the page from changing
		//e = new Event(e);

		var ajaxSuccess = true;
		
		// Get the values from the form
		var myaecid = $('aecidinput').getValue();
		var mydobYear =  $('aecdob_name_Year_ID').getValue();
		var mydobMonth = parseInt($('aecdob_name_Month_ID').getValue())+1;
		var mydobDay =  $('aecdob_name_Day_ID').getValue();
		var mydob = (isNaN(mydobYear) || isNaN(mydobMonth) || isNaN(mydobDay))? '' : mydobYear+'-'+mydobMonth+'-'+mydobDay;

		// Get the AEC data via AJAX
		var req = new Ajax('../../../salesforce/badgelookup.php', {
			method: 	'get',
			data:		{'badge_id':myaecid , 'dob':mydob },
			onRequest: 	function() { $('ajax-loading').setStyle('visibility', 'visible'); },
			onComplete: function() {

				// First, let's break up the PHP response
				var infoString 	= req.response.text;

				if(infoString == 'no badge') {
					$('ajax-results').innerHTML = "<strong><font color=\"#C00C00\">Sorry, the Badge ID was not entered.</font></strong><hr />";
				} else if(infoString == 'no dob') {
					$('ajax-results').innerHTML = "<strong><font color=\"#C00C00\">Sorry, the DOB was not entered.</font></strong><hr />";
				} else  {
					if (infoString == 'no result') {
						$('cbfr_54').setStyle('display', 'none');
						$('ajax-results2').innerHTML = "<strong><font color=\"#C00C00\">Sorry, that Badge ID was not recognized.</font></strong><hr />";
						ajaxSuccess = false;
					} else if(infoString == 'dob mismatch') {
						$('cbfr_54').setStyle('display', 'none');
						$('ajax-results2').innerHTML = "<strong><font color=\"#C00C00\">Sorry, the DOB did not match.</font></strong><hr />";
						ajaxSuccess = false;
					} 
				
					if(ajaxSuccess) {
						var infoArray 	= infoString.split('##;##');
						var badge 		= infoArray[0];
						var name 		= infoArray[1];
						var email 		= infoArray[2];
						var zip 		= infoArray[3]; 
					
						$('name').value = name;
						$('email').value = email;
						if($chk($('auto_reg_badge_id')) && $chk($('auto_reg_dob'))) {
							$('username').value = email;	//setting username as email only if user comes from email link
						}
						$('cb_aecid').value = badge;
						$('zipcode').value = zip;
					}
					
					//copy over the dob from original pane
					$('cb_dob_Year_ID').value = $('aecdob_name_Year_ID').value;
					$('cb_dob_Month_ID').value = $('aecdob_name_Month_ID').value;
					$('cb_dob_Day_ID').value = $('aecdob_name_Day_ID').value;
					var tmpMonth = parseInt($('aecdob_name_Month_ID').value)+1;
					$('cb_dob').value = leadingZeros(tmpMonth,2,'0')+'/'+leadingZeros($('aecdob_name_Day_ID').value,2,'0')+'/'+$('aecdob_name_Year_ID').value;
					
					
					initialForm.toggle().chain(function() { fullForm.toggle(); });	
				}
				$('ajax-loading').setStyle('visibility', 'hidden');
				
									
			}
		}).request();

		//e.stop();

	}

	
	// Only add these events if the html elements actually exist
	if ($('lookupaecid') != null && $('noaecid') != null) {

		// Set up some Effects to use in form trasitions
		var initialForm = new Fx.Slide('registrationTable', {duration: 700});
		var fullForm = new Fx.Slide('originalRegistrationTable', {duration: 700});

		// Initially hide the full registration form
		if($chk($('registration_goto_page2')) && $('registration_goto_page2').getValue() == 'true') {
			initialForm.hide();
		} else {
			fullForm.hide();
		}
		
		
		// If the Lookup button is clicked, do an AJAX call to get the data to
		// populate the corresponding registration fields.
		$('lookupaecid').addEvent('click', lookupaecidEvent);
				
		
		
		
		// If no AEC ID is available, simply display the full registration form.
		$('noaecid').addEvent('click', function(e) {
	
			// this line keeps the page from jumping b/c of position: absolute;
			e = new Event(e);
			
			// Hide the AEC ID field, it would be confusing to display it.
			$('cbfr_54').setStyle('display', 'none');
			
			// And then toggle the initial form out and the full form in.
			initialForm.toggle().chain(function() { fullForm.toggle(); });									
			e.stop();
	
		});

		// I know doing this twice is not the best way to do it, but it works.
		// Is there a way to add events to multiple elements with the same class instead?
		$('forgotaecid').addEvent('click', function(e) {
	
			// this line keeps the page from jumping b/c of position: absolute;
			e = new Event(e);
			
			// Hide the AEC ID field, it would be confusing to display it.
			$('cbfr_54').setStyle('display', 'none');
			
			// And then toggle the initial form out and the full form in.
			initialForm.toggle().chain(function() { fullForm.toggle(); });									
			e.stop();
	
		});
		
		$('register_reset_button').addEvent('click', function(e) {
			fullForm.toggle().chain(function() { initialForm.toggle(); });
			document.getElementById('content').style.height = 375+'px';
			$('ajax-results2').innerHTML = '';
			//If any required fields are red, switch them back to white
			$$('.required').each(function(item, index){
				item.style.backgroundColor = '';
			});
			 
		});
		
	}
	
	

	
	//bind the date of birth text with calendar button 
	/*try {
		Calendar.setup({
	        inputField     :    "dobinput",     // id of the input field
	        ifFormat       :    "%Y/%m/%d",      // format of the input field
	        button         :    "dobinput_image",  // trigger for the calendar (button ID)
	        align          :    "Bl",           // alignment (defaults to "Bl")
	        singleClick    :    true
	    });
	} catch(e) { alert(e);} */ 
	
	//Check if badge id and dob are entered via url, if so set the input boxes
	var DefaultDate = '';
	if($chk($('auto_reg_badge_id')) && $chk($('auto_reg_dob'))) {
		DefaultDate = $('auto_reg_dob').getValue();
		$('aecidinput').value = $('auto_reg_badge_id').getValue(); 
	}  
	
	try {
		var DateName = 'aecdob_name';
		var DateFieldName = 'aecdob_id';
		var Required = false;
		var DateFormat = "MM/DD/YYYY";
		
		var AdditionalInputAttributes = '';
		var YearDropDownStop = '1';
		var YearMin = 1908;
		var YearMax = 2025;
		$('aecdob').innerHTML = '<input type="hidden" name="' + DateFieldName + '" id="' + DateName + '" value="'   + '" ' + AdditionalInputAttributes + ' />';
		$('aecdob').innerHTML += cbcalDateHtml(DateName, Required, DateFormat, DefaultDate, DateFieldName, AdditionalInputAttributes, YearDropDownStop, YearMin, YearMax);
	} catch(e) {}
	
	//Check if badge id and dob are entered via url, if so click "Lookup" to get the info from sales force. 
	if($chk($('auto_reg_badge_id')) && $chk($('auto_reg_dob'))) {
		lookupaecidEvent();
	}
	
});


function leadingZeros(num, totalChars, padWith) {
	num = num + "";
	padWith = (padWith) ? padWith : "0";
	if (num.length < totalChars) {
		while (num.length < totalChars) {
			num = padWith + num;
		}
	} else {}

	if (num.length > totalChars) { //if padWith was a multiple character string and num was overpadded
		num = num.substring((num.length - totalChars), totalChars);
	} else {}
	return num;
}
