function showBlockUI(msg) {
    $.blockUI({ message: '<div class="uiBlockPrompt saving"><span>'+msg+'</span></div>' });
    $('.blockUI').css('cursor','default');
    $('.blockUI').css('z-index','9999998');
    $('.blockUI.blockMsg').css('z-index','9999999');
}

// function fbYaptaAuthorize(redir,returnTo) {
//     //FB.Connect.showPermissionDialog("publish_stream", function(x){alert(x);}, false, null);
//     markUserAsConnected();
//     if (redir) {
//         var url = redir+'?fb=true';
//         if (returnTo) {
//             url += '&returnTo='+escape(returnTo);
//         }
//         document.location = url
//     } else {
//         showBlockUI('Reloading');
//         document.location.reload(true);
//     }
// }


// @note: not using for now
// function logoutFacebook() {
//     try {
//         // for now, just call FB's logout
//         FB.Connect.logout();
//     } catch(err){}
// }

// @note: not using for now
// function insertFacebookProfileElem(elemId) {
//     var fbuid = FB.Connect.get_loggedInUser();
//     if (fbuid) {
//         html = '<fb:profile-pic uid="'+fbuid+
//             '" width="16" height="16" facebook-logo="false"></fb:profile-pic>'+
//             '<img src="/images/fb-favicon-sm.gif" /><fb:name uid="'+
//             fbuid+'" useyou="false"></fb:name>';
//         $ ('#'+elemId).html(html);
//         FB.XFBML.Host.parseDomTree();
//     }
// }


// @note: not using for now
// function setupFacebookNavElem(elemId,size,length,background,copy) {
//     // @note:  once we know user is logged in, we could use 
//     //       FB.Connect.ifUserConnected(function(){alert('connected');},function(){alert('not');});
//     //     to carry out action based on conencted status; (we could also just use result
//     //     returned by get_status()....)
//     // @note: not displaying for now
//     FB.ensureInit(function() {
//            FB.Connect.get_status().waitUntilReady(function(status) {
//                    var html = '';
//                    if (status == FB.ConnectState.connected) {
//                       insertFacebookProfileElem(elemId);
//                    } else {
//                        // For now, don't show Connect button
//                        //html = '<fb:login-button size="'+size+
//                        //    '" length="'+length+'" background="'+background+
//                        //    '" onlogin="fbYaptaAuthorize(null,null);"></fb:login-button>'+copy;
//                        //$ ('#'+elemId).html(html);
//                        //FB.XFBML.Host.parseDomTree();
//                    }
//                });
//       });
// }

function onConnected(user_id) {
    //alert('onConnected:  User '+user_id+'is logged in');
}

function onNotConnected() {
    //alert('onNotConnected: User not logged in');
}



/* Share methods */

// function setupShare(shareContentFuncName,uaId,elemId,argsStr) {
//     //FB.ensureInit(function() {
//             //FB.Connect.get_status().waitUntilReady(function(status) {
//                     //argsjson=JSON.stringify(args).replace(/\"/g,'\'');
//                     html = '<span class="shareLink"' + //((status != FB.ConnectState.connected) ? (' style="display: none;"') : (''))+
//                         '><img src="/images/fb-favicon-sm.gif" />'+
//                         '<a href="javascript: void(0)" onclick="share('+
//                         shareContentFuncName+','+uaId+',\''+elemId+'\','+
//                         argsStr+');">Share with my Facebook friends</a></span>';
//                     //if (status != FB.ConnectState.connected) {
//                     //    html += '<span class="connectLink"><fb:login-button size="small" length="short" onlogin="connectAndShare('+
//                     //        shareContentFuncName+','+uaId+',\''+elemId+'\','+
//                     //        argsStr+');"></fb:login-button>Share with my Facebook friends</span>';
//                     //}
//                     $('#'+elemId+' .fbConnectShareLink').html(html);
//                     $('#'+elemId+' .fbShare').show();
//                     //FB.XFBML.Host.parseDomTree();
//               //});
//      //});
// }

// function connectAndShare(shareContentFunc,uaId,elemId,args) {
//        //This should only have been called from within an ensureInit, and 
//        //it should only be called once user connects, so don't need calls to 
//        //ensureInit and get_status
// //     FB.ensureInit(function() {
// //             FB.Connect.get_status().waitUntilReady(function(status) {
// //                     if (status == FB.ConnectState.connected) {
//                         // @todo: pass share link html already formed in setupShare
//                         //alert('logged in');
//                         $('.connectLink').hide();
//                         $('.shareLink').show();
//                         insertFacebookProfileElem('fbConnectNav');
//                         share(shareContentFunc,uaId,elemId,args);
// //                     } //else, do nothing
// //                 });
// //         });
// }

