<!--
var apiKey = 0;
var FBconnected = false;
var publishing = false;
var publishData = {};

var publishCount = 0;
var published = 0;

var flash = "";


var fbData = [];
var fbFirstName = "";
var extendedPublish = false;

/**
 * Initialize Facebook API
 */
function FBInit(callback) {
    var host = window.location.hostname;
    
    if(host == 'stimorol.friendlydot.dk') {
        // Test (Friendlydot.dk)
        window.apiKey = "998a875c3faa0c5e7068b0b7a7d8df94";
    }else {
        // LIVE (sensesparty.dk)
        window.apiKey = "ee381a901e8b4ab4d4466417d7a9d7ec";
    }

    try {
        if(FB != false) {
            FB.init(apiKey, "xd_receiver.htm");
            /*FB.ensureInit(function() {
                FB.Connect.get_status().waitUntilReady( function( status ) {
                    switch ( status ) {
                        case FB.ConnectState.connected:
                            onConnected(callback);
                            break;
                        case FB.ConnectState.appNotAuthorized:
                        case FB.ConnectState.userNotLoggedIn:
                            onNotConnected(callback);
                    }
                });
            });*/
        }else {
            // When Facebook isn't initalized properly.
            $("#flashInner").show();
            alert("Der skete en fejl. Prøv at logge på igen.");
        }
    }catch(error) {
        alert("Der skete en fejl. Reload siden og prøv venligst igen. Vi beklager.");
        window.FBinitialized = false;
        return false;
    }

    try {
        callback();
    }catch(err) {
        // Do nothing. Eliminates ie error...
    }
}

function FBLogout() {
    $.post('gateway.php', {action:'logout'});
    FB.Connect.logout(function(){
        trackFBConnectLogout();
        window.location.reload();
    });
}

/**
 * Called when user isn't connected to Facebook.
 */
function onNotConnected(callback){
    $("#flashInner").hide();
    $("#loader").show();
    window.FBconnected = false;

    
    trackFBConnectButton();

    try {
        FB.ensureInit(function() {
            FB.Connect.requireSession(function() {
                onConnected(callback);
            }, function(){
                // This is called if the user skips/closes the Facebook Connect prompt
                trackFBConnectCancel();
                $("#loader").hide();
                $("#flashInner").show();
                alert("Du skal forbinde til Facebook for at kunne se dette site.");
            });
        });
    }catch(err) {
        alert("Der skete en fejl. Reload siden og prøv venligst igen. Vi beklager.");
        return false;
    }
}

/**
 * Called when user is connected to Facebook.
 */
function onConnected(callback){
    window.fbData = false;
    try {
        //FB.ensureInit(function() {
            window.fbData = FB.Facebook.apiClient.get_session();
        //});
    }catch(err) {
        alert("Der skete en fejl ved hentning af brugerdata. Tryk F5 i din browser og prøv venligst igen.");
    }

    // Check if data was fetched correctly
    if(window.fbData == false) {
        alert("Der skete en fejl. Reload siden og prøv venligst igen. Vi beklager.");
        return false;
    }

    FB.Facebook.apiClient.users_hasAppPermission("publish_stream", function(result) {
        if(result == '0') {
            FB.Connect.showPermissionDialog("publish_stream", function(data) {
                if(data == "publish_stream") {
                    extendedPublish = true;
                }
                
                fillData(callback);
            });
        }else {
            extendedPublish = true;
            fillData(callback);
        }
    })
}

