YUI.add('dragontape-ui-logindialog',function(Y) {
    Y.namespace('dragontape.ui');
    var LoginDialog=Y.Base.create('logindialog',Y.Widget,[],{
    	// prototype
    	
    	_loginTab:null,
    	_registerTab:null,
    	_loginPanel:null,
    	_registerPanel:null,    	
    	_cregisterButton:null,
    	_cloginButton:null,
    	_registerButton:null,
    	_loginButton:null,
    	_loginError:null,
    	_registerError:null,
    	_overlay:null,
    	_getData:function(node){
	    	var data={};
	    	try {
	        	node.all('input').each(function(node){ 
	        		data[node.getAttribute('name')]=Y.Node.getDOMNode(node).value 
	        	});
	    	} catch (e) {
//	    		Y.log(e)
	    	}
	    	
	    	return data;
		},
    	initializer:function() {  
    	},
    	renderUI:function() {
    		var tabbar=Y.Node.create('<div class="tabbar"></div>');
    		var bb=this.get('boundingBox');
    		var cb=this.get('contentBox');
    		
    		this._overlay=Y.Node.create('<div id="dialogoverlay" style="z-index:999;display:none;background:black;opacity:0.5;position:fixed;top:0px;left:0px;right:0px;bottom:0px;"></div>');
    		this._loginTab=Y.Node.create('<div class="tab"><span>Sign in</span></div>');
    		this._registerTab=Y.Node.create('<div class="tab"><span>Join</span></div>');
    		
    		tabbar.append(this._loginTab);
    		tabbar.append(this._registerTab);
    		tabbar.append(	'<span id="fbconnect" style="float:right"><fb:login-button scope="email,publish_actions" autologoutlink="false" onlogin="try{fbLoginPressed()}catch(e){}">Login with Facebook</fb:login-button></span>'+
							'<span id="loginname"></span>');
    		//addFBLogin(function(u){console.log(u)});
    		bb.insertBefore(tabbar,cb);
    		
    		this._loginPanel=Y.Node.create(
    				
    				'<form>'+
    				'<div class="error"></div>'+
    				'<label for="login-email">email:</label><br>'+
    				'<input type="text" id="login-email" name="email"/>'+
    				'<label for="login-password">password:</label><br>'+
    				'<input type="password" id="login-password" name="password"/>'+
    				
    				
    				//'<div class="help" style="">You can change the auto-generated password after login by clicking on your username in the header'+
    				'<div class="help"><a href="/signin" style="margin:10px;">Forgot password?</a>'+
    				//'<a class="lightcolor" href="javascript:showModal(\'modal-faq\')">Need help?</a>'+
    				'</div><div style="clear:both"></div>'+
    				'<div class="buttonbar"></div>'+
				'</form>');
    		
    		this._registerPanel=Y.Node.create(
    				
    				'<form>'+
    				'<div class="error"></div>'+
    				
    				'<label for="register-email">email:</label><br>'+
    				'<input type="text" id="register-email" name="email"/>'+
    				'<label for="register-name">screen name:</label><br>'+
    				'<input type="text" id="register-name" name="name"/>'+
    				
    				'<div class="accept"><input type="checkbox" id="register-accept" name="accept" checked>'+
    				'<a href="/terms" class="acceptterms" target="_blank">accept terms and conditions</a></div><div style="clear:both">'+
    				'<div class="accept"><input type="checkbox" id="register-auto" name="auto" checked><span class="acceptterms auto">generate password automatically</span></div><div style="clear:both">'+
    				'<div id="addpass" class="help">You can change the auto-generated password after registration by clicking on your username in the header'+
    				
    				'</div>'+
    				'<div class="buttonbar"></div>'+
				'</form>');

    		this._cregisterButton=Y.Node.create('<div class="button lightbggray">LATER</div>');
    		this._cloginButton=Y.Node.create('<div class="button lightbggray">CANCEL</div>');
    		this._loginButton=Y.Node.create('<div class="button lightbgcolor">SIGN IN</div>');
    		this._registerButton=Y.Node.create('<div class="button lightbgcolor">SIGN UP</div>');

    		this._loginPanel.one('.buttonbar').insert(this._cloginButton,0);
    		this._loginPanel.one('.buttonbar').insert(this._loginButton,0);
    		
    		this._registerPanel.one('.buttonbar').insert(this._cregisterButton,0);
    		this._registerPanel.one('.buttonbar').insert(this._registerButton,0);
    		
    		this._loginError=this._loginPanel.one('.error');
    		this._registerError=this._registerPanel.one('.error');
    		
    		Y.on('click',function(e){
    			if(Y.one('#register-auto')._node.checked==true){
    				Y.one('#addpass').set('innerHTML','You can change the auto-generated password after registration by clicking on your username in the header');
    			}
    			else {
    				Y.one('#addpass').set('innerHTML',
    					'<label for="register-pass">password:</label><br>'+	
    					'<input type="password" id="register-pass" name="password" placeholder="Type a password" />');
    					Y.one('#register-pass').focus();
    			}
    		},'#register-auto');
    		
    		if(!dragontape.user){
    		initFB(function(){
    			//FB.Event.subscribe('auth.sessionChange', Y.dragontape.ui.fbLoginSession);
    			//FB.getLoginStatus(Y.dragontape.ui.fbLoginSession);
    		});
    		}
    		
    		cb.append(this._loginPanel);
    		cb.append(this._registerPanel);
    		Y.one('body').append(this._overlay);
    	},
    	bindUI:function() {
    		var that=this;
    		var cancel=function() {
    			if(!that.get('loginProgress') && !that.get('registerProgress')) {
    				that.hide();
    				if(Y.one('#dragontape-player')) Y.one('#dragontape-player').setStyle('visibility','visible');
    			}
    		};
    		
    		initFB(function(){
    			FB.Event.subscribe('auth.sessionChange', Y.dragontape.ui.fbLoginSession);
    			//FB.getLoginStatus(Y.dragontape.ui.fbLoginSession);
    		});
    		
    		var submitLogin=function(e) {
    			that._loginError.removeClass('show');
    			e.halt();
    			if(!that.get('loginProgress')) {
        			Y.fire('logindialog:login',that._getData(that._loginPanel));    			
    			}
    		};
    		
    		var submitRegister=function(e){
    			that._registerError.removeClass('show');
    			e.halt();
//    			Y.log(that._getData(that._registerPanel).accept);
    			if(!that.get('registerProgress') && that._getData(that._registerPanel).accept=="on") {
        			Y.fire('logindialog:register',that._getData(that._registerPanel));    			
    			}
    		};
    		
    		var lostRegistration=function(e) {
    			//that._loginError.removeClass('show');
    			e.halt();
//    			Y.log('email '+that._getData(that._loginPanel).email);
    			Y.dragontape.models.user.lostregistration({email:that._getData(that._loginPanel).email});
//    			Y.log('after email '+that._getData(that._loginPanel).email);
    			that._loginError.removeClass('show');
    		};
    		
    		this._loginTab.on('click',function(){
    			that.set('selectedTab',0);
    		});
    		this._registerTab.on('click',function(){
    			that.set('selectedTab',1);
    			
    		});
    		
    		this.on('selectedTabChange',function(e) {
    			if(e.newVal==0) {
    				this._loginTab.addClass('active');
    				this._registerTab.removeClass('active');
    				this._loginPanel.addClass('show');
    				this._registerPanel.removeClass('show');
    				try{this._loginPanel.one('#login-email').focus();}catch(e){}
    			} else {
    				this._loginTab.removeClass('active');
    				this._registerTab.addClass('active');
    				this._loginPanel.removeClass('show');
    				this._registerPanel.addClass('show');
    				try{this._registerPanel.one('#register-email').focus();}catch(e){}
    			}
    		});
    		
    		this._loginButton.on('click',submitLogin);
    		this._loginPanel.on('submit',submitLogin);
    		this._loginPanel.on("keydown",  function(e) {
    			if (e.charCode == 13) {
//	    			Y.log('keydown');
	    			submitLogin(e)
	    		}
    		});
    		this._registerButton.on('click',submitRegister);
    		this._registerPanel.on('submit',submitRegister);
    		this._registerPanel.on("keyup",  function(e) {
    			if (e.charCode == 13) {submitRegister(e)}
    			
    			if(Y.one('#register-name')._node.value.substr(-1)=="@") {
    				value=Y.one('#register-name').get('value');
    				Y.one('#register-name').set('value',value.substr(0,value.length-1));
    			}
    			
    		});
    		this._cregisterButton.on('click',cancel);
    		this._cloginButton.on('click',cancel);
    		
    		this.on('visibleChange',function(e) {
    			if(e.newVal) {
    				this._overlay.setStyle('display','block');
    				this.set('registerError','');
    				this.set('loginError','');    				
    			} else {
    				this._overlay.setStyle('display','none');
    			}
    		});
    		
    		this.on('registerErrorChange',function(e){
				this._registerError.setContent(e.newVal);
    			if(e.newVal) {
    				this._registerError.addClass('show');
    			} else {
    				this._registerError.removeClass('show');
    			}
    		});
    		
    		this.on('loginErrorChange',function(e){
				this._loginError.setContent(e.newVal);
    			if(e.newVal) {
    				this._loginError.addClass('show');
    				Y.on('click',lostRegistration,'.error .resetpass');
    			} else {
    				this._loginError.removeClass('show');
    			}
    		});
    		
    		this.on('loginProgressChange',function(e) {
    			if(e.newVal) {
    				this._loginButton.addClass('progress');
    			} else {
    				this._loginButton.removeClass('progress');
    			}
    		});

    		this.on('registerProgressChange',function(e) {
    			if(e.newVal) {
    				this._registerButton.addClass('progress');
    			} else {
    				this._registerButton.removeClass('progress');
    			}
    		});
    		
    	},
    	syncUI:function() {
    		this.set('selectedTab',0);
    	}
    },{
    	ATTRS:{
    		selectedTab:{
    			value:0
    		},
    		registerError:{
    			value:''
    		},
    		loginError:{
    			value:''
    		},
    		loginProgress:{
    			value:false
    		},
    		registerProgress:{
    			value:false
    		}
    	}
    });   
    
    var FBReady=false;
    var afterFbReady=[];
    
    window.fbAsyncInit = function() {
    	//console.log('fbinit logindialog');
    	FBReady=true;
    	//FB.init({appId: '146702228739647', status: true, cookie: true, xfbml: true}); //<- test
    	FB.init({appId: dragontape.fbid?dragontape.fbid:'155927247798446', status: true, cookie: true, xfbml: true});
    	for(i=0;i<afterFbReady.length;i++){
    		try{afterFbReady[i]();}catch(e){}
    	}
    	afterFbReady=[];
    }
    
    window.fbLoginPressed=function(){
    	
    	initFB(function(){
    		//console.log('pressed');
    		FB.getLoginStatus(Y.dragontape.ui.fbLoginSession);
    		}
    	);
    }
    
    window.initFB = function(callback){
    	afterFbReady.push(callback);
    	
    	if(FBReady){ fbAsyncInit(); return false;}
    	
    	(function(d){
    		var r = document.createElement('div');
    		r.setAttribute('id', 'fb-root');
    		document.getElementsByTagName('body')[0].appendChild(r);
    	     var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
    	     js = d.createElement('script'); js.id = id; js.async = true;
    	     js.src = "//connect.facebook.net/en_US/all.js";
    	     d.getElementsByTagName('head')[0].appendChild(js);
    	   }(document));
	}
    
 // fb connect

    var registering=false;
    Y.dragontape.ui.fbLoginSession=function(response) {
    	
    	FB.api('/me/permissions', function(perms){
    	user=dragontape.user?dragontape.user:null;
    	if (perms.data[0] && perms.data[0]['email']==1 && !registering) {
    		 registering=true;
    		 FB.api('/me', function(me){
    			 FB.api('/me/friends?access_token='+response.authResponse.accessToken, function(fbfriends){
    					f='';
    					var friends=[];
    					for(i=0;i<fbfriends.data.length;i++){f+='"'+fbfriends.data[i].id+'", ';friends.push(fbfriends.data[i].id);}
    					f='['+f.substr(0,f.length-2)+']';
    						var data={name:me.name,email:me.email,about:me.bio || '',url:me.link || '',pictureUrl:'http://graph.facebook.com/'+me.id+'/picture?type=large',facebookId:me.id,motivation:'dragontape'
    					}
    					Y.io('/api/user/fbLogin',{
    			    		method: "POST",
    			    	    data: data,
    			    	    headers:{'Content-Type':'application/x-www-form-urlencoded; charset=utf-8'},
    			    		on:{
    			    			success:Y.dragontape.models.user.loginSuccess,
    			    			failure:function(e){console.log(e);}
    			    		}
    			    	});
    					
    			 });
    		});
    	 } 
    	});
    };

    
    Y.dragontape.ui.LoginDialogWidget=LoginDialog;
    
},'0.1.1',{ requires: ['tabview','dragontape-models-user'] });

