/*
 *	Facebook Stuff
 */
 
//Production key?
//var facebookApiKey = '1c92be3163cb4dcb4ee3fbef65a1ea27';

// Dev key
// var facebookApiKey = '56cc121cad48372b5eae92f81cf511e4';
// 
// function facebookLoginHandler(exception) {
//  this.sessionData = FB.Facebook.apiClient.get_session();
//  thisMovie("flash").startFlashSess(sessionData.secret,sessionData.session_key,FB.Connect.get_loggedInUser());
// }
//   
// function facebookCancelLoginHandler(exception)   {
//  thisMovie("flash").cancelFBLogin();
// }
//  
// function startFBConnect()    {
//  FB_RequireFeatures(["Api"], function() {
//      FB.Facebook.init(facebookApiKey, 'xd_receiver.htm');   
//  });
//                                          
//  FB.Bootstrap.requireFeatures(["Connect"], function() {
//      FB.Connect.requireSession(facebookLoginHandler, facebookCancelLoginHandler);
//  });
// }
//  
// function getJSSess(){
//  return sessionData.session_key;
// }
//  function getJSUID(){
//  //return sessionData.fb_sig_user;
//  return FB.Connect.get_loggedInUser();
// }
// function getJSSec()  {
//  return sessionData.secret;
// }
// function thisMovie(movieName) {
//     if (navigator.appName.indexOf("Microsoft") != -1) {
//      return window[movieName]
//     } else {
//      return document[movieName]
//     }
// }


var FBPublish = function(){
    
    
	this.debug = true;
	this.flashId = "flash";

	// Used when debug is true
	this.devPaths = {
		apiPath: "",
		imgPath: "",
		deepLink: "",
		appId: "114894218601289"
	}

	// Used when debug is false
	this.livePaths = {
		apiPath: "",
		imgPath: "",
		deepLink: "",
		appId: "114894218601289"
	}

	this.paths;

	this.ready = false;
	this.authenticated = false;
	this.session = null;
	this.userData = null;

	var self = this;

	this.__construct__ = function(){
		//console.log("SlotCars::__construct__");
	}

	this.init = function(){
		//console.log("SlotCars::init");
		self.paths = (self.debug) ? self.devPaths : self.livePaths;
        
        FB.init({
			appId: self.paths.appId,
			status: true,
			cookie: true,
			xfbml: true
		});

        // FB.Event.subscribe("auth.login", self.loginHandler);
		FB.Event.subscribe("auth.logout", self.logoutHandler);

		FB.getLoginStatus(self.loginStatusHandler);
        
		setTimeout(function(){
			self.ready = true;
		}, 4000);
	}

	this.isReady = function(){
		console.log("SlotCars::isReady", this.ready);
	    return this.ready;
	}

	this.isAuthenticated = function(){
        console.log("SlotCars::isAuthenticated", this.authenticated);
		return this.authenticated;
	}

	this.getPath = function(){
        console.log("SlotCars::getPath");
		return (this.debug) ? this.devPath : this.livePath;
	}

	this.login = function(){
       
        console.log("SlotCars::login");
       	var permissions = [
			"publish_stream",
			"email"
		];

		var options = {
			perms: permissions.join(",")
		}

		FB.login( self.loginHandler, options );
	}

	this.logout = function(){
		//console.log("SlotCars::logout"); 
		FB.logout();
	}

	this.loginStatusHandler = function(response){
		
		console.log("SlotCars::loginStatusHandler", response);
        if(response.session){
			self.session = response.session;
			self.authenticated = true;
		}

		self.ready = true;
	}

	this.loginHandler = function(response){
		self.session = response.session;
		self.authenticated = true;

        // add in google analytics
        self.runGoogleAnalytics();

        self.shareStory();
    }

    this.runGoogleAnalytics = function() {
        _gaq.push(['_trackPageview','/Madden12/FacebookConnect/LogIn/']);
    }

	this.getUserData = function(){
		//console.log("SlotCars::getUserData");
		FB.api('/me', this.userDataHandler);
	}

	this.getUserData = function(){
		//console.log("SlotCars::getUserData");
		FB.api('/me', this.userDataHandler);
	}

	this.userDataHandler = function(response){
		//console.log("SlotCars::userDataHandler", response);

		if(!response.name){
			self.authenticated = false;
			self.getFlash().userDataHandler(false);
		} else {
			response.token = TOKEN;
			response.session = self.session;
			response.session.toString = self.JSON.serialize;
			//response.location.toString = self.JSON.serialize;
			response.action = "createUser";

			new Ajax({
				path: self.paths.apiPath,
				method: "POST",
				params: response,
				onComplete: self.userUpdateHandler
			});
		}
	}
    this.shareStory = function(p_teams){
    	//console.log("SlotCars::createScore", time, trackId, userId, driverId, bestLap);

    	// Yes, I understand that assigning the week this way
    	// is hacky and bad. I'm in a hurry okay? Will fix it later.
        // var week = track;
    	var img;
    	
    	var desc = (
    		"I just visited Doritos® Change the Game and unlocked "+
            "1 out of 32 Prima Team Guides for EA SPORTS Madden NFL 12."+ 
            "Grab a bag of Doritos® for a code to unlock some of your own." 
            );

    	img = "http://doritoschangethegame.com/images/fb_icon.jpg";

    	desc = desc.replace("{{ teams }}", p_teams);
    	
    	// Share prompt
    	FB.ui({
    		method: 'stream.publish',
    		message: desc,

            attachment: {
               name: 'Doritos&reg; Presents: Change the Game',
               description: 'Grab a bag of Doritos® for a code to unlock some of your own.',
               href: "http://doritoschangethegame.com/",
               media: [{
                   type: 'image',
                   src: img,
                   href: 'http://doritoschangethegame.com/'
               }]
           },

    		action_links: [{
    			text: 'Grab a bag of Doritos® for a code to unlock some of your own.', 
    			href: "http://doritoschangethegame.com/"
    		}],

    		user_message_prompt: 'Share your unlocked Prima\'s'
    	},

    	function(response) {
            // if (response && response.post_id) {
            //   alert('Post was published.');
            // } else {
            //   alert('Post was not published.');
            // }
        })
    }


	this.logoutHandler = function(response){
		//console.log("SlotCars::logoutHandler", response);
		self.authenticated = false;
	}

	this.__construct__();
}


/* END Facebook */

