var manuallyTypedInSiteAddress = false;
var total = 0;
var service_total = 0;
var disk_space_total = 0;
var ad_option_total = 0;
var coppa_date = new Date();
var displayName_check_timer = null;
var site_check_timer = null;
var display_name_available = true;
var sitename_available = true;
var younger_than_13 = false;

// create some default 'state' and 'zip' label names.
// these correspond to the first couple country codes (1, 2) which are USA, Canada
// 0 is the 'default' label to be used for any country that doesn't have a specific one
var state_label_names = ['State/Province','State','Province'];
var zip_label_names = ['Postal Code','Zip Code','Postal Code'];



function init() {

	// Set the date on which coppa rules would take effect
	coppa_date.setFullYear(coppa_date.getFullYear() - 13);

	// this will run most scripts on the page as soon as it is loaded.
	// this way any fields that are pre-filled (because of a browser reload or being sent
	// back here with error messages) will trigger the proper functions on the page
	//fieldsetBlock.changeFeeType();
	//fieldsetBlock.showHideLeagueInfo();
	//fieldsetBlock.selectCountry('contact',false);
	//fieldsetBlock.sportChange();
	//fieldsetBlock.checkSite();
	//fieldsetBlock.changeSiteType();
	// fieldsetBlock.updateSiteAddress();
	//fieldsetBlock.selectFeatureService();
	//fieldsetBlock.selectFeatureDiskSpace();
	//fieldsetBlock.selectFeatureAdOption();
	fieldsetBlock.selectCountry('account');
	
	// SET DROP DOWNS //
	fieldsetBlock.selectAccountGender();

}

