function UNDEF(a){ return 'undefined' == typeof(a); }
var tv_login = {};
var tv_util_login = {};
var zz,XX,XXX;

var TWINEDU=/twinedu/.test(document.location);
var TWINNAME = 'Twinverse';
var LOGO = "logo.png";
var SLOGAN = "ourplanet.png";


if(TWINEDU){
	TWINNAME = "Twinedu";
	document.title = "Twinedu - Schools of our planet";
	LOGO = "logo-twinedu.png";
	SLOGAN = "schools.png";
} else {
	TWINNAME = 'Twinverse';
	document.title = "Twinverse - Our planet is a virtual world";
	LOGO = "logo.png";
	SLOGAN = "ourplanet.png";
}


tv_util_login.init = function(){

	if(TWINEDU){
		//setCookie(TWINEDU_COOKIE_KEY,"edu",null,'/','.twinverse.com');
		COOKIE_2_TWINEDU();
	}
	//else {
	//	setCookie(TWINEDU_COOKIE_KEY,"twi",null,'/','.twinverse.com');
	//}
	
	var ua = navigator.userAgent.toLowerCase();
    var t = function(r) { return r.test(ua); };
	tv_util_login.isiPhone = Ext.isSafari && t(/iphone/);

	
	tv_util_login.loopProgress = function(startindex, startmsg, finalmsg){
		var chain = null;
		tv_util_login.progress.updateProgress(startindex,startmsg);
		var animlist = []; 
		for(var i=1; i < 20; i+=1){
			animlist.push({
				nb:i,
				action:function(){ tv_util_login.progress.updateProgress(startindex+(1.0-startindex)*this.nb/20.0);},
				stopAction:function(){},
				delay:1000.0
			});
		}
		animlist.push({
			action:function(){
				tv_util_login.progress.updateProgress(startindex,finalmsg);
				chain = new Tv_chainedAnimation(animlist);
				chain.start();
			},
			stopAction:function(){
				chain.abort();
			},
			delay:25000.0
		});
		chain = new Tv_chainedAnimation(animlist);
		chain.start();
		return chain
	}
}

