function buildForm(targetDiv,params){
	var returning_billing_account_id= '';
	var user_name = params['user_name'];
	//defaults
	Ext.QuickTips.init();
	Ext.QuickTips.enable();	
	Ext.apply(Ext.QuickTips.getQuickTip(), 
	    {
	        showDelay: 0
	    }
	);
	Ext.form.Field.prototype.msgTarget = 'side';
	Ext.form.Field.prototype.labelSeparator = '';
	Ext.form.Field.prototype.labelAlign= 'top';
	//Ext.Ajax.timeout = 300000;
	Ext.Ajax.extraParams = {
		DEPLOYMENT_TYPE: params['DEPLOYMENT_TYPE']
	}

	Ext.override(Ext.layout.FormLayout, {
	    renderItem : function(c, position, target){
	        if(c && !c.rendered && c.isFormField && c.inputType != 'hidden'){
	            var args = [
	                   c.id, c.fieldLabel,
	                   c.labelStyle||this.labelStyle||'',
	                   this.elementStyle||'',
	                   typeof c.labelSeparator == 'undefined' ? this.labelSeparator : c.labelSeparator,
	                   (c.itemCls||this.container.itemCls||'') + (c.hideLabel ? ' x-hide-label' : ''),
	                   c.clearCls || 'x-form-clear-left' 
	            ];
	            if(typeof position == 'number'){
	                position = target.dom.childNodes[position] || null;
	            }
	            if(position){
	                c.formItem = this.fieldTpl.insertBefore(position, args, true);
	            }else{
	                c.formItem = this.fieldTpl.append(target, args, true);
	            }
	
	//          Remove the form layout wrapper on Field destroy.
	            c.on('destroy', c.formItem.remove, c.formItem, {single: true});
	            c.on('hide', c.formItem.hide, c.formItem, {single: false});
	            c.on('show', c.formItem.show, c.formItem, {single: false});
	            c.render('x-form-el-'+c.id);
	        }else {
	            Ext.layout.FormLayout.superclass.renderItem.apply(this, arguments);
	        }
	    }
	});
	
	
	
	Ext.apply(Ext.form.VTypes, {
		password : function(val, field) {
	        if (field.initialPassField) {
	            var pwd = Ext.getCmp(field.initialPassField);
	            return (val == pwd.getValue());
	        }
	        return true;
	    }
		,passwordText : 'Passwords do not match'
	});
	

	if (LibsynIndie.signup_debug_mode) console.log('in fxn');
	
	var mode = params['mode'];
	
	function newUser(){
		Ext.getCmp('signup_notice').show();
		Ext.getCmp('use_existing_billing_account').show();
		
	}
	
	function inactiveUser(){	
		main_form.getForm().load({
			url:'/ajax/accountInfo/user_id/' + params['user_id']
			,success:function(a,b){
				//debugger;
				var service_level = b.result.data.service_level;
				returning_billing_account_id =  b.result.data.billing_account_id;
				Ext.getCmp('service_level_'+service_level).setValue(true);
				if (b.result.data.paid_dns){
					Ext.getCmp('paid_dns').hide();
					Ext.getCmp('paid_dns').setValue(0);
				}
				if (service_level == "101"	){
				//	Ext.getCmp('paid_stats').show();
				}
				if (service_level == "102"){
					Ext.getCmp('libsyn50').hide();
					Ext.getCmp('libsyn100').show();
				}
				Ext.getCmp('service_level_'+service_level).setValue(true);	
			}
		});
			
		Ext.getCmp('user_name').disable();
		Ext.getCmp('password').disable();
		Ext.getCmp('confirm').disable();
		Ext.getCmp('password').hide();
		Ext.getCmp('confirm').hide();
		Ext.getCmp('overdue_notice').show();
		
		Ext.getCmp('human_validation').hide();
		//main_form.getForm().setValues(params['account_json']);
	}
	
	function upgradeUser(){
		main_form.getForm().load({
			url:'/ajax/accountInfo/user_id/' + params['user_id']
			,success:function(a,b){
				
				var service_level = b.result.data.service_level;
				returning_billing_account_id =  b.result.data.billing_account_id;
				Ext.getCmp('service_level_'+service_level).setValue(true);
				if (b.result.data.paid_dns){
					Ext.getCmp('paid_dns').hide();
					Ext.getCmp('paid_dns').setValue(0);
				}
				
				if (service_level == "101"){
					//console.log('need to display stats upgrade');
					//Ext.getCmp('paid_stats').show(true);
					//Ext.getCmp('paid_stats').setVisible(true);
				}
				if (service_level == "102"){
					Ext.getCmp('libsyn50').hide();
					Ext.getCmp('libsyn100').show();
				}
			}
		});
		Ext.getCmp('account_details').hide();
		Ext.getCmp('user_name').disable();
		Ext.getCmp('password').disable();
		Ext.getCmp('confirm').disable();
		Ext.getCmp('password').hide();
		Ext.getCmp('confirm').hide();
		Ext.getCmp('email').disable();
		Ext.getCmp('upgrade_notice').show();
		
		Ext.getCmp('human_validation').hide();
	
		//main_form.getForm().setValues(params['account_json']);
	}
	
	function transferUser(){
		
		main_form.getForm().load({
			url:'/ajax/accountInfo/user_id/' + params['user_id']
			,waitMsg:'Retrieving current account data...'
			,success:function(a,b){
				//debugger;
				var service_level = b.result.data.service_level;
				returning_billing_account_id =  b.result.data.billing_account_id;
				if (service_level == 1){
					Ext.getCmp('libsyn50').hide();
					Ext.getCmp('libsyn100').show();
				} else if (service_level == 8){
					Ext.getCmp('libsyn50').hide();
					Ext.getCmp('libsyn3000').show();
				}
				var new_service_level;
				switch(service_level){
					case "1":
					new_service_level = 102;
					break;
					case "2":
					new_service_level = 103;
					break;
					case "3":
					new_service_level = 104;
					break;
					case "4":
					new_service_level = 105;
					break;
					case "5":
					new_service_level = 106;
					break;
					case "8":
					new_service_level = 107;
					break;
				}
				if (new_service_level){
					var radio= Ext.getCmp('service_level_'+new_service_level);
					Ext.getCmp('service_level_'+new_service_level).setValue(true);
					//debugger;
				}
				if (b.result.data.paid_dns){
					Ext.getCmp('paid_dns').hide();
					Ext.getCmp('paid_dns').setValue(0);
				}
				/*
				if (service_level == 1){
					Ext.getCmp('paid_stats').show();
				}
				*/
			}
		});
		
		
		//Ext.getCmp('account_details').hide();
		Ext.getCmp('user_name').disable();
		Ext.getCmp('password').disable();
		Ext.getCmp('confirm').disable();
		Ext.getCmp('password').hide();
		Ext.getCmp('confirm').hide();
		Ext.getCmp('email').disable();
		Ext.getCmp('transfer_notice').show();
		
		Ext.getCmp('human_validation').hide();
		Ext.getCmp('use_existing_billing_account').show();
		//main_form.getForm().setValues(params['account_json']);
	}
	
	
	
	
	function submitForm(){
		if (main_form.getForm().isValid()){
			//productize the selection
			
			var service_level = Ext.getCmp('service_level_103').getGroupValue();
			var products = new Array();
			
			switch(service_level){
				case "101":
				products.push(2);
				break;
				case "102":
				products.push(3);
				break;
				case "103":
				products.push(4);
				break;
				case "104":
				products.push(5);
				break;
				case "105":
				products.push(6);
				break;
				case "106":
				products.push(7);
				break;
				case "107":
				products.push(8);
				break;
			}
			if (Ext.getCmp('paid_dns').getValue()){
				products.push(10);
			}
			if (Ext.getCmp('paid_stats').getValue()){
				products.push(9);
			}
			//debugger;
			if(mode =="signup"){
				main_form.getForm().submit({
				    url:'recaptcha_check.php'
				    ,success:function(){
						softSubmit(products)
					}
					,failure:function(a,b){
						if (b.result){
							Recaptcha.reload();
							Recaptcha.focus_response_field();
							Ext.getCmp('recaptcha_fail').show();
						} else {
							window.scroll(0,0);
						}
					}
				})
			} else {
				softSubmit(products)
			}
		} else { //form is not valid
			window.scroll(0,0);
		}
		
	}
	function softSubmit(products){
		main_form.getForm().timeout = 300;
		if (Ext.getCmp('billing_account_id').getValue()==""){
			Ext.getCmp('billing_account_id').setValue(returning_billing_account_id)
		}
		main_form.getForm().submit({
			url:'/ajax/purchase'
			,waitTitle:'Saving Changes'
			,waitMsg:'Please be patient while we process your account.  This could take several minutes...'
			,params:{
				products:products
				,email:Ext.getCmp('email').getValue()
				,billing_account_id:returning_billing_account_id
			}
			,success:function(f,a){
				//debugger;
				hardSubmit(a.result.data);
			}
			,failure:function(f,a){				
				Recaptcha.reload();
				Recaptcha.focus_response_field();
				Ext.Msg.alert('Error',a.result.data.msg);
			}
		});
	}
	
	function hardSubmit(data){
		var myMask = new Ext.LoadMask(Ext.getBody(), {msg:"Please wait..."});
		myMask.show();
		Ext.getCmp('proceed_button').hide();
		var formHTML = '<form name="hardform" method="POST" action="'+data.billing_url+'">';
		for (var i in data){
			if (typeof data[i] == "object"){
				formHTML += '<input type="hidden" name="'+i+'" value=\''+Ext.util.JSON.encode(data[i])+'\'>';
			} else {
				formHTML += '<input type="hidden" name="'+i+'" value="'+data[i]+'">';
			}
		}
		formHTML += '</form>';
		/*
		'<input type="hidden" name="billing_account_id" value="'+data.billing_account_id+'"'+
		'<input type="hidden" name="purchase_data" value=\''+Ext.util.JSON.encode(data.products)+'\'</form';
		*/
		Ext.get(targetDiv).insertHtml('afterEnd',formHTML);
		//debugger;
		document.hardform.submit();
		
	}
	
	function validateUsername(field){
		if (field.getValue()){
			Ext.Ajax.request({
				url:'/ajax/checkUsername/user_name/'
				,params:{
					user_name:field.getValue()
				}
				,success: function(transport) {
					
		             var jason = Ext.util.JSON.decode(transport.responseText);
		            
		             if (jason.success == false){
		             	Ext.getCmp('user_name').markInvalid(jason.data.msg);
		             	 //debugger;
		             	//field.markInvalid('This username is not available');	             	
		             }
				 }
			})
		}
	}

	var main_form = new Ext.form.FormPanel({
		id:'main_form_panel'
		,width:705
		,title:' '
		,border:true
		,style:'text-align:left;margin:auto;'
		,bodyStyle:'padding:10px;'
		,autoHeight:true
		,layout:'form'
		,labelAlign:'top'
		,items:[
			{
				id:'signup_notice'
				,border:false
				,style:'padding-bottom:10px;'
				,hidden:true
				,html:'<h1 style="margin-left:5px;margin-right:5px;padding:3px;background:#ddd;color:black">Signup for Liberated Syndication</h1> ' +
						'<div style="margin:5px;">'+
						'Once you complete the following form you will be prompted for payment information. All major credit cards and PayPal are accepted to establish your account.  ' +
						'Your account will be charged on the 1st of every month.</div>' 
			},{
				id:'transfer_notice'
				,border:false
				,style:'padding-bottom:10px;'
				,hidden:true
				,html:'<h1 style="margin-left:5px;margin-right:5px;padding:3px;background:#555;color:white">Transferring billing account for '+ user_name+'</h1> ' +
						'<div style="margin:5px;"> Please <a href="/account/transfer.php?status=inactive">click here for explanation</a> of new billing policy.</div>'+
						'<div style="margin:5px;">Accounts are now charged on the 1st of the every month in advance of the month to follow.  Your first payment will include any pro-' +
						'rated amount for the remainder of the current month based on your previous billing period.</div>' +
						'<div style="margin:5px;">Your old PayPal recurring payment will be cancelled once you complete this process. ' +
						'<b>You will get a notice from PayPal that your libsyn subscription has been cancelled.</b> This is your old account payment, and it is to be expected.</div>' +
						'<div style="margin:5px;">During this transfer, the $5.00 change of service fee will be waived, however after this process, any downgrades are subject to the service fee.</div>' +
						'<div style="margin:5px;">If at any point you are having problems, or do not receieve the cancellation notice from PayPal in a few days, please contact <a href="support@libsyn.com">support@libsyn.com</a> for assistance.</div>'
			},{
				id:'overdue_notice'
				,border:false
				,style:'padding-bottom:10px;'
				,hidden:true
				,html:'<h1 style="margin-left:5px;margin-right:5px;padding:3px;background:red;color:white">Your libsyn account '+ user_name+' is inactive</h1> ' +
						'<div style="margin:5px;"><b>If you are a new user</b>, you are seeing this page because we have not yet received payment for ' +
						'your account. If you believe you have already made a payment, please note that while the ' +
						'processing of payments normally takes a few seconds, it could take up to 24 hours for your payment ' +
						'to be cleared and your account to be activated.' +
						'<br />If you have not yet made a payment, please complete the form below and make a payment for your ' +
						'account using Paypal or our secure online credit card processor. If you are having problems ' +
						'with Paypal or need other assistance, please contact <a href="support@libsyn.com">support@libsyn.com</a>.</div>' +
						'<div style="margin:5px;"><b>If you are a veteran user</b>, you are seeing this page because ' +
						'a) You failed to make a payment and your account was automatically put on hold, or ' +
						'b) your account has been deactivated by LibSyn Support for some other reason. ' +
						'Please use the form below to re-activate your account, or contact <a href="support@libsyn.com">support@libsyn.com</a> for assistance.</div>'
			}
			,{
				id:'upgrade_notice'
				,border:false
				,style:'padding-bottom:10px;'
				,hidden:true
				,html:'<h1 style="margin-left:5px;margin-right:5px;padding:3px;background:orange;color:white">Upgrading your libsyn account: '+ user_name +'</h1> ' +
						'<div style="margin:5px;"><b>If you are upgrading</b>, once you successfully complete the payment process your account will ' +
						'immediately be upgraded to the larger storage quota. You will be charged the pro-rated difference between your old account level ' +
						'and the new account level.' +
						'<div style="margin-top:5px;"><b>If you are downgrading</b>, you still need to authorize the payment change and your account quota will immediately be downgraded to the new size.' +
						'You will receive a credit for the pro-rated difference between the old account level and the new level minus a $5.00 service charge.' +
						'<br /><br />Please use the form below to change your account, or contact <a href="support@libsyn.com">support@libsyn.com</a> for assistance.</div>'
			}
			,{
				xtype:'fieldset'
				,autoHeight:true
				,id:'account_details'
				,title:'Account Details'
				,layout:'column'
				,items:[
					{
						columnWidth:.5
						,layout:'form'
						,labelAlign:'top'
						,border:false
						,items:[
							{
								xtype:'textfield'
				        		,fieldLabel:'Email'
				        		,name:'email'
				        		,id:'email'
				        		,width:200
				        		,allowBlank:false
				        		,vtype:'email'
							}
						]
					}
					,{
						columnWidth:.5
						,layout:'form'
						,labelAlign:'top'
						,border:false
						,items:[
							{
								layout:'column'
								,border:false
								,items:[
									{
										layout:'form'
										,border:false
										,items:[
											{
												xtype:'textfield'
									    		,fieldLabel:'Username'
									    		,name:'user_name'
									    		,id:'user_name'
									    		,width:150
									    		,msgTarget:'qtip'
									    		,plugins:[Ext.ux.plugins.RemoteValidator]
												,rvOptions: {
													url:'/ajax/checkUsername/user_name/'
													
												}
									    		,allowBlank:false	
									    		,listeners: {
									    			blur:function(field){
									    				//validateUsername(field);
									    			}
									    		}
											}
										]
									}
									,{
										html:'.libsyn.com'
										,border:false
										,style:'padding-left:5px;margin-top:25px;'
									}
								]
							}
						]
					}
					,{
						columnWidth:1
						,layout:'column'
						,border:false
						,items:[
							{
								columnWidth:.5
								,layout:'form'
								,labelAlign:'top'
								,border:false
								,items:[
									{
										xtype:'textfield'
						        		,fieldLabel:'Password'
						        		,name:'password'
						        		,id:'password'
						        		,visibilityMode :Ext.Element.DISPLAY
						        		,inputType:'password'
						        		,width:100
						        		,allowBlank:false
									}
								]
							}
							,{
								columnWidth:.5
								,layout:'form'
								,labelAlign:'top'
								,border:false
								,items:[
									{
										xtype:'textfield'
						        		,fieldLabel:'Confirm Password'
						        		,name:'confirm'
						        		,id:'confirm'
						        		,inputType:'password'
						        		,vtype: 'password'
						        		,visibilityMode :Ext.Element.DISPLAY
        								,initialPassField: 'password' 
						        		,width:100
						        		,allowBlank:false
									}
								]
							}
							,{
								columnWidth:1
								,layout:'form'
								,border:false
								,items:[
									{
									 	xtype:'checkbox'
									 	,id:'use_existing_billing_account'
									 	,name:'use_existing_billing_account'
									 	,hideLabel:true
										,boxLabel:'Consolidate the charges for this account with an exisiting billing account.'
										,listeners:{
											check:function(f,check){
												
												if (check) {
													Ext.getCmp('billing_account_block').show();
													Ext.getCmp('billing_account_id').enable();
													Ext.getCmp('billing_account_email').setValue(Ext.getCmp('email').getValue());
													Ext.getCmp('billing_account_id').allowBlank = false;
													Ext.getCmp('billing_account_email').allowBlank = false;
												} else {
													Ext.getCmp('billing_account_block').hide();
													Ext.getCmp('billing_account_id').disable();
													Ext.getCmp('billing_account_id').allowBlank = true;
													Ext.getCmp('billing_account_email').allowBlank = true;
												}
											}
										}
									 }
									 ,{
										 border:false
										,style:'padding-left:16px;border-left:1px solid #999;margin-left:4px;font-size:12px;'
										,width:650
										,hidden:true
										,id:'billing_account_block'
										,layout:'column'
										,items:[
											{
												layout:'form'
												,width: 309
												,border:false
												,items:[
													{
														xtype:'textfield'
											    		,fieldLabel:'Billing Account Email'
											    		,name:'billing_account_email'
											    		,id:'billing_account_email'					    		
											    		,width:200
													}
												]
											}
											,{
												layout:'form'
												,width: 300
												,border:false
												,items:[
													{
														xtype:'textfield'
														,columnWidth:.5
											    		,fieldLabel:'Billing Account ID'
											    		,name:'billing_account_id'
											    		,id:'billing_account_id'
											    		,disabled:true
											    		,width:200
											    		,emptyText:'k-xxxxxxxxxxxxx'
													}
												]
											}
											,{
												columnWidth:1
												,border:false
												,width:600
												,html:'<b>This option is only avaialble if you already have an updated libsyn billing account.</b><br />The billing account ID and the email address of the billing account (where you get invoices emailed to) needs to match exactly.'+
												'Your billing account ID can be found on your invoice or through the Account tab when logged into libsyn.com.  '
													
											}
										]
									 }
								]
							}
							,{
								xtype:'hidden'
								,name:'user_id'
								,id:'user_id'
							}
							
						]
					}
				]	
			}
			
			,service_selection
			,addition_options
			//,billing_fields
			,{
				xtype:'fieldset'
				,autoHeight:true
				,id:'human_validation'
				,title:'Human Validation'
				,items:[
					 {
				 		xtype: 'recaptcha'
	                    ,name: 'recaptcha'
	                    ,id: 'recaptcha'
	                    ,publickey: '6Lf5KgYAAAAAABN66HqRTTZxdA7RicvYEBcGBc1p'
	                    ,theme: 'white'
	                    ,lang: 'en'
	                }
	                ,{
	                	id:'recaptcha_fail'
	                	,xtype:'label'
	                	,hidden:true
	                	,cls:'x-form-invalid-msg'
	                	,text:'Human validation failed. Please try again.'
	                }
				]
			}
			,{
				xtype:'checkboxgroup'
				,msgTarget:'under'
            	,blankText:'You really should read the end user agreement!'
				,allowBlank:false
				,items:[
					{
						id:'read_eua'
						,name:'read_eua'
						,hideLabel:true
						,boxLabel:'I have read and fully understand the <a href="/legal.php" onclick="window.open(\'/legal.php\',\'_blank\');">END USER AGREEMENT</a> and agree to all of its terms and conditions.'					
						/*
						,listeners: {
							render: function(c){
								var label = c.getEl().up('.x-form-item').child('.x-form-cb-label');
								label.dom.htmlFor = '';
								var a = label.child('a');
								a.on('click', function(){
									 window.open('/legal.php','_blank');
								}, c, {stopEvent: true});		
							}
						}
						*/
					}
				]
			}
		]
		,buttonAlign:'center'
		,buttons:[
			{
				xtype:'button'
				,formBind: true
				,text:'Proceed to payment'
				,id:'proceed_button'
				,handler:function(){
					submitForm();
				}
			}
		]	
	});
	
	if (LibsynIndie.signup_debug_mode) console.log('about to render');
	Ext.get(targetDiv).update('');
	main_form.render(targetDiv);
	Ext.getCmp('paid_stats').hide();
	
	if (mode=="inactive"){
		inactiveUser();
	} else if (mode=="upgrade"){
		upgradeUser();
	} else if (mode=="transfer"){
		transferUser();
	} else if (mode == "signup"){
		newUser();
	}
	//allow libsyn3000 override
	if (params['ENABLE3000']){
		Ext.getCmp('libsyn50').hide();
		Ext.getCmp('libsyn3000').show();
	}
}
