/////////////////////////////////////////////////////////////////////////////
//
// Gladiator Components 
//
// http://www.gladiatorweb.com
//
// (c) 2006 by Edward H. Trager .  All Rights Reserved
//
// NAME: gladiatorSVGLoginWidget.js
//
// AUTHOR: Edward H. Trager
//
// LAST UPDATE: 2007.01.03
//
// NOTE: SEE "LICENSE" FILE FOR LICENSING TERMS
//
//////////////////////////////////////////////////////////////////////////////

//
// 
//
var GLADIATOR_SVG_LOGIN_INCLUDED=true;
if(typeof GLADIATOR_CORE_INCLUDED == 'undefined') alert('NOTA BENE: "gladiatorSVGLoginComponent.js" REQUIRES "gladiatorCore.js"!');
// DISABLE CHECKING FOR SVG -- THIS IS AN IE WORK-AROUND:
//if(typeof GLADIATOR_SVG_INCLUDED == 'undefined') alert('NOTA BENE: "gladiatorSVGLoginComponent.js" REQUIRES "gladiatorSVG.js"!');
if(typeof GLADIATOR_REQUEST_INCLUDED == 'undefined') alert('NOTA BENE: "gladiatorSVGLoginComponent.js" REQUIRES "gladiatorRequest.js"!');
if(typeof GLADIATOR_INDICATOR_INCLUDED == 'undefined') alert('NOTA BENE: "gladiatorSVGLoginComponent.js" REQUIRES "gladiatorWaitIndicator.js"!');

