
//<script>
var WIAN = (function($) { 
    $.fn.privateData =  {
                        lastActionStatus:{
                                    func:null,
                                    funcData:null,      
                
                        },
                        twitter:{ uid:null,
                                 loginState:null,
                                 accessToken:null,
                                 }, 
                        fbInfo:{ uid:null,
                                 loginState:"unknown",
                                 accessToken:null,
                               }, 
                        wian:{  uid:null,
                                loginState:"unknown",
                                sessionID:null,
                                cookieInfo:{wiansessid:null,
                                            wianuid:null },
                             },
                        domainInfo:{domain:null,
                                    port:null,
                                    protocol:null,
                                   },
                        fbPostGroupings:{   1:{ type:"Big Five",   
                                                text:"High five for me! Check out the 'Big 5' names that I just read, then high five yourself.",
                                                link:"http://www.whatsinaname.com/#/Big5", 
                                                name:"Whatsinaname Big 5 content"
                                            },
                                            2:{ type:"True False", 
                                                text:"Check out whatsinaname.com for the answer to this!",
                                                link:"http://whatsinaname.com/#/Quiz", 
                                                name:'Whatsinaname.com Quiz'
                                              },
                                            3:{ type:"Poll",       
                                                text:"I just took this poll on whatsinaname.com.  See what you — and everybody else — think about it",
                                                link:"http://www.whatsinaname.com/#/Polls" , 
                                                name:'Whatsinaname Poll'
                                              },
                                            6:{ type:"video",
                                                text:"Check out this fascinating video from whatsinaname.com",
                                                link:"http://www.whatsinaname.com/#/Videos", 
                                                name:"Whatsinaname Video"
                                              },
                                       },
                        };

        
    $.fn.hideIt = function(){
        $("#fbFloat").hide("slow");
    };
    $.fn.showIt=function(){
        //$("#fbFloat").show("slow");
        $.colorbox({height:500, width:550, inline:true, href:"#fbRegistrationBox"});
    };

    $.fn.checkFBPerms =function(userID,callback){
        var query = FB.Data.query('select publish_stream,read_stream from permissions where uid={0}',userID);
        query.wait(function(rows) {
            JSON.stringify(rows);
            if(rows[0].publish_stream == 1 && rows[0].read_stream == 1) {
                callback(true);
            } 
            else {
                callback(false);
            }
        });
    };

    $.fn.inviteFacebookFriends=function(){
        $(this).getLoggedInStatus();
        if ($(this).privateData.fbInfo.uid == null){
            FB.login(function(response){
                if (response.authResponse){
                    $(this).privateData.fbInfo.uid = response.authResponse.userID;        
                    $(this).privateData.fbInfo.accessToken = response.authResponse.accessToken;
                    //$(this).registerFBCredentials();
                    $(this).inviteFacebookFriends();
                }
            });
        }
        else{
            FB.ui({ method: 'apprequests', message: 'Come check out all the fun in whats in a name :-)'},
                                            function(response){
                                                $(this).privateData.lastActionStatus.func='FB.UI.apprequests';
                                                $(this).privateData.lastActionStatus.funcData=response;
                                            });
        }
    };

    $.fn.registerFBCredentials = function(){
        $(this).getLoggedInStatus();
        //console.log(JSON.stringify($(this).privateData));
        if($(this).privateData.wian.uid != null){ 
            if ($(this).privateData.fbInfo.uid != null){
                pkg = { session_id: $(this).privateData.wian.wiansessid,
                        user_id:    $(this).privateData.wian.wianuid,
                        platform_id:"1",
                        platform_user_id:$(this).privateData.fbInfo.uid
                      };
                $.ajax({    url: "http://www.whatsinaname.com/rest/friendsService/registerPlatformUserId",
                            type:"POST",
                            data:JSON.stringify(pkg),
                            contentType:"application/json; charset=utf-8",
                            dataType:"json",
                            mimeType:"application/json",
                            success:function (response){ 
                                            $(this).privateData.lastActionStatus.func="ajax:+http://www.whatsinaname.com/rest/friendsService/registerPlatformUserId";
                                            $(this).privateData.lastActionStatus.funcData=response;
                            }
                      });
            }
        }
    };

    $.fn.getFacebookFriends=function(){
        $(this).getLoggedInStatus();
        if ($(this).privateData.fbInfo.uid == null){
            //console.log(' ... already logged in but here?');
            FB.login(function(response){
                if (response.authResponse){        
                    $(this).privateData.fbInfo.uid = response.authResponse.userID;        
                    $(this).privateData.fbInfo.accessToken = response.authResponse.accessToken;
                    $(this).registerFBCredentials();
                    $(this).getFacebookFriends();
                }
                else{
                //authentication failed
                    ;
                }
            });
        }
        if ($(this).privateData.fbInfo.uid != null){
            FB.api('/me/friends',function(response){
                if (response.data){
                    $.ajax({    url: "http://www.whatsinaname.com/rest/friendsService/registerFriends",
                                type:"POST",
                                data: JSON.stringify({ user_id:$(this).privateData.wian.uid,
                                        session_id:$(this).privateData.wian.sessionID,
                                        facebook_id:$(this).privateData.fbInfo.uid,
                                        friends:response.data
                                    }),
                                contentType:"application/json; charset=utf-8",
                                dataType:"json",
                                mimeType:"application/json",
                                success:function (response){ 
                                                $(this).privateData.lastActionStatus.func="ajax:+http://www.whatsinaname.com/rest/friendsService/registerFriends";
                                                $(this).privateData.lastActionStatus.funcData=response;
                                                if (response.status == "OK"){
                                                    $(this).callToActionscript({status:"success",message:"_getFacebookFriends"});
                                                }
                                                else{
                                                    $(this).callToActionscript({status:"failed",message:"_getFacebookFriends"});
                                                }
 
                                }
                            });
                        }
                        else{ 
                            $(this).privateData.lastActionStatus.func='FB.api:/me/friends';
                            $(this).privateData.lastActionStatus.funcData=response;
                        }
            });
        }
    };

    $.fn.shareWithFacebook=function(object_type,object_id){
        FB.api('/me/feed', 'post',
                {
                    message     : $(this).privateData.fbPostGroupings[object_type.toString()].text,
                    link        : $(this).privateData.fbPostGroupings[object_type.toString()].link+"?id="+object_id,
                    picture     : 'http://www.whatsinaname.com/images/WIAN_Logo_Small.png',
                    name        :  $(this).privateData.fbPostGroupings[object_type.toString()].name,
                    description : 'Explore the history of names like never before! Activities, quizzes, and games -- a name exploration adventure!'

                },
                function(response) {
                    //console.log('Post to FB returned'+JSON.stringify(response));
                    if (!response || response.error) {
                        //console.log('in fail route ... something was not right');
                        var doLogin=true;
                        $(this).getLoggedInStatus();
                        if ($(this).privateData.fbInfo.uid != null){
                            $(this).checkFBPerms($(this).privateData.fbInfo.uid, function(isWorking){ 
                                                                                    if (isWorking){ doLogin=false; }
                                                                                    else{ doLogin=true;}});    
                        }

                        if (doLogin){
                            FB.login(function(response){
                                //console.log('login result was ' + JSON.stringify(response));
                                if (response.status != null){
                                    //console.log('lets try again');
                                    $(this).registerFBCredentials();
                                    $(this).shareWithFacebook(object_type,object_id);
                                }
                                else{
                                    //console.log("logged in with the right perms failed");
                                    $(this).callToActionscript({status:"Failed",message:"Unable to get permission to post"});
                                }
                            },{scope:"publish_stream,publish_actions"});
                        }
                        else{
                            //console.log('in fail mode ... no login required');
                            $(this).callToActionscript({status:"Success",message:response.id});
                        }
                    } else {
                        //console.log('in success route');
                        //console.log('Post ID: ' + response.id+' should be calling success actionscript');
                        $(this).callToActionscript({status:"Success",message:response.id});
                    }
                });
    };

    $.fn.getLoggedInStatus=function(){
        //hack to get FB to emit an event we are listening on
        FB.getLoginStatus();
        //then again to get the status
        FB.getLoginStatus(function(response){
            $(this).privateData.fbInfo.loginState = response.status;
            if (response.authResponse){
                $(this).privateData.fbInfo.uid = response.authResponse.userID;        
                $(this).privateData.fbInfo.accessToken = response.authResponse.accessToken;
                if ($(this).privateData.wian.uid != null){
                    if($.cookie('wianHasFacebook' == null)){ 
                        $.ajax({    url: "http://www.whatsinaname.com/rest/friendsService/registerPlatformUserId",
                                    type:"POST",
                                    data: JSON.stringify({ user_id:$(this).privateData.wian.uid,
                                            session_id:$(this).privateData.wian.sessionID,
                                            platform_id:'1',
                                            platform_user_id:$(this).privateData.fbInfo.uid
                                        }),
                                    contentType:"application/json; charset=utf-8",
                                    dataType:"json",
                                    mimeType:"application/json",
                                    success:function (response){
                                                    $(this).privateData.lastActionStatus.func="ajax:+http://www.whatsinaname.com/rest/friendsService/registerPlatformUserId";
                                                    $(this).privateData.lastActionStatus.funcData=response;
                                    }
                               });
                    }
                }
            }
            else{
                $(this).privateData.fbInfo.uid = null;
                $(this).privateData.fbInfo.accessToken = null;
            }
        });

        if (typeof $.cookie("wiansessid") == "string"){
            $(this).privateData.wian.sessionID = $.cookie("wiansessid");
            $(this).privateData.wian.loginState = 'unknown';
        }
        if (typeof $.cookie("wianuid") == "string"){
            $(this).privateData.wian.uid = $.cookie("wianuid");
            $(this).privateData.wian.loginState = 'connected';
        }
    };

    $.fn.placeIt =function(){
        $("#fbFloat").css.top = $("#content").offset().top -20;
        setTimeout(function(){
            $("#fbFloat").placeIt();
        },10);
    };
	
	$.fn.showVideo = function(_vid){
		var flashvars = {},
        flashparams = {wmode:"opaque",bgcolor:"#000000"},
        flashattributes = {};
        swfobject.embedSWF("http://www.globaltv.com/video/swf/EmbedPlayer.swf?player.width=614&player.height=346&player.overlayImageUrl=&pid=" + _vid, "video", "100%", "100%", "9.0.0","/swf/expressInstall.swf",flashvars,flashparams,flashattributes);
		$.colorbox({width:664, height:446, inline:true, href:"#video"});
	}
	
	$.fn.getFlashMovie = function (_movieName) {
		var isIE = navigator.appName.indexOf("Microsoft") != -1;
		return (isIE) ? window[_movieName] : document[_movieName];
	}
	
	$.fn.callToActionscript = function (_status) {
		 $(this).getFlashMovie("content").getStatusUpdate(_status);
	}

    return {           
        doShowIt: function(){ $(this).showIt(); },
        doPlaceIt:function(){ $(this).placeIt(); },
        doHideIt: function(){ $(this).hideIt(); },
        doFacebookRegister: function(){$(this).showIt();},
        doGetDomainInfo: function(){return {domain:document.domain,protocol:document.location.protocol};},
        doGetLoginStatusAsString: function(){ 
                                        $(this).getLoggedInStatus();
                                        var myWian=$(this).privateData.wian;
                                        var myFB=$(this).privateData.fbInfo;
                                        return JSON.stringify({wian:myWian , fbInfo:myFB});
                                    },
        doGetLoginStatus: function(){ 
                                        $(this).getLoggedInStatus();
                                        var myWian=$(this).privateData.wian;
                                        var myFB=$(this).privateData.fbInfo;
                                        return {wian:myWian , fbInfo:myFB};
                                    },
        doPostToFB : function(object_type,object_id){
                                    $(this).shareWithFacebook(object_type,object_id);
                     },
        doRegisterFBCredentials : function(){ $(this).registerFBCredentials(); },
        doGetFBFriends : function(){ $(this).getFacebookFriends(); },
        doInviteFBFriends : function(){ $(this).inviteFacebookFriends(); },

		doShowVideo: function(_vid){$(this).showVideo(_vid);},
		doReturnStatus: function(_status){$(this).callToActionscript(_status);}
		};
    // Pass in jQuery.
})(jQuery);