function share(shareContentFunc,uaId,elemId,args,baseId,uaType) {
    FB.ensureInit(function() {
            //FB.Connect.get_status().waitUntilReady(function(status) {
            var content = shareContentFunc(args);
            var callback = function (postId,exc,data){
                // if user clicks 'skip' (skipping post), then postId is 'null' (i.e. string
                // representation of null); if the user posts, then postId should be non-'null'
                //alert('callback: '+postId+','+exc+','+data);
                
                // user must be connected by this point, so if fb setting nav profile element is 
                // missing (which would be the case if user just connected), then creat it
                // @note: not showing for now
                //if (''==$('#fbConnectNav').html()) { //if (!$('#fbConnectNav').html()) {
                //    insertFacebookProfileElem('fbConnectNav');
                //}
                // if user posted, then we want to delete the user action and hide the alert
                if ('null' != postId) {
                    //alert(postId);
                    //alert('null != postId:  '+(null != postId));
                    if (uaId) {
                        $.ajax({url: getUrl='/ajax/user/userAction/unset/?uaid=' + uaId + '&actedOn=true',cache: false});
                    } 
                    if (baseId && uaType) {
                        $.ajax({url: getUrl='/ajax/user/userAction/set/?actedon=true&delete=true&baseid='+baseId+'&uatype='+uaType,cache: false});
                    }
                    if (elemId) {
                        $('#'+elemId).slideUp();
                    }
                    // though user hasn't really 'connected' to FB, for our purposes, mark them
                    // as having connected (since we want to keep track of who has used the FB feature)
                    // @note: user will be marked only once they've successfully posted
                    markUserAsConnected();
                } else if (exc) {
                    /* display error message? */
                }
            };
            FB.Connect.streamPublish(content.usermsg,content.attach,content.actionLinks,null,null,callback,false);
            //});
        });
}


function shareNewTripContent(args) {
    return { 'attach': {'description':'I\'m planning a trip to '+args.destCity+' in '+args.monthStr+', '+args.yearStr+' on Yapta'},
            'actionLinks': [{ "text": "Plan trips on Yapta", "href": "http://www.yapta.com"}],
                'usermsg' : ''};
}

function sharePurchasedFlightContent(args) {
    return { 'attach': {'description':'I saved '+args.percentSavings+'% on a flight to '+args.destCity+' by tracking price drops with Yapta'}, 
            'actionLinks': [{ "text": "Track price drops on Yapta", "href": "http://www.yapta.com"}],
                'usermsg' : ''};
}

function shareRefundContent(args) {
    return { 'attach' : {'description':'I found a $'+args.refund+' refund by tracking price drops on a purchased flight with Yapta'}, 
            'actionLinks': [{ "text": "Track price drops on Yapta", "href": "http://www.yapta.com"}],
                'usermsg' : ''};
}



/* helper methods to update user table values */

function dontShowAgain(elemId) { //,settingKey) {
    showBlockUI('Updating your settings.');
    changeSetting('all',  //settingKey,
                  'false',
                  function(msg){$('#'+elemId).slideUp();$.unblockUI();},
                  function(msg){ /* todo: show error msg*/ $.unblockUI()});
}

function changeSetting(key,value,successFunc) {
    $.ajax({
            type: "POST",
            url: "/ajax/fbconnect/settings/",
            data: 'key='+key+'&value='+value+'&unsetall=true',
            success: successFunc
            //error: function(msg){},
        });
}

function markUserAsConnected() {
    $.ajax({
            type: "POST",
            url: "/ajax/fbconnect/connected/"
            //success: function(msg){},
            //error: function(msg){},
        });
}








// function shareNewTripUsingShowFeedDialogue(templateId,uaId,elemId,destCity,monthStr,yearStr) {
//     FB.ensureInit(function() {
//             var callback_nt = function(postId,exc,data){
//                 // this call back will only get invoked if the user connects, thus initiating
//                 // the feed dialogue; if user connects but then clicks 'skip' (skipping post), 
//                 // then postId is 'null' (i.e. string representation of null); if the user posts, 
//                 // then postId should be non-'null'
//                 //alert('callback_nt: '+postId+','+exc+','+data);
                
//                 // user must be connected by this point, so if fb setting nav profile element is 
//                 // missing (which would be the case if user just connected), then creat it
//                 if (''==$('#fbConnectNav').html()) { //if (!$('#fbConnectNav').html()) {
//                     insertFacebookProfileElem('fbConnectNav');
//                 }
//                 // if user posted, then we want to delete the user action and hide the alert
//                 if ('null' != postId) {
//                     //alert('null != postId:  '+(null != postId));
//                     $.ajax({url: getUrl='/ajax/user/userAction/?uaid=' + uaId + '&actedOn=true',cache: false});
//                     $('#'+elemId).slideUp();
//                 } else if (exc) {
//                     /* display error message? */
//                 }
//             };
//             var templateData = {"city":destCity,"month":monthStr,"year":yearStr,"yapta-url":"http://www.yapta.com"};
//             FB.Connect.showFeedDialog(templateId, templateData, null, null, null, 
//                                       FB.RequireConnect.promptConnect, callback_nt, null, null);
//         });
// }