function fillData(callback) {
    window.FBconnected = true;

    try {
        FB.Facebook.apiClient.users_getInfo(window.fbData.uid, ['first_name', 'last_name', 'birthday_date', 'pic_square_with_logo'], function(data){
            data = data[0];

            // Check for a profile picture.
            if(data.pic_square_with_logo == '' || data.pic_square_with_logo == null) {
                data.pic_square_with_logo = 'http://static.ak.fbcdn.net/pics/q_silhouette.gif';
            }

            $("#loggedInUser").html(''+
                '<div id="pendingInvites" class="fl">'+
                    '<a href="invites.php?redir=true">'+
                        '<img src="images/mailOff.png" style="margin-top: 6px; vertical-align: -15%;" border="0" id="mailIcon" alt="Ventende invitationer" title="Ventende invitationer">'+
                    '</a>&nbsp;'+
                    '<span id="invitesCounter">0</span>&nbsp;'+
                '</div>'+
                '<div class="fl">'+
                    '<img src="'+data.pic_square_with_logo+'" width="25" height="25" style="vertical-align: middle;" />&nbsp;'+data.first_name+' '+data.last_name+'&nbsp;&nbsp;&nbsp;<a href="" onclick="FBLogout(); return false;"><img src="images/btn_facebookLogout.png" border="0" style="vertical-align: middle;" /></a>'+
                '</div>');

            checkInvites();

            $.post("gateway.php", {action:'storeAge', birthday: data.birthday_date});

            callback();
        });
    }catch(err) {
        alert("Der skete en fejl. Reload siden og prøv venligst igen. Vi beklager.");
        return false;
    }
}


/**
 * Require publish stream access from user.
 */
function requirePermission() {
    FB.Connect.showPermissionDialog('publish_stream', function(result) {
        result = (result == "publish_stream")

        window.flash.permissionCallback(result);
    });
}


/**
 * Show the friend selector overlay.
 **/
function loadFriends() {
    var uid = fbData.uid;
    FB.XFBML.Host.autoParseDomTree = false;
    
    // Causes weird page reload. So have disabled it (08/01-2010)
    //FB_RequireFeatures(["CanvasUtil"], function(){FB.CanvasClient.startTimerToSizeToContent();});

    var api = FB.Facebook.apiClient;

    api.fql_query("SELECT uid, first_name, last_name FROM user WHERE  uid IN (SELECT uid2 FROM friend WHERE uid1 = "+uid+") order by first_name", function(result, ex) {

        data = "<table cellspacing='0' cellpadding='10' style='width: 100%;'>";
        for (i=0;i<result.length;i++)
        {
            data += "<tr>"+
                        "<td width='1px'><input type='radio' value='"+result[i].uid+"' name='friend' id = 'friend"+result[i].uid+"' /></td>"+
                        "<td><label for='friend"+result[i].uid+"'>"+ result[i].first_name + " " + result[i].last_name+"</label></td>"+
                    "</tr>";
        }
        data +="</table>";
        $('#friends').html(data);
        $("#overlay").show();
        $("#friendSelector").fadeIn("slow");
    });
}


function getFriends() {
    FB.Facebook.apiClient.friends_get(new Array(), function(result, exception){
        //FB.FBDebug.dump(result, 'friendsResult from non-batch execution ');
    });
}

function getInfo(uid, callback, debug) {
    try{
        if(debug == true) {
            FB.Facebook.apiClient.users_getInfo(uid, ['first_name', 'last_name', 'pic_square'], function(data){console.debug(data);});
        }else {
            FB.Facebook.apiClient.users_getInfo(uid, ['first_name', 'last_name', 'pic_square'], function(data){callback(data);});
        }
    }catch(err) {
        console.debug(err);
    }
}

/**
 * Send Facebook notification to friends.
 * 
 * @friends String : A JS array of Facebook uids.
 * @callback String : A function name for a flash callback function.
 */
function sendNotifications(friends, callback) {
    try {
        var friendList = eval(friends);

        var message =  ' vil have dig med til sin STIMOROL Senses fest. <a href="http://sensesparty.dk/invites.php?u='+fbData.uid+'">Se invitationen her</a>';

        FB.Facebook.apiClient.notifications_send(friendList, message, callback);
    }catch(err) {
    }
}

function publishReturn(result) {
    if(result == false) {
        if(!window.publishing) {
            window.publishing = true;
            FB.Connect.streamPublish(window.publishData.text, window.publishData.attachment, window.publishData.actionLink, window.publishData.target, "Skriv noget...", function(result){
                $("#loader").hide();
                try {
                   if(result == 'null'){
                       window.flash[window.publishData.callback](false);
                   }else {
                       window.flash[window.publishData.callback](true);
                   }
                }catch(err) {
                    alert(err);
                }
            });
        }
    }else {
        window.published++;
        if(window.published == window.publishCount || window.published == 5) {
            $("#loader").hide();
            window.flash[window.publishData.callback](true);
        }else {
            // Send next wall post
            window.flashGateway.streamPublish(window.publishData.text, JSON.stringify(window.publishData.attachment), JSON.stringify(window.publishData.actionLink[0]), window.publishData.uids[window.published]);
        }
    }

}


