
/*
 * API key, this should be initialized before any another function in this file is called.
 */
var is_initialized = false;
window.api_key = "7f50e70430740deebc0e20a0d0a2b3b8";

function FBLogOut() {
    FB.Connect.logout(function() {
        document.location.href = 'http://www.shopr.com/scripts/logout.aspx';
    });
}

/*
 * Ensure Facebook app is initialized and call callback afterward
 *
 */
function Facebook_init(callback) {
  if(!window.api_key) {
    window.alert("api_key is not set");
  }

  if(window.is_initialized) {
    callback();
  } else {
     try {
        FB_RequireFeatures(["XFBML"], function() {
            //FB.FBDebug.logLevel = 4;
            //FB.FBDebug.isEnabled = true;
            FB.init(window.api_key, "/social/xd_receiver.htm");

            window.is_initialized = true;
            callback();
          });
      } catch(err) {}
  }
}

/*
 * @param already_logged_into_facebook  reports whether the server thinks the user
 *                                      is logged in, based on their cookies
 *
 */
//function facebook_onload(already_logged_into_facebook) {
//  // user state is either: has a session, or does not.
//    // if the state has changed, detect that and reload.
//    Facebook_init(function() {
//        FB.Facebook.get_sessionState().waitUntilReady(function(session) {
//            var is_now_logged_into_facebook = session ? true : false;
//            var fbu = FB.Facebook.apiClient.get_session() ? FB.Facebook.apiClient.get_session().uid : 0;


//            alert('waitUntilReady callback for get sessionState, is_now_logged_in as ' + is_now_logged_into_facebook + ' and fbu is ' + fbu);
//            
//            // if the new state is the same as the old (i.e., nothing changed)
//            // then do nothing
//            if (is_now_logged_into_facebook == already_logged_into_facebook) {
//                return;
//            }

//            // otherwise, refresh to pick up the state change
//            refresh_page();
//        });
//    });
//}

function refresh_page() {
    window.location = '/my';
}


function facebook_linkaccount() {
    Facebook_init(function() {
        FB.Facebook.get_sessionState().waitUntilReady(function() {
            var user = FB.Facebook.apiClient.get_session() ? FB.Facebook.apiClient.get_session().uid : null;

            // probably should give some indication of failure to the user
            if (!user) {
                return;
            }
            facebook_get_all_permissions();
            //updateConnection();
        });
    });
}

function facebook_get_all_permissions() {
    facebook_prompt_permission('offline_access', function(accepted) {
        //facebook_prompt_permission('publish_stream', function(accepted) {
            
            updateConnection();
        //});
    });
 }

 function updateConnection() {
    window.location.href = 'http://www.shopr.com/social/fbconnected.aspx?redir=true';
}
function updateSignin() {

    jQuery.ajaxDotNet(window.ShoprService + "LoginFromFB",
    {
        data: {},
        success: function(o) {
            if (o != null) {
                //0=loggedin
                //1=Did not log into facebook
                //2=no shopr account
                if (o.d == 0) {
                    window.location.href = 'http://www.shopr.com/my';
                }
                else if (o.d == 1) {
                    alert('Error in Facebook login.');
                }
                else if (o.d == 2) {
                    displayNoShoprAccount();
                }
            }
            else {
            }
        },
        error: onCommonError
    });
    
}

function loginlink() {
    window.location.href = 'http://www.shopr.com/my?new=true';
}

function displayNoShoprAccount() {
//    jQuery.ajaxDotNet(window.ShoprService + "GetSendToControl",
//    {
//        data: { pType: typeid, pRecID: recid, pProjID: projid, pMembers: arrSelectedUsers, pSelectedUserName: singleSelectedUser || "[none]" },
//        success: function(o) {
//            if (o != null) {

//                if (typeid == INLINE) {
//                    jQuery('#userselectbox').html(o.d);
//                    jQuery('#userselectbox').html(o.d).slideDown(100);
//                }
//                else {
    //                    jQuery.facebox.settings.width = 700;
    var source = "http://www.shopr.com/scripts/newuser/createfromfacebook.aspx";
    jQuery.facebox("<iframe width='900' height='505' frameborder='0' scrolling='no' allowtransparency='true' src='" + source + "'></iframe>");
//                }
//            }
//        },
//        error: onCommonError
//    });

}

function facebook_prompt_permission(permission, callbackFunc) {
    Facebook_init(function() {
        try {
            //check is user already granted for this permission or not
            //FB.Facebook.apiClient.users_hasAppPermission(permission, function(result) {
                //alert('here21');
                // prompt offline permission
                //if (result == 0) {
                // render the permission dialog
                FB.Connect.showPermissionDialog(permission, callbackFunc);
                //} else {
                //   alert('user has ' + permission + ' permissions already.');
                //    // permission already granted.
                //    callbackFunc(true);
                //}
            //});
        } catch (e) { };
    });
}

/*
 * Show the feed form. This would be typically called in response to the
 * onclick handler of a "Publish" button, or in the onload event after
 * the user submits a form with info that should be published.
 *
 */
function facebook_publish_feed_story(form_bundle_id, template_data) {
  // Load the feed form
    Facebook_init(function() {
          FB.Connect.showFeedDialog(form_bundle_id, template_data);
          //FB.Connect.showFeedDialog(form_bundle_id, template_data, null, null, FB.FeedStorySize.shortStory, FB.RequireConnect.promptConnect);

      // hide the "Loading feed story ..." div
      ge('feed_loading').style.visibility = "hidden";
  });
}

/*
 * If a user is not connected, then the checkbox that says "Publish To Facebook"
 * is hidden in the "add run" form.
 *
 * This function detects whether the user is logged into facebook but just
 * not connected, and shows the checkbox if that's true.
 */
function facebook_show_feed_checkbox() {
    Facebook_init(function() {
      FB.Connect.get_status().waitUntilReady(function(status) {
          if (status != FB.ConnectState.userNotLoggedIn) {
            // If the user is currently logged into Facebook, but has not
            // authorized the app, then go ahead and show them the feed dialog + upsell
            checkbox = ge('publish_fb_checkbox');
            if (checkbox) {
              checkbox.style.visibility = "visible";
            }
          }
        });
    });
}

function wizarddone() {
    jQuery().trigger('close.facebox')
    jQuery().trigger('closeExtra.facebox');
}

function wizardfinished() {
    jQuery(document).ready(function() {
        setTimeout(function() {
            jQuery().unbind('closeExtra.facebox');
            var source = "http://www.shopr.com/scripts/newuser/bookmark.aspx";
            jQuery.facebox.settings.closeImage = "/images/plugins/facebox/closelabel.gif";
            jQuery.facebox.settings.modal = false;
            jQuery.facebox("<iframe width='940' height='625' frameborder='0' scrolling='no' allowtransparency='true' src='" + source + "'></iframe>");
        }, 2000);
    }); 
}

function showmynewmember() {
    jQuery(document).ready(function() {
        setTimeout(function() {
            var source = "http://www.shopr.com/scripts/newuser/personalinfo.aspx";
            jQuery.facebox.settings.modal = true;
            jQuery.facebox.settings.closeImage = "/images/plugins/facebox/closelabelx.gif";
            jQuery.facebox("<iframe width='900' height='555' frameborder='0' scrolling='no' allowtransparency='true' src='" + source + "'></iframe>");

//            jQuery().bind('closeExtra.facebox', function() {
//                wizardfinished();
//            });
        }, 2000);
    });

}