tv_login.init = function(){





	tv_login.lostpassword = function(){
		var email = tv_login.logInTwinverseFP.getForm().findField('email');
		//var password = login.loginFormPanel.getForm().findField('password');
		email = email.getValue();
		if ( !email ){
			Ext.Msg.alert('','You must provide a valid email address')
			return
		}
		Ext.Msg.confirm("Password Lost",
			"A new password will be sent to "+email,
			function(btn){
				if(btn!='yes'){return}
			    tv_util_login.progress = Ext.Msg.progress("Sending password to "+email,
					    "Please wait",
					    "Checking account"
					    );
			window.setTimeout(function(){tv_util_login.progress.updateProgress(0.5)},500);
			window.setTimeout(function(){tv_util_login.progress.updateProgress(0.75)},2500);
			if(TWINEDU){setCookie(TWINEDU_COOKIE_KEY,"edu",null,'/','.twinverse.com');
			} else { setCookie(TWINEDU_COOKIE_KEY,"twi",null,'/','.twinverse.com'); }

			if(!UNDEF(tv_login.request)){Ext.Ajax.abort(tv_login.request);}
			tv_login.request = Ext.Ajax.request({
				url:"http://beta.twinverse.com/mail_passw",
				scriptTag: true,
				//callbackParam: 'callback',
				//timeout:5,
				method:'GET',
				params: {email:email, twinedu:TWINEDU},
				success: function(response){
					tv_login.ZZZ = response;
					response = response.responseText;
					response = Ext.decode(response);
					if(!response.success){
						Ext.Msg.alert("Failure",response.data.msg);
						return
					}
					var result = response.data;
					Ext.Msg.alert('',
						'A new password have been generated<br/>Check your mailbox for your new password');
				},
				failure: function(failed){
					tv_login.ZZ = failed;
					tv_util_login.progress.hide();
					Ext.Msg.alert('Failure',"Server not available");
				}
			})
				// send email address
				// if email invalid message failed
				// else check your inbox for your new passw
			});
	}


	tv_login.logInTwinverseHandler = function(){
		var form = tv_login.logInTwinverseFP.getForm(); 
	    if(!form.isValid()){return}
	    tv_util_login.progress = Ext.Msg.progress("Connecting...",
					    "Please wait while connecting to "+TWINNAME,
					    "Authentication requested"
					    );
	    var params = form.getValues();
		if (TWINEDU){params.twinedu = true}		
	    var url = "/login/";
		if(TWINEDU){setCookie(TWINEDU_COOKIE_KEY,"edu",null,'/','.twinverse.com');
		} else { setCookie(TWINEDU_COOKIE_KEY,"twi",null,'/','.twinverse.com'); }
	    if(!UNDEF(tv_login.request)){Ext.Ajax.abort(tv_login.request);}
	    tv_login.request = Ext.Ajax.request({
			url:url,
			//scriptTag: true,
			//callbackParam: 'callback',
			//timeout:5,
			method:'GET',
			params: params,
			success: function(response){
				tv_login.ZZZ = response;
				response = response.responseText;
				response = Ext.decode(response);
				if(!response.success){
					Ext.Msg.alert("Authentication Failed",response.data.msg);
					return
				}
				tv_util_login.progress.updateProgress(0.5,"Authentication OK");
				
				var result = response.data;

				window.location = result.redirect_url;
				tv_util_login.loopProgress(0.5,"Connecting to "+TWINNAME, "Still Connecting - Please Wait");
			},
			failure: function(failed){
				tv_login.ZZ = failed;
				tv_util_login.progress.hide();
				Ext.Msg.alert('Authentication failed',"Server not available");
			}
	    });	    
			
	}
	
    tv_login.logInTwinverseFP = new Ext.FormPanel({
        frame:false,
        border:false,
        bodyStyle:'padding:10px 15px 20px',
        //autoHeight:true
		//height:250,
        defaults: {width: 230},
		height:200,
        defaultType: 'textfield',
        labelAlign: 'top',
        items: [{
                fieldLabel: 'email',
                name: 'email',
                allowBlank:false
            },{
                fieldLabel: 'password',
		inputType:'password',
                name: 'password'
            },
			{xtype:"label",html:"<br/>"
            },{xtype:"label",
			html:"<div align='right'><a href='#' onclick='"+'javascript:tv_login.lostpassword();'+"'>forgot password ?</a></div>"}
			],
		keys: [{
			key: Ext.EventObject.ENTER,
			fn: tv_login.logInTwinverseHandler
		}],
        //buttons: [{ text: 'Enter Decatur', handler:function(){
        buttons: [{ text: 'Enter '+TWINNAME, handler:tv_login.logInTwinverseHandler}]
    });

	
	tv_login.logInTwitterHandler = function(){
		//Ext.Msg.alert("Log in using twitter account", "Not activated yet");

		var form = tv_login.logInTwitterFP.getForm();
		var params = form.getValues();
		if(!params.screen_name || !params.twitter_passw){ Ext.Msg.alert('', 'Both field are mandatory'); return}
	    tv_util_login.progress = Ext.Msg.progress("Connecting...",
					    "Please wait while connecting to twitter",
					    "Authentication requested"
					    );

		if(tv_login.request){Ext.Ajax.abort(tv_login.request); tv_login.request = null}
		if(TWINEDU){setCookie(TWINEDU_COOKIE_KEY,"edu",null,'/','.twinverse.com');
		} else { setCookie(TWINEDU_COOKIE_KEY,"twi",null,'/','.twinverse.com'); }
		tv_login.request = Ext.Ajax.request({
			//url:'http://localhost:10001/register/',
			url:'http://twitterapi.twinverse.com/register/',
			scriptTag: true,
			callbackParam: 'callback',
			method:'GET',
			params:params,
			success: function(response){
				response = Ext.decode(response.responseText);
				if (!response || UNDEF(response.data)){ Ext.Msg.alert('Unexpected Error !','Please report the bug to bugs@twinverse.com');	return; }
				if(!response.success){	Ext.Msg.alert("Failure",response.data.msg); return;	}
				response = response.data;
				
				window.location = 'http://dispatch2.twinverse.com/';
				tv_util_login.loopProgress(0.5,"Connecting to "+TWINNAME, "Still Connecting - Please Wait");
			},
			failure: function(failed){
				Ext.Msg.alert('Failure',"Twitter servers are unavailable");
				tv_login.XX = failed;
			}
		});				
	}

    tv_login.logInTwitterFP = new Ext.FormPanel({
        frame:false,
        border:false,
        bodyStyle:'padding:10px 15px 20px',
        //autoHeight:true,
		//height:250,
        defaults: {width: 230},
        defaultType: 'textfield',
        labelAlign: 'top',
        items: [{
                fieldLabel: 'screen name',
                name: 'screen_name',
                allowBlank:false
            },{
                fieldLabel: 'password',
                name: 'twitter_passw'
            }],
		keys: [{
			key: Ext.EventObject.ENTER,  
			fn: tv_login.logInTwitterHandler
		}],
        buttons: [{ text: 'Enter '+TWINNAME, handler:tv_login.logInTwitterHandler }]
    });


	var tabs = [{
	    title:TWINNAME,
	    layout:'fit',
	    frame:true,
	    border:false,
	    items:tv_login.logInTwinverseFP
	}];
	if(!TWINEDU){
		tabs[1]={
			title:'Twitter',
			disabled:true,
			layout:'fit',
			frame:true,
			border:false,
			items:tv_login.logInTwitterFP
	};
	}
    var logInTabPanel = new Ext.TabPanel({
	//title:'Log In',
	frame:false,
	border:false,
	hideBorders:true,
	//plain:true,
	bodyBorder:false,
	//xtype:'tabpanel',
	activeTab: 0,
	height:220,
	//autoHeight:true,
	//defaults:{autoHeight:true, bodyStyle:'padding:15px 20px 30px', labelAlign: 'top'},
	items:tabs
    });

    tv_login.panel = new Ext.Panel({
	title:'Use your account',
    //bodyStyle:"background-color:transparent;",
    //hideBorders:true,
	    //border:false,
    //bodyBorder:false,
	layout:'fit',
	items:logInTabPanel
	
    });
	
}


