function login(merge)
{
	 FB.Facebook.apiClient.users_hasAppPermission("email", 
	 function(blnAccepted) {
	 	 if (blnAccepted == 0) 
         {
         	FB.Integration.showPermissionDialog('email', function(result)
    		{
				if(!result)
		        {
		            if (merge)
		            {
		                fbMerge();  	
		            }
		            else
		            {
		            	loginProcess();
		            }
		          
		          /*alert("You have not provided permissions, so redirecting to home");
		          //$("#loading").hide();
		          FB.Connect.logoutAndRedirect("/");
		          return false;*/
		        }
		        else if(result.indexOf("email") < 0)
		        {
		          alert("You have not provided permissions, so redirecting to home");
		          //$("#loading").hide();
		          FB.Connect.logoutAndRedirect("/");
		          return false;
		        }
		        else if(result.indexOf("proxy") >= 0)
		        {
		          alert("You have not provided permissions, so redirecting to home");
		          $("#loading").hide();
		          FB.Connect.logoutAndRedirect("/user/logout");
		          return false;
		        }
		        else if(result.indexOf("email") >= 0)
		        {
		            if (merge)
		            {
		                fbMerge();  	
		            }
		            else
		            {
		            	loginProcess();
		            }
		          
		        }
    			
    		}, true);         	
         } 
         else
         {
         	if (merge)
		            {
		                fbMerge();  	
		            }
		            else
		            {
		            	loginProcess();
		            }
         	
         }     	
      });    
}

function fbMerge()
{
	if ($("#userPhotoName"))
	{
		var sssPhoto = $("#userPhotoName").val();
	}
	else
	{
		var sssPhoto = '';
	}
	
    FB.Connect.get_status().waitUntilReady(function(status)
     {
           switch(status)
           {
               case FB.ConnectState.connected:
   
				    FB.Facebook.get_sessionState().waitUntilReady(function()
				    {
				        FB.Facebook.apiClient.users_getLoggedInUser(function(result, ex) 
				        {
				            var user_id = result;
				            var email="";
				            var data = "";
						    var city ="";
						    var state ="";
						    var gender ="";
						    var country ="";
						    var zipcode ="";
						    var picture ="";
						    var last_name ="";
						    var first_name ="";
				            
				            FB.Facebook.apiClient.users_getInfo(user_id,'email,first_name,last_name,hometown_location,sex,pic_big',function(result1, ex) 
				            {
				                gender         = result1[0]['sex'];
				                email          = result1[0]['email'];
				                picture        = result1[0]['pic_big'];
				                last_name      = result1[0]['last_name'];
				                first_name     = result1[0]['first_name'];
				                data           = result1[0]['hometown_location'];
				                 
				                if(data != null)
				                {
				                    country = result1[0]['hometown_location']['country'];
				                    state   = result1[0]['hometown_location']['state'];
				                    city    = result1[0]['hometown_location']['city'];
				                    zipcode = result1[0]['hometown_location']['zip'];
				                }
				                var dataString = "facebook_id="+user_id+"&facebook_email="+email+"&first_name="+first_name+"&last_name="+last_name+"&city="+city+"&state="+state+"&picture="+picture+"&country="+country+"&zipcode="+zipcode+"&gender="+gender;
				                
				                var reply = confirm("Merging your Facebook account with your Share Some Sugar account means that any email that " +
				                		            "we send you will go to the email address that you use for Facebook.");
				                
				                if (reply==true)
				                {
				                   dataString += "&overwrite=yes";
				                }
				                
				                if (picture != '' && sssPhoto != '')
                                {
                                        var con = confirm("Would you like to use facebook photo in ShareSomeSugar?");
                                        
                                        if (con)
                                        {
                                            dataString += "&overwritephoto=yes";
                                        }
                                        else
                                        {
                                        	dataString += "&overwritephoto=no";
                                        }
                                }
                                else
                                {
                                	dataString += "&overwritephoto=yes";
                                }
                               
				                $.ajax({
				                      type:'POST',
				                      url:'/user/mergeFacebook',
				                      data: dataString,
				                      beforeSend: function() 
				                      {
				                           //$("#fconnect").html('Connecting...');
				                      },
				                      success:function(msg)
				                      {
				                        if (msg=='unavailable')
				                        {
				                        	alert("Email already used by another account.Try different facebook account");
				                        	FB.Connect.logout();
				                        }
				                        else
				                        {
				                        	window.location.reload();
				                        }
				                      }
				                });
				                
				            });
				        });
				    });
                break;
                case FB.ConnectState.userNotLoggedIn:
                    location.href = '/user/logout/true';
                break;
                default:
                    location.href = '/user/logout/true';
                break;
           }
     });
}

