
// this will replace pageLoad() function
Ext.onReady(function(){

	// create the magic number
	Ext.get('signupMagicNumber').set({value: (Math.floor(Math.random()*1001)) });
	Ext.get('slrextras').setStyle('display','none');
});

function showSLRExtras()
{
	Ext.get('slrextras').setStyle('display','block');
	
} 

function signupProcess() {
 	Ext.get('signupSubmit').dom.disabled = true;
 	  
	var rg_alpha = /\s*[a-zA-Z]+\s*$/;
	var rg_alphanum = /\s*\w+\s*$/;
	var rg_alphanum_special = /\s*[\w.\-,]+\s*$/;
	var rg_phone = /\s*[\d+.\-\s()\[\]]+\s*$/;
	var rg_email = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
	var rg_email_bris = /^.+@(|my\.)bris(\.|tol\.)ac\.uk$/;
	var rg_email_uwe = /^.+@live\.uwe\.ac\.uk$/;
  
	ty = Ext.get('signupSelectType').getValue();         
            
    el = Ext.get('signupFirstname');
    fn = el.getValue()
    if( !rg_alpha.test( el.getValue() ) ) {
        showErrorElement( el );
        Ext.Msg.alert('Error', 'Please check that your first name contains only letters.');
        Ext.get('signupSubmit').dom.disabled = false;
        return;
    }
    el.setStyle('background-color', 'white'); 
        
    el = Ext.get('signupLastname');
    ln = el.getValue()
    if( !rg_alpha.test( el.getValue() ) ) {
        showErrorElement( el );
        Ext.Msg.alert('Error', 'Please check that your last name contains only letters.');
        Ext.get('signupSubmit').dom.disabled = false;
        return;
    }
    el.setStyle('background-color', 'white'); 
    
    el = Ext.get('signupEmail');
    em = el.getValue()
    if( !rg_email.test( el.getValue() ) ) {
        showErrorElement( el );
        Ext.Msg.alert('Error', 'Please check that your email is valid.');
        Ext.get('signupSubmit').dom.disabled = false;
        return;
    }
    el.setStyle('background-color', 'white'); 
    
    el = Ext.get('signupAddress1');
    a1 = el.getValue();
    if( !rg_alphanum_special.test( el.getValue() ) ) {
        showErrorElement( el );
        Ext.Msg.alert('Error', 'Please check that your address contains only letters, numbers, or (-,.) .');
        Ext.get('signupSubmit').dom.disabled = false;
        return;
    }
    el.setStyle('background-color', 'white'); 
    
    a2 = Ext.get('signupAddress2').getValue(); // should be optional
    
    el = Ext.get('signupPostcode');
    pc = el.getValue();
    if( !rg_alphanum_special.test( el.getValue() ) ) {
        showErrorElement( el );
        Ext.Msg.alert('Error', 'Please check that your post code contains only letters and numbers.');
        Ext.get('signupSubmit').dom.disabled = false;
        return;
    }
    el.setStyle('background-color', 'white'); 
    
    el = Ext.get('signupPhone');
    ph =  el.getValue();
    if( !rg_phone.test( el.getValue() ) ) {
        showErrorElement( el );
        Ext.Msg.alert('Error', 'Please check that your phone number is valid (numbers, brackets and + are accepted).');
        Ext.get('signupSubmit').dom.disabled = false;
        return;
    }
    el.setStyle('background-color', 'white'); 
    
    el = Ext.get('signupStudentid');
    sid =  el.getValue();
    if( !rg_alphanum.test( el.getValue() ) ) {
        showErrorElement( el );
        Ext.Msg.alert('Error', 'Please check that your studentid is valid (numbers and letters are accepted).');
        Ext.get('signupSubmit').dom.disabled = false;
        return;
    }
    el.setStyle('background-color', 'white'); 
    
    oc = Ext.get('signupOccupation').getValue();
    oc_other = Ext.get('signupOccupation_other').getValue();
    
    //ev = getCheckedRadioValue(Ext.get('signupOccupation').dom);
    /*if(  Ext.get('signupEventsy').dom.checked )
    	ev =  Ext.get('signupEventsy').getValue();
    else
    	ev =  Ext.get('signupEventsn').getValue();
    */
    
    slr = Ext.get('signupSlr').getValue();
	// concat types    
	slr_type = '';
    if( Ext.get('signupSlr_canon').dom.checked )
    	slr_type += Ext.get('signupSlr_canon').getValue() +';';
    if( Ext.get('signupSlr_nikon').dom.checked )
    	slr_type += Ext.get('signupSlr_nikon').getValue() +';';
    if( Ext.get('signupSlr_sony').dom.checked )
    	slr_type += Ext.get('signupSlr_sony').getValue() +';';
    if( Ext.get('signupSlr_pentax').dom.checked )
    	slr_type += Ext.get('signupSlr_pentax').getValue() +';';
    if( Ext.get('signupSlr_other').dom.checked )
    	slr_type += Ext.get('signupSlr_other').getValue() +';';

    slr_models = Ext.get('signupSlr_model').getValue()
    
    events = '';
	   
	if( Ext.get('signupEvents_music').dom.checked )
    	events += Ext.get('signupEvents_music').getValue() +';';
    if( Ext.get('signupEvents_plays').dom.checked )
    	events += Ext.get('signupEvents_plays').getValue() +';';
    if( Ext.get('signupEvents_arch').dom.checked )
    	events += Ext.get('signupEvents_arch').getValue() +';';
    if( Ext.get('signupEvents_sports').dom.checked )
    	events += Ext.get('signupEvents_sports').getValue() +';';
    if( Ext.get('signupEvents_portraits').dom.checked )
    	events += Ext.get('signupEvents_portraits').getValue() +';';
	if( Ext.get('signupEvents_fashion').dom.checked )
    	events += Ext.get('signupEvents_fashion').getValue() +';'; 
    		
    we = Ext.get('signupWebsite').getValue();
    flck = Ext.get('signupFlickrname').getValue();
    
    //signup_submit.disabled = true;
    //signup_cancel.disabled = true;
    isphoto = Ext.get('signupPhotoStatus').getValue();
	if( !isphoto ) {
        //showErrorElement( el );
        Ext.Msg.alert('Error', 'Please check that you have uploaded a photo of yourself.');
        Ext.get('signupSubmit').dom.disabled = false;
        return;
    }
	magicnumber = Ext.get('signupMagicNumber').getValue();
    //}
    
	
    //Ext.get('signup_form_container').setVisible( false ); // could animate :)
   
    //spinner
    startSpinner("signup","content_body");

    Ext.Ajax.request({
	   url: 'ajax.Backend.php',
	   params: { 'function': 'signUp',
	   			'firstname': fn,
                'lastname': ln,
                'email': em,
                'address1': a1,
                'address2': a2,
                'postcode': pc,
                'phone': ph,
                'website': we,
                'signuptype': ty,
                'flickrname': flck,
                'magic': magicnumber,
                'events': events,
                'slrs': slr,
                'slr_types': slr_type,
                'slr_models': slr_models,
                'occupation': oc,
                'occupation_other': oc_other,
                'studentid': sid 
	    },
	   success: function(transport, options) {
            stopSpinner("signup","content_body");
            
			Ext.get('signupSubmit').dom.disabled = false;
			
            var resp = new Response(transport, options);
            
            if( resp.success() ) 
            {          	
              	setTimeout('document.forms["paypal_form"].submit()',3000);
              	Ext.get('signup_form_container').dom.innerHTML = resp.getText();

            }else if( resp.warning() ) {
                t = resp.getText();
                retobj = resp.getReturnObject(); 
              
              	for( i=0; i < retobj.length; i++ ) {
	            	t+='\n* '+retobj[i]["error"];
					if( retobj[i]['formitem'] )
						showErrorElement( Ext.get('signup'+retobj[i]['name']) );
						//document.forms['signup_form'][retobj[i]['name']].style.backgroundColor = "red";
              	}

              	Ext.Msg.alert('Error', t);
            }
        },
	   failure:  function(){ 
	   		resp = new Response("", "function=signUp");
	   		
            stopSpinner("signup","content_body");
            resp.showError("Error: Our Server cannot be reached. Is server down? Please try again.");
            Ext.get('signupSubmit').dom.disabled = false;
       }	
	});

}

