$(document).ready( function() {
	/* 
		Remove all subdomain facebook cookies. 
		They should all be handled by basedomain cookie 
	*/

	prefix_keys = ['base_domain_', 'fbsetting_']
	postfix_keys = ['', '_user', '_ss', '_session_key', '_expires']

	exp = "=;expires=Thu, 01 Jan 1970 00:00:00 GMT"+'; path=/';
	for(i=0;i<prefix_keys.length;i++){
	   document.cookie = prefix_keys[i]+_facebook_api+exp;
	}
	for(i=0;i<postfix_keys.length;i++){
	   document.cookie = _facebook_api+postfix_keys[i]+exp;
	}
		
	// do normal facebook init
	JJFacebook.init();
});

var user_inf = {};

JJFacebook = {
	init : function(){
        //FB_RequireFeatures(["XFBML", "Connect"], function() {
		FB_RequireFeatures(["XFBML"], function() {
				FB.Facebook.init(_facebook_api,_xd_receiver, {
					//"reloadIfSessionStateChanged":true,
					//"doNotUseCachedConnectState": false,
					"ifUserConnected": function(){
						//alert("i am connected");
						if(!_facebook_registered){
							FB.ensureInit( function(){
								FB.XFBML.Host.parseDomTree();						
								JJFacebook.on_login();
							});
						}
						else{
							if(!_facebook_logged_in) {
								JJFacebook.reload_page();
							}
						}
					},
					// do logout 
					"ifUserNotConnected": function(){
						//alert(1);
						// if your not connected and we think you are.. go to the logout page
						if(_facebook_logged_in){
						//	alert('do logout?');
							if(!JJFacebook.onLogout){
								JJFacebook.reload_page();
							}
						//	document.location.href = '/logout'
						}
					} 
			} );
		});
		//FB.Facebook.init(_facebook_api,'/xd_receiver.html');
	
	},	
	getAPIkey : function(){
		return _facebook_api;
	},
	facebookReady : function(callback){
		FB.ensureInit(function() {
	      FB.Facebook.get_sessionState().waitUntilReady(function(session) {
	          var is_now_logged_into_facebook = session ? true : false;

	          // if the new state is the same as the old (i.e., nothing changed)
	          // then do nothing
	          if (is_now_logged_into_facebook == _facebook_logged_in) {
	            callback();
				return;
	          }

	          // otherwise, refresh to pick up the state change
	          JJFacebook.reload_page();
	        });
	    });
	},
	
	show_login_from_page : function(){
		ModalHelper._authenticatedDest = location.href;
		JJFacebook.show_login();
	}, 
	show_login : function(done_url){
		if(done_url){
			ModalHelper._authenticatedDest = done_url;
		}
		if (s) {
			s.pageName = "Modal : login - Facebook";
			s.t();
		}
	//	FB.Connect.requireSession();
    // i dont know why facebook connect dows this but this setTimeout will force it to open in the page.
//	setTimeout(function(){
          FB.Connect.requireSession(function(){
            FB.Connect.ifUserConnected( function( uid ){
              //JJFacebook.on_login();
            }, function() {
              //alert( "User not connected" );
            });
          });
//      }, 1);	

	},

        // on a good login check for prems, and account
		on_login : function(){
                JJFacebook.check_have_account();
		},
      
        // show the facebook popup to ask for more premissions 
        prompt_advanced: function(){
			FB.ensureInit( function(){
				FB.Connect.showPermissionDialog("email",function (status){
				    var resp = {};
					if(status){
				        allowed = status.split(',');
				        for(i=0; i<allowed.length; i++){
				            resp[allowed[i]] = true;
				        }
				    }
				    // update us so we dont prompt for it anymore
				    $.post('/user/update_facebook_extended_access', resp, function(resp, _status){
						// now lets check login stuff
						JJFacebook.check_login();
				    },'json');
				})
			});
		},

        // this is shown in the user is not logged in and connected with facebook
        check_have_account: function(from_flash){
			if(from_flash)
            JJFacebook.from_flash = from_flash;
			//alert('show Already have a Jibjab account pupup');
			// make sur we only post once
			if(!JJFacebook.post_done){
				JJFacebook.post_done = true;
	            $.post('/user/facebook_login', {}, function(resp, _status){
	                JJFacebook.user_inf = resp;
					//alert(JJFacebook.user_inf.jibjab_user +' : '+ JJFacebook.user_inf.facebook_user+' : '+JJFacebook.user_inf.facebook_email_prompted);
                
	                // after this this user will be a facebook_user, so this will not show up
					// check_have_accountck if we need advanced options (email)
				    // if er have a facebook user and no e-mail... we have laready asked them.
					if(!JJFacebook.user_inf.facebook_email_prompted){
							JJFacebook.prompt_advanced();
					}
					else{
						JJFacebook.check_login();
					}
	            }, 'json'); 
			}
        },

		check_login: function(){
            // this is a facebook user but not a real jibjab user 
            // so let prompt them to link the account
			//alert(JJFacebook.user_inf.facebook_user +' : '+ JJFacebook.user_inf.jibjab_user);
            if(!JJFacebook.user_inf.facebook_user && !JJFacebook.user_inf.jibjab_user){ 
				JJFacebook.show_merge = true;
				
				// reload the FBML tags for the new windows. 
				FB.ensureInit( function(){FB.XFBML.Host.parseDomTree();});
				ModalHelper.showModal("already_have_account");
			}
			// this is a jibjab user and facebook user so just reload the page
            else if(JJFacebook.user_inf.facebook_user && JJFacebook.user_inf.jibjab_user){
				JJFacebook.reload_page();
            }
			// this user did not merge so is a facebook only user
			else{
				JJFacebook.reload_page();
			}			
		},
		
        // Log out and send to jibjab logout page
        do_logout: function(url){
          FB.ensureInit( function(){
				JJFacebook.onLogout = true;
            	FB.Connect.logout(function(logout){
					location.href = url;
				});
				//FB.Connect.logoutAndRedirect("/logout");  
          });
			// on logout clear the birthday cookie
	    	document.cookie = "birthday_data=; expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/";
        },

        // when we are done with the popups we want to reload the page 
        // dont use reload function so that it does not try to repost forms. 
        reload_page: function(){
          	if(JJFacebook.from_flash){
				document.getElementById('@{application}')['onLoggedIn'](FB.Facebook.apiClient._session);
			}
			else{
				
				ModalHelper.gotoAuthenticatedDest();
				/*
				if(ModalHelper._authenticatedDest){
					window.location.href = ModalHelper._authenticatedDest;
					//alert('go to url: '+ JJFacebook.done_url);
				}
				else{
					window.location.href = window.location.href;
					//alert('normal reload')
				}
				*/
        	}
		},
		
		post: function(url, title, preview_url, _callback){
		    if(_fb_post_cmpid){
			    url += (url.indexOf('?') > -1)?"&":"?" + "cmpid="+_fb_post_cmpid
			}
			conf = {
		        "base_url":  _http_base,
		        "url":url,
		        "title":title,
		        "images":[{
		            "src": preview_url, 
		            "href":url}
		        ]
		    };

			var callback = function(id) {
				if(id != 'null'){
					if(_callback){
						_callback();
					}
				}
			};
			
		    FB.Connect.showFeedDialog(_facebook_post_template_id, conf, null, 'Source: '+url, null, FB.RequireConnect.require, callback, 'Add a message.', '');
		},
		friend_post: function(url, title, preview_url, friend, _callback){
			if(_fb_friend_post_cmpid){
		    	url += (url.indexOf('?') > -1)?"&":"?" + "cmpid="+_fb_friend_post_cmpid
			}    
			conf = {
		        "base_url":  _http_base,
		        "url":url,
		        "title":title,
		        "images":[{
		            "src": preview_url, 
		            "href":url}
		        ]
		    };
			var callback = function(id) {
				OmnitureHelper.pageView('post_to_friend_click');
				if(id != 'null'){
					if(_callback){
						_callback();
					}
					var api = FB.Facebook.apiClient;
					info = id.split('_');
					user_id = api.get_session().uid;
					story_id = info[1];
					JJFacebook.send_notification(friend, 'posted an awesome JibJab Sendable on your wall. <a href="http://www.facebook.com/profile.php?id='+user_id+'&v=feed&story_fbid='+story_id+'">Click here to see it.</a>')
				}
			};

			freinds = new Array(friend);
			FB.Connect.showFeedDialog(_facebook_friend_post_template_id, conf, freinds, 'Source: '+url, null, FB.RequireConnect.require, callback, 'Add a message.', '');
		},
		photo_post : function(make_id){
			FB_RequireFeatures(["Api"], function(){
				var api = new FB.ApiClient(_facebook_api);
				api.users_hasAppPermission("photo_upload", function(result)
				{ 
				    if(result == 0)
				    {
						// ask for premission 
						FB.Connect.showPermissionDialog("photo_upload",function (status){
							// only if they say yes
							if(status){
								JJFacebook.do_photo_post(make_id);
							}
						});
				    }
						// we are good, just post. 
					else{
						JJFacebook.do_photo_post(make_id);
					}
				});
			});
		},
		do_photo_post : function(make_id){
			JJFacebook.logged_in_facebook(
			   function(){

				data = 'make=' + encodeURIComponent(make_id) 
					handler = function(json){
						$('#throbber').hide();
						$('#modal_preview_wrap').show();			
						document.getElementById('upload_photo_link').href = json.link
					}
					ModalHelper.showModal('upload_modal');  
					// /share/facebook_upload.json  ..?
					$.post('/share/facebook_upload', data, handler, 'json');
			   },
			   function(){
			       JJFacebook.reload_page();
			   }
			);			
		},

		logged_in_facebook : function(is_logged_in, not_logged_in){
		    // some times FB is not defined 
		    try{FB}catch(e){not_logged_in();return};

		    var api = FB.Facebook.apiClient;
		    // check session
		    if(api.get_session()){
		        // facebook dosnt really know the status of the session until we try fql query
		        // get the current users name with FBML 
		        api.fql_query("SELECT name FROM user WHERE uid='"+api.get_session().uid+"'",function(users){
		            if(users != null){
		                // we got a reply back so all is good
		                is_logged_in();
		            }
		            else{
		                // we thought we had a session but after a query we know we do not. 
		                not_logged_in();
		            }
		        });
		    }
		    else{
		        // no session
		        not_logged_in(); 
		    }
		},
		send_notification : function(user, message){
		    var api = FB.Facebook.apiClient;
		    var sequencer = new FB.BatchSequencer();   
		    var pendingNotificationsResult = api.notifications_send(user, message,sequencer);
		    sequencer.execute(function() { 
		        //FB.FBDebug.dump(pendingNotificationsResult.result, 'notificationsResult from batch execution'); 
		    });
		}
};

/*
FB_RequireFeatures(["XFBML"], function() {
  FB.Facebook.init('9d3c08ecf24a14c9faaf7db420c8aa62','/xd_receiver.html');
  
});*/
