var formObj = null;

var fObj = new Class({
	initialize: function(){
		// BBCheck
		if( $('bbcheck_submit') ){
			$('checkResult').innerHTML = "<strong>Please enter your BT telephone number above and click check</strong>";
			$('bbcheck_submit').addEvent('click', function(e){
				this.bbcheck();
			}.bind(this));
			
			// Run account checking...
			//this.accountcheck();
			
			this.disabled = $$('.startDisabled input').concat($$('.startDisabled select'));
			this.disabled.each( function(obj, n){
				obj.setProperty('disabled','disabled');
			});
			this.hidden = $$('.startHidden');
			this.hidden.each( function(obj, n){
				obj.setStyle('display','none');
			});
		}
		
		this.cancel = $$('.cancel');
		this.cancel.each(function(obj,n){
			obj.addEvent('click',function(e){
				if(confirm('Are you sure?'))
					window.location='.';
			});
		}.bind(this));
		
		// Required fields
		this.form = $$('form');
		
		this.form.each(function(obj, n){
			obj.addEvent('submit', function(e){
				var required = obj.getElements('.required input').concat(obj.getElements('.required select'));
				var shownAlert = 0;
				required.each(function(rob,rn){
					if(!rob.value && !shownAlert){
						shownAlert = 1;
						alert('Please fill in all required fields');
						e.preventDefault();
					}
				});
			});
		}.bind(this));
		
		var ddConf = $$('#ddConfirm .confirm');
		if(ddConf){
			$$('#ddConfirm .ddconfchk').addEvent('click',function(e){
				ddConf.removeProperty('disabled');
			});
		}
	},
	
	bbcheck: function(){
		var bbcheck = $$('.bbcheck_tel');
		
		$('checkResult').innerHTML = "Checking...";
		//$('checkResult').innerHTML = "Calculating infinity...";
		$('bbChecking').setStyle('display','block');
		checkRequest = new Request({
			method: 'get',
			url: '/ajax.php?broadband_check=' + $('inBTPhone').getProperty('value') + '&product=' + $('seFormProduct').options[$('seFormProduct').selectedIndex].value + '&' +(Math.random()*100),
			onComplete: function( response ){
				$('bbChecking').setStyle('display','none');
				response = JSON.decode( response );
				if(response.msg){
					$('checkResult').innerHTML = response.msg;
					if( response.canhas ){
						this.disabled.each( function( obj, n ){
							obj.removeProperty('disabled');
						});
						this.hidden.each( function( obj, n ){
							obj.setStyle('display', 'block');
						});
					}
				}
			}.bind(this)
		}).send();
	},
	
	// Check account
	accountcheck: function(){
		var acHas = $('account_has');
		
		$$('.accountCheck').setStyle('display','none');
		$$('.nonAccount').setStyle('display','none');
		
		acHas.addEvent('change',function(e){
			if(acHas.value.contains('Yes')){
				$$('.nonAccount').setStyle('display','none');
				$$('.accountCheck').setStyle('display','block');
			}else{
				$$('.accountCheck').setStyle('display','none');
				$$('.nonAccount').setStyle('display','block');
			}
		});
	}
});

window.addEvent('domready',function(){
	formObj = new fObj();
});