/*
Ext.onReady(function(){
    //hideSignupMessage();
    Ext.get("signup_result").hide();
    startSpinner("signup_types","signup_typetable");
    
    Ext.Ajax.request({
	   url: 'ajax.Backend.php',
	   params: { 'function': 'getMemberships' },
	   success: function(transport, options) {
            stopSpinner("signup_types","signup_typetable");
            var resp = new Response(transport, options);
            
            if( resp.success() ) 
            {
            	retobj = resp.getReturnObject(); 
                // create the Grid
                var grid = new Ext.grid.GridPanel({
                    store:  new Ext.data.JsonStore({
                            data: retobj, 
                    		fields: ['desc', 'filter', {name:'amount', type: 'float'}, 'typeid', 'student']
                	}),
                    columns: [
                        {id:'desc',header: "Description", width: 75, sortable: true, dataIndex: 'desc'},
                        {header: "Price", width: 75, sortable: true, renderer: 'ukMoney', dataIndex: 'amount'},
                        {header: "E-mail Filter", width: 150, sortable: false, dataIndex: 'filter'}
                    ],
                    sm: new Ext.grid.RowSelectionModel({singleSelect:true}),
                    enableHdMenu: false,
                    stripeRows: true,
                    autoExpandColumn: 'desc',
                    height:130,
                    width:400,
                    title:'Photosoc Signup Options'
                });
					grid.on('cellclick', function(grid, rowIndex, columnIndex, e) { 
						var record = grid.getStore().getAt(rowIndex);  
                       	signupChooseType( record.typeid, record.student );
					}, this, {});

                grid.render('signup_typetable');
            } else {
                resp.showError(resp.getText());
            }
        },
	   failure:  function(){ 
	   		resp = new Response("", "function=getMemberships");
            stopSpinner("signup_types","signup_typetable");
            resp.showError("Error: Our Server cannot be reached. Is server down? Please try again.") 
            }	
	});

});

function signupChooseType(type, student) {
    document.getElementById("signup_typetable").style.display = "none";
    document.getElementById("signup_form_container").style.display="block";
    if( student == 0 ) {
       document.getElementById("studentid_field").style.display="none";
       document.forms["signup_form"]["studentid"].value ="ext";
    }
    document.forms["signup_form"]["signup_type"].value = type;
}

function signupCancel() {
    document.getElementById("signup_typetable").style.display = "block";
    document.getElementById("signup_form_container").style.display="none";
    document.forms["signup_form"]["signup_type"].value = "";
	hideSignupMessage();
}

function signupProcess() {
    signup_type = document.forms["signup_form"]["signup_type"].value;
    
    // check form is filled out 
    o = document.forms["signup_form"];
    with (o) {
        
        var rg_alpha = /\s*[a-zA-Z]+\s*$/;
        var rg_alphanum = /\s*\w+\s*$/;
        var rg_alphanum_special = /\s*[\w.\-,]+\s*$/;
        var rg_phone = /\s*[\d+.\-\s()\[\]]+\s*$/;
        var rg_email = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
        var rg_email_bris = /^.+@(|my\.)bris(\.|tol\.)ac\.uk$/;
        var rg_email_uwe = /^.+@uwe\.ac\.uk$/;
        
        
        fn = firstname.value;
        if( !rg_alpha.test(fn) ) {
            showErrorElement(firstname);
            Ext.Msg.alert('Error', 'Please check that your first name contains only letters.");
            return;
        }
        firstname.style.backgroundColor = "white";
        
        ln = lastname.value;
        if( !rg_alpha.test(ln) ) {
            showErrorElement(lastname);
            Ext.Msg.alert('Error', 'Please check that your last name contains only letters.");
            return;
        }
        lastname.style.backgroundColor = "white";
        
        em = email.value;
        if( !rg_email.test(em) ) {
            showErrorElement(email);
            Ext.Msg.alert('Error', 'Please check that your email is valid.");
            return;
        }
        email.style.backgroundColor = "white";
        
        a1 = address1.value;
        if( !rg_alphanum_special.test(a1) ) {
            showErrorElement(address1);
            Ext.Msg.alert('Error', 'Please check that your address contains only letters, numbers, or (-,.) .");
            return;
        }
        address1.style.backgroundColor = "white";
        
        a2 = address2.value; // should be optional
        
        pc = postcode.value;
        if( !rg_alphanum_special.test(pc) ) {
            showErrorElement(postcode);
            Ext.Msg.alert('Error', 'Please check that your post code contains only letters and numbers.");
            return;
        }
        postcode.style.backgroundColor = "white";
        
        ph = phone.value;
        if( !rg_phone.test(ph) ) {
            showErrorElement(phone);
            Ext.Msg.alert('Error', 'Please check that your phone number is valid (numbers, brackets and + are accepted).");
            return;
        }
        phone.style.backgroundColor = "white";
        
        sid = studentid.value;
        if( !rg_alphanum.test(sid) ) {
            showErrorElement(studentid);
            Ext.Msg.alert('Error', 'Please check that your studentid is valid (numbers and letters are accepted).");
            return;
        }
        studentid.style.backgroundColor = "white";
        
        oc = occupation.value;
        oc_other = occupation_other.value;  
        
        ev = getCheckedRadioValue(events);    
        
        we = website.value;
        he = heard.value;
        ty = signup_type.value;
        flck = flickrname.value;
        
        //signup_submit.disabled = true;
        //signup_cancel.disabled = true;
        isphoto = signup_photoupload_status.value;
		if( !isphoto ) {
            jumptoErrorElement(photouploadframe);
            Ext.Msg.alert('Error', 'Please check that you have uploaded a photo of yourself.");
            return;
        }
		magicnumber = signup_magic_number.value;
    }

    hideSignupForm();
    
    //spinner
    startSpinner("signup","content_body");

    Ext.Ajax.request({
	   url: 'ajax.Backend.php',
	   params: { 'function': "function=signUp&firstname': fn +
                "&lastname': ln +
                "&email': em +
                "&address1': a1 +
                "&address2': a2 +
                "&postcode': pc +
                "&phone': ph +
                "&website': we +
                "&heard': he + 
                "&signuptype': ty +
                "&flickrname': flck +
                "&magic': magicnumber +
                "&events': ev +
                "&occupation': oc +
                "&occupation_other': oc_other +
                "&studentid': sid 
	    },
	   success: function(transport, options) {
            stopSpinner("signup","content_body");

            var resp = new Response(transport, options);
            
            if( resp.success() ) 
            {
            	retobj = resp.getReturnObject(); 
              setTimeout('document.forms["paypal_form"].submit()',3000);
              response = document.createElement("div");		
              a = document.getElementById("signup_result");
              if( a.firstChild )
                  a.removeChild( a.firstChild );
              response.innerHTML = resp.getText();
              a.appendChild(response);
					a.style.display="block";
            } else {
	              showSignupForm();
	              t = resp.getText();
	              retobj = resp.getReturnObject(); 
	              
	              for( i=0; i < retobj.length; i++ ) {
		              t+='\n* '+retobj[i]["error"];
						  if( retobj[i]["formitem"] )
								document.forms["signup_form"][retobj[i]["name"]].style.backgroundColor = "red";

	              }
	              // stuff
	
	              showSignupMessage(t);
            }
        },
	   failure:  function(){ 
	   		resp = new Response("", "function=signUp");
            stopSpinner("signup","content_body");
            resp.showError("Error: Our Server cannot be reached. Is server down? Please try again.");
            showSignupForm();
            }	
	});

}

function showErrorElement(e) {
    e.style.backgroundColor = "red";  
	jumptoErrorElement(e) ;
}

function jumptoErrorElement(e) {
    // *******************************************
}
    
function hideSignupForm() {
    document.forms["signup_form"]["signup_submit"].disabled = 1;
    document.getElementById("signup_form_container").style.display="none";
}
function showSignupForm() {
    document.forms["signup_form"]["signup_submit"].disabled = 0; 
    document.getElementById("signup_form_container").style.display="block";
}
 
function hideSignupMessage() {
	r = document.getElementById("signup_result");
	r.style.display="none";
}
	
function showSignupMessage(x) {
    r = document.getElementById("signup_result");
	r.style.display="block";
    if(r.firstChild)
        r.removeChild(r.firstChild);
    r.appendChild( document.createTextNode( x ) );
}
*/
/*
function pageLoad()
{
	// set magic number 
	//var rn=Math.floor(Math.random()*1001);
	//document.forms["signup_form"]["signup_magic_number"].value = rn;
	
	hideSignupMessage();
    startSpinner("signup_types","signup_typetable");
    //document.getElementById("signupform").style.display="none";
    new Ajax.Request('ajax.Backend.php', {
        method: 'post',
        parameters: "function=getMemberships",
        onComplete: function() {},
        onSuccess: function(transport) {
            stopSpinner("signup_types","signup_typetable");
            resp = eval( '(' + transport.responseText + ')');
            if( resp.code != -1 ) {
                retobj = eval( '(' + resp.json + ')' );
                // for each returned result
                response = document.createElement("div");		
    
                rule = {"self":'<table class="bookingtable" id="signup_table"><tr class="header"><td>Signup Type</td><td>Price (Pounds)</td><td>Valid email domains</td></tr>{$}</table>', 
                    "self[*]": '<tr>' +
                    '<td class="session" onclick="signups.choosetype({$.typeid},{$.student})">{$.desc}</td>' +
                    '<td>{$.amount}</td>' +
                    '<td>{$.filter}</td>' +
                    '</tr>'};
                
                response.innerHTML = jsonT(retobj, rule);
                document.getElementById("signup_typetable").appendChild(response);
            } else {
                alert(resp.text);
            }
        },
        onFailure: function(){ 
            stopSpinner("signup_types","signup_typetable");
            alert("Error: Our Server cannot be reached. Is server down? Please try again.") 
            }	
        }	
    );    
    
}
*/

