Auth = {
	
	working : false,
	step : 0,
	
	logout: function(){
		if( Auth.working ) return;
		
		Auth.working = true;
		Auth.step = 0;
		
		new Ajax('/auth/sec.auth.php?action=logout', {
			method: 'post',
			onComplete: function(txt){
				if( Auth.step == 0 ){
					Auth.step = 1;
					Auth.working = false;
					My.showauth();
				}
			}
		}).request();
	},

	attemptLogin: function(){
		if( Auth.working ) return;
		
		Auth.working = true;
		Auth.step = 0;
		$('login_status').setText("Connecting...");
		
		var req1 = new Ajax('/auth/sec.auth.php?action=handshake', {
			method: 'post',
			onComplete: function(key){
				if( Auth.step == 0 ){
					Auth.step = 1;
					$('login_status').setText("Sending...");
					
					var value = 'u='+ $('myname').value +'&p='+ $('mypass').value;
					var crypt = Auth.jsc002E(key, value);
					
					//console.log( "key:"+ key);
					//console.log( "value:"+ value);
					//console.log( "crypt:"+ crypt );
					
					var req2 = new Ajax('/auth/sec.auth.php?c='+crypt, {
						method: 'post',
						onComplete: function(txt){
							if( Auth.step == 1 ){
								Auth.step = 2;
								
								var msg = "Granted";
								var ok = (txt=='TRUE') ? true : false;
								if( !ok ) msg = "Denied";

								$('login_status').setText(msg);
								
								if( ok ){
									if(typeof(Menu)!='undefined') Menu.menu_loadLevel3(MenuChapter, '11' );
									if(typeof(Login)!='undefined') Login.success();
									
									// open the inspector:
									console.log( "open the inspector:" );
									//(function(){ Auth.openPanel(); }).delay(1200);
									My.panel_open();
									
								}else{
									if(typeof(Login)!='undefined') Login.failure();
								}
								
								if(typeof(My)!='undefined') My.showauth();
								Auth.working = false;
								
								// test
								//console.log( typeof(Login) );
								//if(typeof(Login)!='undefined') Login.success();
							}
						}
					}).request();
				}
			}
		}).request();
		
	},

	jsc002E: function(k,v){
		var i,f=v.length,a=[],j=0,c=k.length,b=false;for(i=0;i<f;i++){a[i]=v.charCodeAt(i).toString(16);}v=a.join('');i=0;a=[];if(c>v.length)c=v.length;while(i<c){a[j]=(b)?v.charAt(i):k.charAt(i);if(b){i++};b=!b;j++;}return a.join('')+v.substr(i);
	},
	
	openPanel: function(){
		console.log( "openPanel:" );
		console.log( $("panelbtn") );
		if( $("panelbtn") ){
			console.log( "found - clicking..." );
			$("panelbtn").fireEvent("click");
			My.panel_open();
		}
	}
	
};