function deleteCookie (name, path, domain) {
	document.cookie = name + "=" + ((path) ? "; path=" + path : "") + ((domain) ? "; domain=" + domain : "") + "; expires=Thu, 01-Jan-70 00:00:01 GMT";
}


function setCookie (name, value, expires, path, domain, secure) {
    var curCookie = name + "=" + escape(value) +
    ((expires) ? "; expires=" + expires.toGMTString() : "") +
    ((path) ? "; path=" + path : "") +
    ((domain) ? "; domain=" + domain : "") +
    ((secure) ? "; secure" : "");
    document.cookie = curCookie;
}


ACOOKIE_KEY = '_tva00';  // authentication cookie, to be read in python 
NCOOKIE_KEY = '_tvn00';  // to be read in python, this cookie is not permanent
WCOOKIE_KEY = '_tvw00';  // to be read in javascript, this cookie is not permanent
PARAM_COOKIE_KEY = '_tvp00'; // to be read in javascript, this cookie is not permanent
NODE2WEB_COOKIE_KEY = '_tvn2w00'; // node sending data to the browser



TWINEDU_COOKIE_KEY = '_twinedu00'; // value is set to True when the twinedu is on


EDU_ACOOKIE_KEY = 'edu_tva00';  // authentication cookie, to be read in python 
EDU_NCOOKIE_KEY = 'edu_tvn00';  // to be read in python, this cookie is not permanent
EDU_WCOOKIE_KEY = 'edu_tvw00';  // to be read in javascript, this cookie is not permanent
EDU_PARAM_COOKIE_KEY = 'edu_tvp00'; // to be read in javascript, this cookie is not permanent
EDU_NODE2WEB_COOKIE_KEY = 'edu_tvn2w00'; // node sending data to the browser