//
// URL: URL which performs authentication.
//      The SVGLoginComponent uses AJAX to POST the username (un) and  
//      password (pw) variables to the server.  The returned XML data should
//      look like this:
//
//        <feed>
//          <r>RETURN_DATA</r>
//        </feed>
//
//      ... where RETURN_DATA is normally the user's name or username which
//      can be used to format a "Welcome" message.
//      
//      In case there is no match, an empty XML feed is returned:
//
//        <feed></feed>
//
// In addition, you can optionally pass the following parameters:
//
// loginOKMethod     -- A function to be called when the login succeeds.
// 
// loginFailedMethod -- A function to be called when a login fails.
//
// registerMethod    -- A function to be called so new users can register.
//                      If registerMethod is not null (or false), then a "Register" button
//                      appears on the component.
//
// parentNode        -- An optional parent node to which the LoginComponent canvas is attached.
//                      By default, the LoginComponent canvas becomes a child of the document body.
//
function gSVGLoginComponent(URL,loginOKMethod,loginFailedMethod,registerMethod,parentNode){
	
	// Explicitly  initialize the window dimesions for browsers like Opera:
	DIMENSIONS.init();
	var _self = this;
	
	//
	// Optional handler methods:
	//
	var _loginOKMethod = false;
	if(loginOKMethod) _loginOKMethod = loginOKMethod;
	
	var _loginFailedMethod = false;
	if(loginFailedMethod) _loginFailedMethod = loginFailedMethod;
	
	var _registerMethod = false;
	if(registerMethod) _registerMethod = registerMethod;
	
	//
	// CREATE THE LOGIN WIDGET CANVAS:
	//
	var _canvas = document.createElementNS(NS.xhtml,"div");
	_canvas.setAttribute("class","gSVGLoginWidget");
	_canvas.id="loginCanvas";
	// Add a tooltip
	_canvas.title="Click on the login component to cancel.";
	
	var _width  = 206;
	var _height = 206;
	var _padding= 12;
	
	//
	// POSITION is a global convenience enumeration object in gladiatorCore.js:
	//
	var _horizontalPosition=POSITION.center;
	var _verticalPosition  =POSITION.center;
	
	//
	// ADD SVG:
	//
	var _svg = new gSVG();
	_svg.drawHeader(_width,_height);
	_svg.addContent('<radialGradient id="gradient1" gradientUnits="userSpaceOnUse" cx="103" cy="103" r="100" fx="100" fy="100">');
	_svg.addContent(' <stop offset="75%" stop-color="#ddd" />');
	_svg.addContent(' <stop offset="100%" stop-color="#000" />');
	_svg.addContent('</radialGradient>');
	_svg.addContent('<circle fill="url(#gradient1)" class="loginDisc" cx="103" cy="103" r="100" />');
	_svg.addContent('<circle id="loginDisc" class="loginDiscNeutral" cx="103" cy="103" r="100" tooltip="Click on disc to cancel" />');
	_svg.addContent('<g id="loginForm">');
	_svg.addContent(' <rect class="inputPlatter" id="usernamePlatter" width="161" height="31" rx="15.5" ry="15.5" x="22.5" y="49.362183" />');
	_svg.addContent(' <rect class="inputPlatter" id="passwordPlatter" width="161" height="31" rx="15.5" ry="15.5" x="22.5" y="110.86218" />');
	_svg.addContent(' <text class="loginLabels" text-anchor="middle" x="103" y="39.362183">Username:</text>');
	_svg.addContent(' <text class="loginLabels" text-anchor="middle" x="103" y="101.36218">Password:</text>');
	
	if(_registerMethod){
		_svg.addContent('<g id="registerGroup">');
		_svg.addContent(' <rect class="loginButton" x="56.1759" y="150.42409" width="93.84350" height="24.876196" rx="15.5" ry="15.5" />');
		_svg.addContent(' <text id="registerButton" class="buttonLabels" text-anchor="middle" x="103" y="168.1698">Register</text>');
		_svg.addContent('</g>');
	}
	_svg.addContent('</g>');
	_svg.addContent('<g id="loginWelcome">');
	_svg.addContent(' <text class="welcomeLabels" text-anchor="middle" x="103" y="85.00">Welcome</text>');
	_svg.addContent(' <text id="loginWelcomeName" class="welcomeLabels" text-anchor="middle" x="103" y="116.00">user!</text>');
	_svg.addContent('</g>');
	_svg.drawFooter();
	_svg.render(_canvas);
	
	
	//
	// Now add input boxes:
	//
	var _userName = document.createElementNS(NS.xhtml,"input");
	_userName.id="loginId";
	_userName.name=_userName.id;
	_userName.setAttribute("class","loginUserName");
	_canvas.appendChild(_userName);
	
	var _password = document.createElementNS(NS.xhtml,"input");
	_password.id="loginPassword";
	_password.name=_password.id;
	_password.setAttribute("class","loginPassword");
	_password.setAttribute("type","password");
	_canvas.appendChild(_password);
	
	
	//
	// set position based on DIMENSIONS:
	//
	_canvas.style.width  = _width  + "px";
	_canvas.style.height = _height + "px";
	//
	// Place in center:
	//
	_position();
	
	//
	// add to DOM:
	//
	if(parentNode){
		parentNode.appendChild(_canvas);
	}else{
		var bodyRef = document.getElementsByTagName("body").item(0);
		bodyRef.appendChild(_canvas);
	}
	
	//////////////////////////////////////////////////////
	//
	// POPULATE METHOD
	//
	//////////////////////////////////////////////////////
	function _populatePage(request){
		
		var userDataRows = request.responseXML.documentElement.getElementsByTagName('r');
		var disc = document.getElementById("loginDisc");
		if(userDataRows.length){
			//
			// Login succeeded:
			//
			disc.setAttribute("class","loginDiscPass");
			//
			// Hide input boxes, show welcome message:
			//
			_userName.style.display="none";
			_password.style.display="none";
			document.getElementById("loginForm").style.display="none";
			document.getElementById("loginWelcomeName").firstChild.nodeValue=userDataRows[0].firstChild.nodeValue+"!";
			document.getElementById("loginWelcome").style.display="block";
			
			//
			// call optional handler:
			//
			if(_loginOKMethod) _loginOKMethod(userDataRows[0].firstChild.nodeValue);
			
			//
			// Make the login component disappear:
			//
			fadeOut("loginCanvas",1.0);
			_show=false;
			
		}else{
			//
			// Login failed:
			//
			disc.setAttribute("class","loginDiscFail");
			
			//
			// Clear entries for next round:
			//
			//_userName.value="";
			_password.value="";
			_userName.focus();
			
			//
			// call optional handler:
			//
			if(_loginFailedMethod) _loginFailedMethod();
			
		}
		
	}
	
	//
	// Wait indicator and gRequest objects:
	//
	
	//
	//var _waitIndicator = new gWaitIndicator();
	//
	var _waitIndicator = false;
	
	//var _request       = new gRequest(URL,_populatePage,"post",_waitIndicator);
	//
	var _request       = new gRequest(URL,_populatePage,"post");
	
	////////////////////
	//
	// PRIVATE METHODS
	//
	////////////////////
	
	//
	// position()
	//
	function _position(){
		if( _horizontalPosition > 0 ){
			//
			// If the horizontal pos. is greater than 
			// zero (POSITION.center==0), then
			// interpret as a fixed position:
			//
			_canvas.style.left = _horizontalPosition + "px";
		}else{
			//
			// Treat as a symbolic position:
			//
			switch(_horizontalPosition){
			case POSITION.center:
				_canvas.style.left = DIMENSIONS.horizontalCenter - 0.5*_width + "px";
				break;
			case POSITION.left:
				_canvas.style.left = _padding + "px";
				break;
			case POSITION.right:
				_canvas.style.left = DIMENSIONS.width - _padding - _width + "px";
				break;
			}
		}
		if( _verticalPosition > 0 ){
			//
			// If the vertical pos. is greater than 
			// zero (POSITION.center==0), then
			// interpret as a fixed position:
			//
			_canvas.style.top = _verticalPosition + "px";
		}else{
			//
			// Treat as a symbolic position:
			//
			switch(_verticalPosition){
			case POSITION.center:
				_canvas.style.top  = DIMENSIONS.verticalCenter   - 0.5*_height + "px";
				break;
			case POSITION.top:
				_canvas.style.top  = _padding + "px";
				break;
			case POSITION.bottom:
				_canvas.style.top  = DIMENSIONS.height - _padding - _height + "px";
				break;
			}
		}
	}
	
	//
	// handleKeyEvents
	//
	function _handleKeyEvents(e){
		
		switch(e.keyCode){
		case KB.enter:
		case KB.tab:
			//
			// Set up query string:
			//
			var qstring="un="+_userName.value+"&pw="+_password.value;
			_request.setQueryTermsString(qstring);
			_request.load();
			break;
			
		case KB.escape:
			break;
			
		case KB.left:
			break;
			
		case KB.right:
			break;
			
		case KB.down:
			break;
			
		case KB.up:
			break;
			
		default:
			//alert(e.keyCode);
			break;
		}
		
	}
	
	//
	// _cancel()
	//
	function _cancel(){
		//
		// Make the login component disappear:
		//
		//fadeOut("loginCanvas",1.0);
		_self.show(false);
		
	}
	
	
	////////////////////
	//
	// PUBLIC METHODS
	//
	////////////////////
	
	var _show;
	//
	// show:
	//
	this.show = function(showIt){
		// No state change?
		if(showIt == _show) return;
		// Get here if state change:
		_show=showIt;
		if(_show){
			_canvas.style.display="block";
			_canvas.style.opacity=1;
		}else{
			_canvas.style.display="none";
		}
	}
	
	//
	// setPosition():
	// 
	// => If horizontal and vertical are symbolic constants
	//    from the POSITION enumeration object, then the relative position
	//    is set, possibly using _padding.
	// => Otherwise, if horizontal and vertical are numerals greater than
	//    zero ( POSITION.center == 0 ), then the position is set to a fixed
	//    position in pixels.
	//
	this.setPosition = function(horizontal,vertical){
		// Set the symbolic positioning:
		_horizontalPosition = horizontal;
		_verticalPosition   = vertical;
		// Make it take effect:
		_position();
		//
		// Make the wait indicator have the same position:
		//
		if(_waitIndicator) _waitIndicator.setPosition(horizontal,vertical);
	}
	
	//
	// Initially show in view:
	//
	_self.show(true);
	
	//
	//
	//
	this.reset = function(){
		
		document.getElementById("loginDisc").setAttribute("class","loginDiscNeutral");
		_userName.value="";
		_password.value="";
		_userName.style.display="block";
		_password.style.display="block";
		document.getElementById("loginForm").style.display="block";
		document.getElementById("loginWelcomeName").firstChild.nodeValue="";
		document.getElementById("loginWelcome").style.display="none";
		_self.show(true);
		_userName.focus();
		
	}
	
	///////////////////
	//
	// EVENT HANDLERS:
	//
	///////////////////
	
	//
	// reposition the indicator whenver the window is resized:
	//
	window.addEventListener("resize",_position,false);
	
	_password.addEventListener("keypress",_handleKeyEvents,false);
	
	// Cancel by clicking on the disc itself:
	document.getElementById("loginDisc").addEventListener("click",_cancel,false);
	
	if(_registerMethod) document.getElementById("registerGroup").addEventListener("click",_registerMethod,false);
	
}