// Get the facebook data for the facebook loged in user
function loginProcess()
{
     $("#loading").show();
     
     var data = "";
     var user_id ="";
     var user_city ="";
     var user_email ="";
     var user_state ="";
     var user_gender ="";
     var user_country ="";
     var user_zipcode ="";
     var user_picture ="";
     var user_lastname ="";
     var user_firstname ="";
   
    FB.Facebook.get_sessionState().waitUntilReady(function()
    {
        FB.Facebook.apiClient.users_getLoggedInUser(function(result, ex) 
        {
             user_id =   result;       
                     
             FB.Facebook.apiClient.users_getInfo(user_id,'first_name,last_name,email,hometown_location,sex,pic_big',function(result1, ex) 
             {
                 user_firstname = result1[0]['first_name'];
                 user_lastname  = result1[0]['last_name'];
                 user_email     = result1[0]['email'];
                 data           = result1[0]['hometown_location'];
                 user_gender    = result1[0]['sex'];
                 user_picture   = result1[0]['pic_big'];
                 
                 if (user_email == null)
                 {
                 	user_email = "";
                 }
                 
                 if(data != null)
                 {
                     user_city    = result1[0]['hometown_location']['city'];
                     user_state   = result1[0]['hometown_location']['state'];
                     user_country = result1[0]['hometown_location']['country'];
                     user_zipcode = result1[0]['hometown_location']['zip'];
                 }
                 
                 var dataString = 'first_name='+user_firstname+'&last_name='+user_lastname+'&email='+user_email+'&userid='+user_id+'&city='+user_city+'&state='+user_state+'&picture='+user_picture+'&country='+user_country+'&zipcode='+user_zipcode+'&gender='+user_gender+'&overwritephoto=yes';
                                                                   
                 $.ajax({
                           type:'POST',
                           url:'/facebook/insert',
                           data: dataString,
                           success: function(msg)
                           { 
                               $("#loading").hide();
                               
                               if (msg == 'email existing')
                               {
                                     if ($('#hiddenurl').val() != '')
									 {
									     location.href = $('#hiddenurl').val().replace(/ /g, "+");
									 }
									 else
									 {
									     location.href ="/user/friendgroup";
									 }
                                    
                               }
                               else if(msg == 'user_merge')
                               {
                                    alert("You already have an account with ShareSomeSugar." +
                                    		"We merged your facebook account with existing ShareSomeSugar account Finito completo! " +
                                    		"Your Share Some Sugar account is now merged with your facebook account!");
                                    
                                    if ($('#hiddenurl').val() != '')
								    {
								        location.href = $('#hiddenurl').val().replace(/ /g, "+");
								    }
								    else
								    {
								        location.href ="/user/friendgroup";
								    }
                                     
                               }
                               else if(msg == 'user_merge_error')
                               {
                               	    alert("Email already used by another account.Try different facebook account");
                                    FB.Connect.logout();
                               }
                               else if (msg == 'new user')
                               {
                                   location.href = "/user/join"; 
                                    
                               }
                               else
                               {
                                    if ($('#hiddenurl').val() != '')
                                    {
                                        location.href = $('#hiddenurl').val().replace(/ /g, "+");
                                    }
                                    else
                                    {
                                        location.href = msg;
                                    }    
                                   
                               }
                               
                           }
                       }); 
             });
          });
      });
}