function COOKIE_2_TWINEDU(){
    ACOOKIE_KEY = EDU_ACOOKIE_KEY;  // authentication cookie, to be read in python 
    NCOOKIE_KEY = EDU_NCOOKIE_KEY;  // to be read in python, this cookie is not permanent
    WCOOKIE_KEY = EDU_WCOOKIE_KEY;  // to be read in javascript, this cookie is not permanent
    PARAM_COOKIE_KEY = EDU_PARAM_COOKIE_KEY; // to be read in javascript, this cookie is not permanent
    NODE2WEB_COOKIE_KEY = EDU_NODE2WEB_COOKIE_KEY; // node sending data to the browser    
}

Ext.onReady(function(){
    Ext.QuickTips.init();
	tv_util_login.init();


	deleteCookie(ACOOKIE_KEY,'/','.twinverse.com');
	deleteCookie(NCOOKIE_KEY,'/','.twinverse.com');
	deleteCookie(WCOOKIE_KEY,'/','.twinverse.com');
	deleteCookie(NODE2WEB_COOKIE_KEY,'/twinverse/','.twinverse.com');
	deleteCookie(ACOOKIE_KEY,'/','twinverse.com');
	deleteCookie(NCOOKIE_KEY,'/','twinverse.com');
	deleteCookie(WCOOKIE_KEY,'/','twinverse.com');
	deleteCookie(NODE2WEB_COOKIE_KEY,'/twinverse/','twinverse.com');

	deleteCookie(ACOOKIE_KEY,'/');
	deleteCookie(NCOOKIE_KEY,'/');
	deleteCookie(WCOOKIE_KEY,'/');
	deleteCookie(NODE2WEB_COOKIE_KEY,'/twinverse/');
	deleteCookie(ACOOKIE_KEY,'/');
	deleteCookie(NCOOKIE_KEY,'/');
	deleteCookie(WCOOKIE_KEY,'/');
	deleteCookie(NODE2WEB_COOKIE_KEY,'/twinverse/');

	//tv_util_login.isiPhone = true;
	if(!tv_util_login.isiPhone){tv_register.init();}
	tv_login.init();
	//Ext.getBody().addListener("specialkey", function(){alert("escape");});

	var linkstyle =
		"margin:3px;padding:3px;font-size:12px;color:#c0ffff;font-family:tahoma,arial,helvetica;"+
		"cursor:pointer;font-weight:bold; text-decoration: none;";
	var fontsize = "font-size:12px;";
	var windowwidth=310;
	if (window.innerWidth<1050){fontsize = "font-size:9px;"; windowwidth=230;}
	if(tv_util_login.isiPhone){
		var panel = new Ext.Viewport({
		baseCls:'x-plain',
		layout:'border',
		hideBorders:true,
		items:[
	    { 
	    region:'north',bodyStyle:"background-color:transparent;",
		layout:'fit',
	    height:100,
	    html:"<img src='"+LOGO+"'/>"
	    },
	    {
	    region:'center', bodyStyle:"background-color:transparent;"
	    },
	    {
	    region:'west', bodyStyle:"background-color:transparent;",
	    width:300,
	    height:200,
	    //layout:'fit',
	    border:false,
	    items:tv_login.panel 
	    }
	    ]
    });
	}  else {
	var panel = new Ext.Viewport({
		baseCls:'x-plain',
		layout:'border',
		hideBorders:true,
		items:[
	    { 
	    region:'north',bodyStyle:"background-color:transparent;",
		layout:'fit',
	    height:100, //128
	    //html:"<img src='logo.png'/><img align='right' src='ourplanet.png'/>",
	    items:new Ext.Panel({
			layout:'border',
			height:128,

			//hideBorders:true,
			bodyStyle:"background-color:transparent;",
			border:false,
			items:[
				{region:'west',	bodyStyle:"background-color:transparent;",
				width:270,	    height:128,
				border:false,

				html:"<img src='"+LOGO+"'/>"
				//html:"<img src='decatur2.png'/>"
				
				},
				{
				region:'center',bodyStyle:"background-color:transparent;",
				//width:300,
				//height:128,
				border:false,
			    html:"<div style='"+linkstyle+"' align='right'>"+
				"<a style='"+linkstyle+"' href='http://www.twinverse.com/'>home</a>&nbsp;&nbsp;"+
				"</div><div style='font-size:22px'>&nbsp;</div>"+
				"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"
				+"<img src='"+SLOGAN+"'/>"
				}
			]
	    })		
	    },
		
//-x-system-font:none;
//color:#416AA3;
//cursor:pointer;
//font-family:tahoma,arial,helvetica;
//font-size:11px;
//font-size-adjust:none;
//font-stretch:normal;
//font-style:normal;
//font-variant:normal;
//font-weight:normal;
//line-height:normal;
//padding:4px 0;
//white-space:nowrap;		
		
	    {
	    region:'center', bodyStyle:"background-color:transparent;",
	    //width:250,
	    layout:'fit',
	    border:false,
	    items:new Ext.Panel({
			layout:'border',
			hideBorders:true,
			bodyStyle:"background-color:transparent;",
			border:false,
			items:[
				{region:'north',	bodyStyle:"background-color:transparent;",height:40},
				{region:'west',	bodyStyle:"background-color:transparent;",width:20},
				{region:'east',	bodyStyle:"background-color:transparent;",width:20},
				{
				region:'center',
				bodyStyle:"background-color:transparent;",
				layout:'column',
				//width:200,
				//height:200,
				items:[{columnWidth:.5, border:false, bodyStyle:"background-color:transparent;",html:" &nbsp;" },
					   //new Ext.Panel({
					   {
						title:TWINNAME+' is:',
						//layout:'fit',
						width:windowwidth,
						border:true,
						frame:true,
						bodyStyle:"padding:8px 0px 15px;font-family:tahoma,arial,helvetica;"+
						fontsize+
						"text-align:center;"+
						"font-size-adjust:none;font-stretch:normal;font-style:normal;font-variant:normal;"+
						"font-weight:bold;line-height:normal;"+
						"color:#416AA3;"+
						"cursor:normal;",
						//html:'toto hello'
						html:Ext.get(TWINNAME+'-msg').dom.innerHTML
					   }
						//})
					   ,{columnWidth:.5, border:false, bodyStyle:"background-color:transparent;",html:" &nbsp;" }]
				}
			]
	    })
	    },
	    {
	    region:'west', bodyStyle:"background-color:transparent;",
	    width:370,
	    layout:'fit',
	    border:false,
	    items:new Ext.Panel({
			layout:'border',
			hideBorders:true,
			bodyStyle:"background-color:transparent;",
			border:false,
			items:[
				{region:'west',	bodyStyle:"background-color:transparent;",width:90},
				{
				region:'center',
				bodyStyle:"background-color:transparent;",
				width:300,
				items:tv_login.panel
				}
			]
	    })
	    },
	    {
	    region:'east', bodyStyle:"background-color:transparent;",
	    width:370,
	    layout:'fit',
	    border:false,
	    items:new Ext.Panel({
		layout:'border', bodyStyle:"background-color:transparent;",
		hideBorders:true,
		border:false,
		items:[
		    {region:'east',	bodyStyle:"background-color:transparent;",width:90},
		    {
		    region:'center',
		    bodyStyle:"background-color:transparent;",
		    //width:350,
		    items:tv_register.registerFP
		    }
		]
	    })
	    }
	    ]
    });
	
	}
	window.setTimeout(function(){
		if(tv_util_login.isiPhone){return;}
		Ext.getBody().applyStyles("background-image:url(http://js.twinverse.com/jsnew/earth.jpeg);background-repeat: no-repeat;background-position: center top;");	
	},50.0)

});