jQuery.noConflict();

jQuery(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
	WFacebook.init();
});

var user_inf = {};
var _user_name;

WFacebook = {
	init : function(){
        //FB_RequireFeatures(["XFBML", "Connect"], function() {
		FB_RequireFeatures(["XFBML"], function() {
				FB.Facebook.init(_facebook_api,_xd_receiver, {
					//"reloadIfSessionStateChanged":true,
					//"doNotUseCachedConnectState": false,
					
					"ifUserConnected": function(){
						
						// Facebook broke parsing of quotes in JSON for IE 
						// this is a hack to fix that
						// http://bugs.developers.facebook.com/show_bug.cgi?id=8269
						if((jQuery.browser.msie || jQuery.browser.safari) && !FB.JSON.old_parse){
							FB.JSON.old_parse = FB.JSON.parse;
						    FB.JSON.parse = function(text,revive){
						        if(/"name":".*?\\'.*?"/.test(text)) text = text.replace(/\\'/g,"'");
						        return FB.JSON.old_parse(text,revive);
						    }
						}						
						
						if(!_facebook_registered){
							FB.ensureInit( function(){
								FB.XFBML.Host.parseDomTree();
								WFacebook.on_login();
							});
						}

						if(_facebook_registered && _facebook_logged_in && _pintar_sorteo_wall){
							//queremos mostrar en el muro que nos hemos apuntado a un sorteo
							FB_RequireFeatures(["Api"], function(){
								var api = new FB.ApiClient(_facebook_api);
								/*api.users_hasAppPermission("publish_stream", function(result)
								{ 
									
									if(result == 0)
									{
										// ask for premission 
										FB.Connect.showPermissionDialog("publish_stream",function (status){
											// only if they say yes
											if(status){
												WFacebook.wall_post(_message_sorteo_wall, _title_sorteo_wall);
											}
										});
									}
									// we are good, just post. 
									else{
										WFacebook.wall_post(_message_sorteo_wall, _title_sorteo_wall);
									}
									
									////////////////////////////////////////////////////////////////////////
									var auto = (result == 0) ? false : true;
									WFacebook.wall_post(_message_sorteo_wall, _title_sorteo_wall, auto);
									
								});*/

								WFacebook.wall_post(_message_sorteo_wall, _title_sorteo_wall, _image_sorteo_wall, false);
							});
						}
						
						
						/*código para insertar en el muro las votaciones de fiestas*/
						if(_facebook_registered && _facebook_logged_in && _pintar_voto_wall){
							FB_RequireFeatures(["Api"], function(){
								var api = new FB.ApiClient(_facebook_api);
								WFacebook.wall_post(_message_voto_wall, _title_voto_wall, _image_voto_wall, false);
							});
						}
						////////////////////////////////////////////////////////////////////////
						
						/*código para insertar en el muro las votaciones de playas*/
						if(_facebook_registered && _facebook_logged_in && _pintar_playa_wall){
							FB_RequireFeatures(["Api"], function(){
								var api = new FB.ApiClient(_facebook_api);
								WFacebook.wall_post(_message_playa_wall, _title_playa_wall, _image_playa_wall, false);
							});
						}
						////////////////////////////////////////////////////////////////////////
						
						
							/*código para insertar en el muro para alojamientos*/
						if(_facebook_registered && _facebook_logged_in && _pintar_alo_wall){
							FB_RequireFeatures(["Api"], function(){
								var api = new FB.ApiClient(_facebook_api);
								WFacebook.wall_post(_message_alo_wall, _title_alo_wall, _image_alo_wall, false);
							});
						}
						////////////////////////////////////////////////////////////////////////
						
						/*código para insertar en el muro para alojamientos*/
						if(_facebook_registered && _facebook_logged_in && _pintar_inm_wall){
							FB_RequireFeatures(["Api"], function(){
								var api = new FB.ApiClient(_facebook_api);
								WFacebook.wall_post(_message_inm_wall, _title_inm_wall, _image_inm_wall, false);
							});
						}
						////////////////////////////////////////////////////////////////////////
						
						
					},
					// do logout 
					"ifUserNotConnected": function(){
						// if your not connected and we think you are.. go to the logout page
						if(_facebook_logged_in){
						//	alert('do logout?');
							if(!WFacebook.onLogout){
								WFacebook.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
	          WFacebook.reload_page();
	        });
	    });
	},
	
	show_login_from_page : function(){
		ModalHelper._authenticatedDest = location.href;
		WFacebook.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 ){
              //WFacebook.on_login();
            }, function() {
              //alert( "User not connected" );
            });
          });
//      }, 1);	

	},

        // on a good login check for prems, and account
		on_login : function(){
			FB.Facebook.get_sessionState().waitUntilReady(function(){
				var query = "SELECT first_name FROM user WHERE uid='" + FB.Facebook.apiClient.get_session().uid + "'";
				FB.Facebook.apiClient.fql_query(query, function(users){
					_user_name = users[0].first_name;
				});
			});
			/*
			jQuery.post(_prefix + 'includes/funciones_facebook.php?fbc=2504', {}, function(resp, _status){
				alert(resp);
				_user_name = resp.nombre;															
			});	
			*/
			
			/*FB.Facebook.apiClient.users_hasAppPermission('publish_stream,offline_access', function (hasPermissions) {
			   if(!hasPermissions){
			    	FB.Connect.showPermissionDialog("publish_stream,offline_access",function (status){
						WFacebook.check_have_account();
					});
			    }
				else{
					WFacebook.check_have_account();
				}
				
			});*/
			WFacebook.check_have_account();
        
		},
		
		wall_post: function(msg, title, imagen, registro){
			var message_wall = msg.replace('{*actor*}', _user_name);
			var title_wall = title.replace('{*actor*}', _user_name);
			var attachment = {	'name': title_wall, 
								'href': _http_base, 
								'caption': message_wall, 
								'media':[{	'type':'image',
										 	'src': imagen,
										 	'href':_http_base}]
								};

			var actionLinks = [{ "text": _title_link_wall, "href": _http_base}];
			var disclaimer = _wall_disclaimer;
			FB.Connect.streamPublish('', attachment, actionLinks, null, disclaimer, function(post_id, exception, data){
				if(exception){
					//alert('error :' + exception);
				}else{
					//alert('todo ok');
				}
				
				if(registro) WFacebook.check_login();
			});
		},
		
        // show the facebook popup to ask for more premissions 
        prompt_advanced: function(){
			FB.ensureInit( function(){
				FB.Connect.showPermissionDialog("email",function (status){
				    var resp = {};
					var registrar=false;
;
					
					
					if(status){
				        allowed = status.split(',');
				        for(i=0; i<allowed.length; i++){
							if(allowed[i]=='email') registrar=true;
							//if(allowed[i]=='publish_stream') auto=true;
				            resp[allowed[i]] = true;
				        }
				    }
					if(registrar){
						// update us so we dont prompt for it anymore
						
						jQuery.post(_prefix + 'includes/funciones_facebook.php?fbc=2502', resp, function(resp, _status){
							// now lets check login stuff
							//if(enviarMuro) WFacebook.wall_post(_message_wall, _title_wall);
							
							WFacebook.user_inf = resp;
							WFacebook.wall_post(_message_wall, _title_wall, _image_wall, true);
							//WFacebook.check_login();
						},'json');
					}else{
						window.location=_prefix + 'html/usuarios/comprobarPermisosFacebook.php'
					}
					
				})
			});
		},

        // this is shown in the user is not logged in and connected with facebook
        check_have_account: function(from_flash){
			if(from_flash)
            WFacebook.from_flash = from_flash;
			//alert('show Already have a welcome account pupup');
			// make sur we only post once

			if(!WFacebook.post_done){
				WFacebook.post_done = true;
	            jQuery.post(_prefix + 'includes/funciones_facebook.php?fbc=2501', {}, function(resp, _status){
	                WFacebook.user_inf = resp;
					//alert(WFacebook.user_inf.welcome_user +' : '+ WFacebook.user_inf.facebook_user+' : '+WFacebook.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(!WFacebook.user_inf.facebook_email_prompted){
						WFacebook.prompt_advanced();
					}else{
						WFacebook.check_login();
					}
	            }, 'json'); 
			}
        },

		check_login: function(){
            // this is a facebook user but not a real welcome user 
            // so let prompt them to link the account
			//alert(WFacebook.user_inf.facebook_user +' : '+ WFacebook.user_inf.welcome_user);
            if(!WFacebook.user_inf.facebook_user && !WFacebook.user_inf.welcome_user){ 
				WFacebook.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 welcome user and facebook user so just reload the page
            else if(WFacebook.user_inf.facebook_user && WFacebook.user_inf.welcome_user){
				//WFacebook.reload_page();
				location.reload();
            }
			// this user did not merge so is a facebook only user
			else{
				WFacebook.do_logout(_prefix + 'salir.php');
				//WFacebook.reload_page();
			}			
		},
		
        // Log out and send to welcome logout page
        do_logout: function(url){
          FB.ensureInit( function(){
				WFacebook.onLogout = true;
            	FB.Connect.logout(function(logout){
					location.href = url;
				});
				//FB.Connect.logoutAndRedirect("/logout");  
          });
        },

        // 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(WFacebook.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: '+ WFacebook.done_url);
				}
				else{
					window.location.href = window.location.href;
					//alert('normal reload')
				}
				*/
        	}
		},
		
        post: function(url, title, preview_url, _callback){
			WFacebook.feed_post(null, title, url, preview_url, _callback);
		},
		friend_post: function(url, title, preview_url, friend, _callback){
			WFacebook.feed_post(friend, title, url, preview_url, _callback);
		},
		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){
								WFacebook.do_photo_post(make_id);
							}
						});
				    }
					// we are good, just post. 
					else{
						WFacebook.do_photo_post(make_id);
					}
				});
			});
		},
		do_photo_post : function(make_id){
			WFacebook.logged_in_facebook(
			   function(){

				data = 'make=' + encodeURIComponent(make_id) 
					handler = function(json){
						jQuery('#throbber').hide();
						jQuery('#modal_preview_wrap').show();			
						document.getElementById('upload_photo_link').href = json.link
					}
					ModalHelper.showModal('upload_modal');  
					// /share/facebook_upload.json  ..?
					jQuery.post('/share/facebook_upload', data, handler, 'json');
			   },
			   function(){
			       WFacebook.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'); 
		    });
		},

		feed_post: function(friend_id, title, url, thumb, callback){
			var api = FB.Facebook.apiClient;    
		    var actor, target, post, cmpid;
		    var lookup_users = [];
		    var base_url = _http_base;
		
		    // we need to know our name
		    lookup_users.push(api.get_session().uid);
			
			if(typeof(_friend_wall_post_template) == 'undefined')
			    _friend_wall_post_template = '';

			if(typeof(_wall_post_template) == 'undefined')
			    _wall_post_template = '';
			
			if(typeof(_site_name) == 'undefined')
				    _site_name = 'Welcome';	
			
		    if(friend_id){
		        // we need to add our friends id to the name lookup 
		        lookup_users.push(friend_id);
		
		        post = _friend_wall_post_template;
		        cmpid =  _fb_friend_post_cmpid; 
		    }
		    else{
		        post = _wall_post_template;
		        cmpid =  _fb_post_cmpid; 
		    }
			
		    // add cmpid to the urls 
		    if (cmpid){
		       url += (url.indexOf('?') > -1)?"&":"?" + "cmpid="+cmpid;
		       base_url += (base_url.indexOf('?') > -1)?"&":"?" + "cmpid="+cmpid;
		    }

		    // first get info about the user
		    api.users_getInfo(lookup_users,['name'], function(info, ex){
		        actor = info[0].name;
		        post = post.replace('{*actor*}', actor);
		        if(friend_id){
		            target = info[1].name;
		            post = post.replace('{*target*}', target);
		        }        

		        // setup the post
		        var action_link = [{'text':'www.welcometoibiza.es','href':base_url}]
		        var attachment = {
		            'name':_site_name,
		            'href':base_url,
		            'caption' : post,
		            'media':[{'type':'image','src': thumb,'href':base_url}]
		        };
		
				// now we get to do the actual post
		        FB.Connect.streamPublish('', attachment,action_link, friend_id, 'Add a message', function(post_id, exception, data){
		            if(exception){
		                // there was some sort of problem 
		            }
		            else if(post_id && post_id != 'null'){
						if(friend_id){
							// do omniture tracking and notification on friend post							
							var api = FB.Facebook.apiClient;
							info = post_id.split('_');
							user_id = api.get_session().uid;
							story_id = info[1];
							//WFacebook.send_notification(friend_id, 'posted an awesome welcome Sendable on your wall. <a href="http://www.facebook.com/profile.php?id='+friend_id+'&v=feed&story_fbid='+story_id+'">Click here to see it.</a>')		                
							OmnitureHelper.pageView('post_to_friend_click');
						}

                                                if (typeof(callback) != 'undefined')
						    callback();
		            }
		            else{
		                // they closed it
		            }
		        });      
		    });
		}		
};

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