/**
 * Publish to the Facebook stream.
 *
 *  uids: A list of up to 10 uids sent from the Flash
 */
function streamPublish(type, callback, target, images, uids) {
    window.publishing = false;
    window.publishCount = 0;
    window.published = 0;

    $("#loader").show();

    //var url = $.jqURL.strip().replace("#", "");

    var url = "http://sensesparty.dk/"

    var attachment = {};
    
    var actionLink = [];
    var text = "";
    var name = "";
    var clickTag = "";
    var page = '';

    var profileImages = eval(images);
    var imagesUrl = "";

    // This is done to ensure that the publish header doesn't say "Friend" when posting to own wall.
    if(target == fbData.uid){
        target = null;
    }

    $.each(profileImages, function(key, val) {

        // If we dont have a profile image, set the silhouette as default.
        if(val == "") {
            val = url+'images/silhouette.gif';
        }
        imagesUrl += "&"+val;
    });
    
    // Check which type of stream publish we are making.
    switch(type) {
        // Invite 10 friends
        case "invites":
            clickTag = url;

            attachment = {'media': [
                {'type':'flash',
                 'swfsrc': url+'swf/FlashAttachmentAS3.swf?'+clickTag+imagesUrl,
                 'imgsrc': url+'images/facebook/fallback_invite_130x100.jpg',
                 'width' : '130',
                 'height': '100',
                 'expanded_width': '460',
                 'expanded_height': '200',
                 'href':url}
            ]};

            $.post("gateway.php", {action:'getHash', uid: target, format:'json'}, function(hash){
                if(target == null) {
                    // Invite to own party.
                    text = "Vil du med til en fed STIMOROL Senses fest med mig og 200 af mine venner?";
                    actionLink = [{"text": "Join party", "href": url+"invites.php?u="+fbData.uid}];
                    page = 'FBPost_InviteToOwnParty';
                }else {
                    var uidsText = uids.replace(/"|\[|\]|'/g, "");
                    // Invite to a friends party.
                    text = "Jeg har inviteret mine venner til din STIMOROL Senses fest. Klik for at se hvem det er...";
                    actionLink = [{"text": "Accepter invitationer", "href": url+"accept.php?u="+uidsText+"&h="+hash}];
                    page = 'FBPost_InviteToFriendsParty';
                }
                uids = eval(uids);

                if(window.extendedPublish) {

                    // Saved for use in Flash callback in case of error...
                    window.publishData = {
                        text: text,
                        attachment: attachment,
                        actionLink: actionLink,
                        target: target,
                        callback: callback,
                        uids: uids
                    }

                    window.publishCount = uids.length;
                    
                    // Call flash gateway due to bug in Facebook Connect API
                    //for(var i = 0; i<uids.length && i<5; i++) {
                    window.flashGateway.streamPublish(text, JSON.stringify(attachment), JSON.stringify(actionLink[0]), uids[0]);
                    //}
                }else {
                    FB.Connect.streamPublish(text, attachment, actionLink, target, "Skriv noget...", function(result){
                        $("#loader").hide();
                        try {
                           if(result == 'null'){
                               window.flash[callback](false);
                           }else {
                               trackFBPublish(page);
                               // Notify friends about the invite;
                               //sendNotifications(uids, function returns() {
                                   window.flash[callback](true);
                               //});
                           }
                        }catch(err) {
                            alert(err);
                        }
                    });
                }
            });

            
            break;

        // Get invited to a friends party
        case "getInvited":

            FB.Facebook.apiClient.users_getInfo(target, ['first_name'], function(data){
                name = data[0].first_name;

                text = "Hej [NAME]. Jeg vil gerne med til dit STIMOROL Senses Party. Klik på linket for at tilføje mig til din gæsteliste. Jo flere, jo bedre - jo feeedere fest :-)";

                text = text.replace(/\[NAME\]/g, name);

                // Get the hash for the user we wanna get an invite from.
                $.post("gateway.php", {action:'getHash', uid: target, format:'json'}, function(hash){

                    // u = the user to invite, h = the hash of the user we wanna get an invite from.
                    actionLink = [{"text": "Ta' mig med!", "href": url+"accept.php?u="+fbData.uid+"&h="+hash}]; // Tilføj bruger automatisk og smid til kontrolpanel.

                    attachment = {'media': [
                        {'type':'image',
                         'src': url+'images/facebook/fallback_get_invited_90x90.jpg',
                         'width' : '90',
                         'height': '90',
                         'href':url+"accept.php?u="+fbData.uid+"&h="+hash}
                    ]};

                    FB.Connect.streamPublish(text, attachment, actionLink, target, "Skriv noget...", function(result){

                        if(result != 'null'){
                            page = 'FBPost_GetInvitedToFriendsParty';
                            trackFBPublish(page);
                            // User published to Facebook, so we create an invitation.
                            $.post("gateway.php", {action:'createInvite', target: target}, function(){
                                $("#loader").hide();
                            });
                        }else {
                            $("#loader").hide();
                        }
                    });
                });
            });
            break;

        // Remind a friend about your party
        case "reminder":
            FB.Facebook.apiClient.users_getInfo(target, ['first_name'], function(data){
                name = data[0].first_name;

                text = "[NAME]! Du må ikke gå glip af den fedeste fest. Jeg vil super gerne have du kommer så vi sammen kan sparke stemingen i vejret.";

                text = text.replace(/\[NAME\]/g, name);

                actionLink = [{"text": "Join party", "href": url+"invites.php?u="+fbData.uid}];

                attachment = {'media': [
                        {'type':'image',
                         'src': url+'images/facebook/fallback_reminder_90.jpg',
                         'width' : '90',
                         'height': '90',
                         'href':url+"invites.php?u="+fbData.uid}
                ]};

                FB.Connect.streamPublish(text, attachment, actionLink, target, "Skriv noget...", function(result){
                   $("#loader").hide();
                   try {
                       if(result == 'null'){
                            window.flash[callback](false);
                        }else {
                            page = 'FBPost_Reminder';
                            trackFBPublish(page);
                            window.flash[callback](true);
                        }
                    }catch(err) {
                        alert(err);
                    }
                });
            });

            break;

        // Get help from a friend to invite people to your party.
        case "getHelp":
            trackHelpMeButton();

            text = "Hjææææælp! Jeg mangler venner til mit STIMOROL Senses party. Det er min fest, og dine venner skal med. Inviter nu nu nu...";

            actionLink = [{"text": "Hjælp mig", "href": url+"index.php?u="+fbData.uid}]; // Fører til karrousel med ven som fokus...

            attachment = {'media': [
                        {'type':'image',
                         'src': url+'images/facebook/fallback_get_help_90x90.jpg',
                         'width' : '90',
                         'height': '90',
                         'href':url+"index.php?u="+fbData.uid}
            ]};

            FB.Connect.streamPublish(text, attachment, actionLink, target, "Skriv noget...", function(result){
                $("#loader").hide();
                if(result != 'null'){
                    page = 'FBPost_GetHelpFromFriend';
                    trackFBPublish(page);
                }
                callback();
            });

            break;

        // Accept an invite from a user and post to your wall about it...
        case "acceptInvite":
            text = "Jeg har accepteret en invitation til den fedeste STIMOROL Senses fest. Skal I med?";

            actionLink = [{"text": "STIMOROL Senses party", "href": url}];

            attachment = {'media': [
                        {'type':'image',
                         'src': url+'images/facebook/fallback_get_invited_90x90.jpg',
                         'width' : '90',
                         'height': '90',
                         'href':url}
            ]};

            FB.Connect.streamPublish(text, attachment, actionLink, target, "Skriv noget...", function(result){
                if(result != 'null'){
                    page = 'FBPost_InviteAccepted';
                    trackFBPublish(page);
                }
                $("#loader").hide();
                callback();
            });

            break;

        default:
            break;
    }
}
// -->