var fieldsetBlock = {
	
	selectAccountGender: function() {
		temp = 1;
	
	},
	
	
	selectCountry: function(type, overwriteStateText) {
		var type = 'account';
		var country_code = $(type+'_country').value;
		var states_select = $(type+'_state_select');
		
		// change the names of the "States" and "Zip" labels
		// if there's a specific label for this country, show it
		if (state_label_names[country_code] != undefined) {
			$(type+'_state_select_label').innerHTML = state_label_names[country_code];
			$(type+'_state_text_label').innerHTML = state_label_names[country_code];
			$(type+'_zip_label').innerHTML = zip_label_names[country_code];
		} else {
			// otherwise show the default first item
			$(type+'_state_select_label').innerHTML = state_label_names[0];
			$(type+'_state_text_label').innerHTML = state_label_names[0];
			$(type+'_zip_label').innerHTML = zip_label_names[0];
		}
		
		// remove all current states from the dropdown
		states_select.options.length = 0;
		
		// re-populate the states dropdown with the proper states
		if (states[country_code]) {
			// create the default 'Select...' option
			if (country_code == 1)
				states_select.options[0] = new Option('State','',true,false);
			else
				states_select.options[0] = new Option('Province','',true,false);
			states_select.options[1] = new Option('','',false,false);
			
			// loop through all of the newly created states and populate the dropdown list with them
			for(var i=0;i<states[country_code].length;i++) {
				states_select.options[i+2] = new Option(states[country_code][i].name, states[country_code][i].id, false, false);
			}
			
			// Show the dropdown and hide the text entry (because it will be a known state)
			Element.show(type+'_state_select_div');
			Element.hide(type+'_state_text_div');
		} else {
			// Show the textfield and hide the dropdown (because we don't know the name of the state)
			// dont overwrite on the js page init, only on users country onchange event
			if (overwriteStateText) {
				$(type+'_state_text').value = '';
				states_select.options[0] = new Option('','');
			}
			Element.hide(type+'_state_select_div');
			Element.show(type+'_state_text_div');
		}
		
		// show or hide the div containing the city/state/div boxes
		/*
		if(country_code != '') {
			Element.show(type+'_city_state_div');
		} else {
			Element.hide(type+'_city_state_div');
		}
		*/
	},
	
	showErrorMessage: function() {
		Element.show('form_errors');
	},
	
	hideErrorMessage: function() {
		Element.hide('form_errors');
	},
	
	fillContactInfo: function() {
	
		// if($F('new_account')) {
			$('contact_country').value = $('account_country').value;
			// Update the rest of the fields with proper labels
			this.selectCountry('contact');
			$('contact_address').value = $('account_address').value;
			$('contact_zip').value = $('account_zip').value;
			$('contact_city').value = $('account_city').value;
			
			if($('contact_state_text_div').style.display == 'none') {
				$('contact_state_select').value = $('account_state_select').value;
				$('contact_state_text').value = '';
			} else {
				$('contact_state_text').value = $('account_state_text').value;
				$('contact_state_select').selectedIndex = 0;
			}
			
		/*
		} else {
			// take the person's login info and get their contact data
			if($F('account_email_1') != '') {
				if($F('account_password_1') != '') {
					Element.show('contact_info_fill_indicator');
					new Ajax.Updater(	'', 
										'/proxy.cfm?service=build_site&method=get_contact_info&email='+$F('account_email_1'), 
										{	asynchronous:true,
											evalScripts: true });
				} else {
					// password was blank
					location.href = '#';
					alert('Please enter your password');
				}
			} else {
				// username was blank
				location.href = '#';
				alert('Please enter your username');
			}
		}
		*/
	},
	
	checkDisplayName: function() {
		if($('account_display_name').value != '') {
			if(displayName_check_timer != null) {
				// cancel previous timer
				this.stopDisplayNameCheck();
			}
			displayName_check_timer = setTimeout('fieldsetBlock.doDisplayNameCheck()', 1000);
		} else {
			displayName_available = true;
		}
	},
	
	stopDisplayNameCheck: function() {
		clearTimeout(displayName_check_timer);
		displayName_check_timer = null;
	},
	
	doDisplayNameCheck: function() {
		if($('account_display_name').value != '') {
			$('display_name_container').show();
			$('account_display_name_error').hide();
			$('account_display_name_check').innerHTML = '<img src="/z/images/indicator_small.gif" alt="" /> Checking display name...';
			Element.show('account_display_name_check');
			displayName_check_timer = null;
			
			var siteBuildingParams = $H({ method:'get_display_name', id:0, params:{ display_name:$('account_display_name').value } }).toJSON();
			new Ajax.Updater(	'', 
								'/proxy.cfm?service=site_building', 
								{	asynchronous:true,
									evalScripts: true,
									parameters:'request='+encodeURIComponent(siteBuildingParams),
									onSuccess:function(r) {
										var response = r.responseText.evalJSON(true);
										if(response.error.size()) {
											// if there were any errors, show them hidden in the normal error message
											$('account_display_name_check').update('Error: '+response.error.flatten());
										} else {
											// if successful, show the text that was returned
											$('account_display_name_check').update(response.result);
										}
									},
									onFailure:function(e) {
										var response = e.responseText.evalJSON(true);
										$('account_display_name_check').update('Error: '+response.error.flatten());
									}
								}
							);
		} else {
			Element.hide('account_display_name_check');
		}
	},
	
	checkSite: function() {
		var address = $F('site_info_address');
		
		if(address != '') {
			// first check that the address doesn't contain any invalid characters
			if(address.match(/^(\w|\d|_|-)+$/) != null) {
				removeError('site_info_address', {message:'This will be the URL to your website (PLUS subscribers can change this later).<br />No spaces are special characters are allowed.'});
				
				// now actually do the ajax call
				if(site_check_timer != null) {
					// Cancel previous timer and set a new one
					this.stopSiteCheck();
				}
				site_check_timer = setTimeout('fieldsetBlock.doSiteCheck()', 1000);
				
			} else {
				// input wasn't valid, show an error
				addError('site_info_address', { message:'Your site name can only contain letters, numbers, _underscores_ and -dashes-'});
			}
		} else {
			removeError('site_info_address', {message:'This will be the URL to your website  (PLUS subscribers can change this later).<br />No spaces are special characters are allowed.'});
		}
		
	},
	
	stopSiteCheck: function() {
		clearTimeout(site_check_timer);
		site_check_timer = null;
	},
	
	doSiteCheck: function() {
		if($('site_info_address').value != '') {
			$('site_name_container').show();
			$('site_info_address_error').hide();
			$('site_info_address_check').innerHTML = '<img src="/z/images/indicator_small.gif" alt="" /> Checking URL availability...';
			Element.show('site_info_address_check');
			site_check_timer = null;
			var siteBuildingParams = $H({ method:'get_sitename', id:0, params:{ sitename:escape($('site_info_address').value) } }).toJSON();
			new Ajax.Updater(	'', 
								'/proxy.cfm?service=site_building', 
								{	asynchronous:true,
									evalScripts: true,
									parameters:'request='+encodeURIComponent(siteBuildingParams),
									onSuccess:function(r) {
										var response = r.responseText.evalJSON(true);
										if(response.error.size()) {
											// if there were any errors, show them hidden in the normal error message
											$('site_info_address_check').update('Error: '+response.error.flatten());
										} else {
											// if successful, show the text that was returned
											$('site_info_address_check').update(response.result);
										}
									},
									onFailure:function(e) {
										var response = e.responseText.evalJSON(true);
										$('site_info_address_check').update('Error: '+response.error.flatten());
									}
								}
							);	
		} else {
			Element.hide('display_name_container');
		}
	},
	
	sportChange: function() {
		var temp = 1;
		/*
		var sport_id = $('sport_info_primary_sport').value;
		var networkz_select = $('sport_info_networkz');
		
		// hide the networkz box by default so if nothing shows it, it's gone
		Element.hide('sport_info_networkz_div');
		networkz_select.options.length = 0;
		
		// check to see if this sport has some networkz
		if(sports_with_networkz[sport_id] != undefined && sports_with_networkz[sport_id].length != 0) {
		
			// if so, create the basic 'select something' entries
			networkz_select.options[0] = new Option('No Affiliation', '', true, false);
			networkz_select.options[1] = new Option('', '', false, false);
			// now loop through the networkz and add an option for each
			for(var i=0;i<sports_with_networkz[sport_id].length;i++) {
				// set i+2 because there are already 2 options in the list (created above)
				networkz_select.options[i+2] = new Option(sports_with_networkz[sport_id][i].name, sports_with_networkz[sport_id][i].id, false, false);
			}
			Element.show('sport_info_networkz_div');
		}*/
	},
	
	showHideCreateAccount: function() {
		if ($('create_account_fields').style.display == 'none') {
			new Effect.BlindUp('forgot_password_fields');
  			new Effect.BlindDown('create_account_fields');
  			Element.hide('forgot_password_link');
  			$('do_not_have_account_link').innerHTML = 'Already have an eteamz account?';
  			
  			$('new_account').value = "true";
  			if($('account_display_name').value != '') {
  				this.checkDisplayName();		// run the username check if this person has already entered one
  			}

  		} else {
  			new Effect.BlindUp('create_account_fields');
  			Element.show('forgot_password_link');
  			$('do_not_have_account_link').innerHTML = 'Don\'t have an eteamz account?';

  			Element.hide('account_display_name_check');	  	// hide the username check since they're not creating a new user now
  			$('new_account').value = "false";
	  	}
	},
	
	forgotPassword: function() {

		window.open('/admin/forgot.cfm','forgot','menubar,scrollbars,resizable,width=470,height=400');

/*
		if($('forgot_password_email').value != '') {
			new Ajax.Updater(	'', 
								'/proxy.cfm?service=build_site&method=forgot_password&email='+$('forgot_password_email').value, 
								{ 	asynchronous:true,
									evalScripts:true
								});
		} else {
			alert('We\'ll need your email address before we can send your password!');
		}
*/
	},

	showHideForgotPassword: function() {

		window.open('/admin/forgot.cfm','forgot','menubar,scrollbars,resizable,width=470,height=400');

/*
		if ($('forgot_password_fields').style.display == 'none') {
  			new Effect.BlindDown('forgot_password_fields');
  		} else {
  			new Effect.BlindUp('forgot_password_fields');
	  	}
*/
	},
	
	updateSiteAddress: function() {
		var regEx = /\W+/g;
		var value = $('site_info_name').value;
		var converted_site_name = value.replace(regEx,'');
		$('site_info_name_error').hide();
		if(!manuallyTypedInSiteAddress) {
			$('site_info_address').value = converted_site_name;
			// go and run the normal ajax call
			this.checkSite();
		}
	},
	
	submitCreateAccount: function() {
		this.showHideCreateAccount();
		new Effect.ScrollTo('account_login');
	},
	
	showHideSiteTypeDescription: function() {
		if($('site_type_description').style.display == 'none') {
			Element.show('site_type_description');
		} else {
			Element.hide('site_type_description');
		}
	},
	
	showHideNetworkzDescription: function() {
		Element.toggle('sport_info_networkz_description_div');
	},
	
	showHideAdOption: function() {
		var radioGroup = document.build_site_form.service;
		
		if (radioGroup[1].checked) {
			$('ad_option_none').disabled = true;
			$('ad_option_monthly').disabled = true;
			$('ad_option_none').checked = true;
		} else if (radioGroup[0].checked) {
			$('ad_option_none').disabled = false;
			$('ad_option_monthly').disabled = false;
		}
		
		this.selectFeatureAdOption();
	},
	
	showHidePlusOptions: function() {
		var radioGroup = document.build_site_form.service;
		if(radioGroup[1].checked) {
			Element.hide('plus_options');
		} else if(radioGroup[0].checked) {
			Element.show('plus_options');
		}
	},
	
	showHideAdOptionOptions: function() {
		var radioGroup = document.build_site_form.ad_option;
		
		if(radioGroup[0].checked) {
			Element.show('ad_option_options');
			this.updateAdPrice();
		}
	
	},
	
	showHideDiskSpaceOptions: function() {
		var radioGroup = document.build_site_form.disk_space;
		
		if(radioGroup[1].checked) {
			Element.hide('disk_space_options');
		} else if(radioGroup[0].checked) {
			Element.show('disk_space_options');
		}
	
		this.showHideDiskSpaceDescription();
	},
	
	updatePlusPrice: function() {
		var site_type = this.figureSiteType();
		var service_type = this.figureServiceType();
		var billing_period = $('service_option').value;
		var price = prices[2][site_type+'_'+billing_period];
		service_total = 0;
		
		$('plus_price').innerHTML = '$' + price.toFixed(2) + '/' + billing_period;
		
		if(service_type == 'plus') {
			service_total = prices[2][site_type+'_'+billing_period];
		}
		
		this.updateAdPrice();
		this.updateTotal();
	},
	
	updateDiskSpacePrice: function() {
		var cost = 0;
		var radioGroup = document.build_site_form.disk_space;
		var site_type = this.figureSiteType();
		var billing_period = $('disk_space_option').value;
		var price = prices[3][site_type+'_'+billing_period];
		disk_space_total = 0;
		
		cost = price.toFixed(2) * parseInt($('disk_space_qty').value);
		$('disk_space_price').innerHTML = '$' + cost.toFixed(2) + '/' + billing_period;
		
		if(radioGroup[0].checked) {
			disk_space_total = cost;
		}
		
		this.updateTotal();
	},
	
	updateDiskSpaceDescription: function() {
		var qty = parseInt($('disk_space_qty').value);
		var total_megs = 20 * qty;
		var image_range = 50 * qty + '-' + 100 * qty;
		
		$('disk_space_description_div').innerHTML = total_megs + ' megabytes will hold approximately ' + image_range + ' photos (depending on size)';
	},
	
	updateDiskSpaceQty: function() {
		var radioGroup = document.build_site_form.disk_space;
		radioGroup[1].checked = false;
		radioGroup[0].checked = true;
		fieldsetBlock.selectFeatureDiskSpace();
	},
	
	updateDefaultDiskSpaceAmount: function() {
		var site_type = this.figureSiteType();
		var service_type = this.figureServiceType();
		
		$('default_disk_space_amount').innerHTML = default_disk_space[site_type+'_'+service_type];
	},
	
	updateAdPrice: function() {
		var radioGroup = document.build_site_form.ad_option;
		var site_type = this.figureSiteType();
		var billing_period = $('ad_option_option').value;
		var price = prices[4][site_type+'_'+billing_period];
		ad_option_total = 0;
		
		$('ad_option_price').innerHTML = '$' + price.toFixed(2) + '/' + billing_period;
		
		if(radioGroup[0].checked) {
			ad_option_total = price;
		}
		
		this.updateTotal();
	},
	
	changeSiteType: function() {
		var temp = 1 ;

		//var type = this.figureSiteType();
		
		/* don't show alert
		if (type != '') {
			alert("You have selected to build a " + type.toUpperCase() + " site. Please be sure this is correct because you cannot change it once your site is built. If you're not sure, click the 'What\'s the difference betweent the site types?' link.");
		}
		

		if (type != '') {
			$('site_type_warning_name').update(type.toUpperCase());
			$('site_type_warning').show();
		}
		
		this.updateDefaultDiskSpaceAmount();
		this.showHideLeagueInfo();
		this.updatePrices();
		*/
	},
	
	figureSiteType: function() {
		var type = '';
		switch ($('site_type').selectedIndex) {
			case '0' : type = 'team'; break;
			case '1' : type = 'league'; break;
			case '2' : type = 'org'; break;
		}
			
		/*		
		var radioGroup = document.build_site_form.site_type;
		var type = '';
		
		if (radioGroup[0].checked) {
			type = "team";
		} else if (radioGroup[1].checked) {
			type = "league";		
		} else if (radioGroup[2].checked) {
			type = "org";
		}
		*/
		return type;
	},
	
	figureServiceType: function() {
		alert(siteServiceOptionGet());
			
		var radioGroup = document.build_site_form.service;
		var type = '';
		
		if(radioGroup[1].checked) {
			type = 'free';
		} else if(radioGroup[0].checked) {
			type = 'plus';
		}
		
		return type;
	},
	
	showHideLeagueInfo: function() {
	
		type = this.figureSiteType();
		/*
		if(type == 'league' || type == 'org') {
			Element.show('league_info');
		} else {
			Element.hide('league_info');
		}*/
	},
	
	showHideDiskSpaceDescription: function() {
		var radioGroup = document.build_site_form.disk_space;
		
		if(radioGroup[1].checked) {
			Element.hide('disk_space_description');
		} else if(radioGroup[0].checked) {
			Element.show('disk_space_description');
		}
	},
	
	updateButton: function() {
		var radioGroup1 = document.build_site_form.service;
		var radioGroup2 = document.build_site_form.disk_space;
		var radioGroup3 = document.build_site_form.ad_option;
		
		if(radioGroup1[1].checked && radioGroup2[1].checked && radioGroup3[1].checked) {
			$('btn_create_my_site').show();
			$('btn_payment_options').hide();
			// $('commit').value = "Create My Site";
		} else {
			$('btn_create_my_site').hide();
			$('btn_payment_options').show();
			// $('commit').value = "Next: Payment Options";
		}
	},
	
	updatePrices: function() {
		this.updatePlusPrice();
		this.updateDiskSpacePrice();
		this.updateAdPrice();
	},
	
	updateTotal: function() {

		var total_price = service_total + disk_space_total + ad_option_total;
		
		if(total_price == 0) {
			total_price = '';
		} else {
			total_price = '$' + total_price.toFixed(2);
		}
		
		$('total_price').innerHTML = total_price;
		this.updateButton();
	},
	
	changeFeeType: function() {
		var radioGroup = document.build_site_form.league_info_signup_fee;
		
		if(radioGroup[0].checked) {
			Element.show('league_info_signup_fee_individual_div');
			Element.hide('league_info_signup_fee_team_div');
		} else if(radioGroup[1].checked) {
			Element.hide('league_info_signup_fee_individual_div');
			Element.show('league_info_signup_fee_team_div');
		} else if(radioGroup[2].checked) {
			Element.show('league_info_signup_fee_individual_div');
			Element.show('league_info_signup_fee_team_div');
		} else if(radioGroup[3].checked) {
			Element.hide('league_info_signup_fee_individual_div');
			Element.hide('league_info_signup_fee_team_div');
		}
	},
	
	checkBirthday: function() {
		var birth_year = $('account_birthday_year').value;
		var birth_month = $('account_birthday_month').value;
		var birth_day = $('account_birthday_day').value;
		var coppa_year = coppa_date.getFullYear();
		var coppa_month = coppa_date.getMonth() + 1;
		var coppa_day = coppa_date.getDate();
		
		// first check to make sure something was selected for all three date parts
		if (birth_year != '' && birth_month != '' && birth_day != '') {
			if (birth_year > coppa_year) {
				younger_than_13 = true;						// year check
			} else if (birth_year == coppa_year) {
				if (birth_month > coppa_month) {
					younger_than_13 = true;					// month check
				} else if (birth_month == coppa_month) {
					if(birth_day > coppa_day) {
						younger_than_13 = true;				// day check
					} else {
						younger_than_13 = false;			// day check
					}
				} else {
					younger_than_13 = false;				// month check
				}
			} else {
				younger_than_13 = false;					// year check
			}
		}
		
		// so show or hide the rest of the form based on person's age
		if(younger_than_13) {
			Element.hide('non_account_info');
			Element.show('coppa_notice');
		} else {
			Element.show('non_account_info');
			Element.hide('coppa_notice');
		}
	},
	
	selectFeatureService: function() {
		create_a_site_init();
		/*
		var radioGroup = document.build_site_form.service;
		
		if(radioGroup[1].checked) {
			// free service selected
			$('service_free_row').className = 'highlight';
			$('service_pay_row').className = '';
		} else if(radioGroup[0].checked) {
			// pay service selected
			$('service_free_row').className = '';
			$('service_pay_row').className = 'highlight';
		}
				
		this.updateDefaultDiskSpaceAmount();
		this.showHidePlusOptions();
		this.showHideAdOption(); 
		this.updatePlusPrice();
		*/
		// this.showHideTemplateChoose();

	},
	
	selectFeatureDiskSpace: function() {
		var radioGroup = document.build_site_form.disk_space;
		
		if(radioGroup[1].checked) {
			$('service_disk_space_free_row').className = 'highlight';
			$('service_disk_space_pay_row').className = '';
		} else if(radioGroup[0].checked) {
			$('service_disk_space_free_row').className = '';
			$('service_disk_space_pay_row').className = 'highlight';
		}
		
		this.showHideDiskSpaceDescription();
		this.showHideDiskSpaceOptions();
		this.updateDiskSpaceDescription();
		this.updateDiskSpacePrice(); 
	},
	
	selectFeatureChangeDiskSpaceQty: function() {
		this.updateDiskSpaceQty(); 
	},
	
	selectFeatureAdOption: function() {
		var radioGroup = document.build_site_form.ad_option;
		
		if(radioGroup[1].checked) {
			$('service_ad_option_free_row').className = 'highlight';
			$('service_ad_option_pay_row').className = '';
		} else if(radioGroup[0].checked) {
			$('service_ad_option_free_row').className = '';
			$('service_ad_option_pay_row').className = 'highlight';
		}
		
		this.showHideAdOptionOptions(); 
		this.updateAdPrice();
	},
	
	showHideFundraising: function() {
		if($('fundraising_info')) {
			if($('account_fundraising').checked) {
				$('fundraising_info').show();
			} else {
				$('fundraising_info').hide();
			}
		}
	},
	
	showHideTemplateChoose: function() {
		var radioGroup = document.build_site_form.service;
		
		if(radioGroup[1].checked) {
			// free service selected
			$('template_choose').hide();
		} else if(radioGroup[0].checked) {
			// pay service selected
			$('template_choose').show();
		}
	},
	
	templateOnClick: function(id) {

		var clickedTemplate = $('template_'+id);
		var currentlyChosenTemplate = $F('template');
	
		// deselect any selected template
		if($('template_'+currentlyChosenTemplate)) {
			$('template_'+currentlyChosenTemplate).className = 'site_template';
		}
		
		// select this template
		clickedTemplate.className = 'site_template_selected';
		
		// remove mouseover and mouseout functions
		$('template').value = id;
	},
	
	templateMouseOver: function(id) {
		// only update if this isn't the selected template already
		if($F('template') != id) {
			$('template_'+id).className='site_template_over';
		}
	},
	
	templateMouseOut: function(id) {
		// only update if this isn't the selected template already
		if($F('template') != id) {
			$('template_'+id).className='site_template';
		}
	}
}
