    
var selectedId = "1";
var selectedItemId = "1";
var selectedTargetId;
var selectedUrl;

function openPanel(num)
{
    var ifrUrl;
    var firstPage = $("firstPage");
    var secondPage = $("secondPage");
    var thirdPage = $("thirdPage");
    var panelSentReceived = $("panelSentReceived");

    if (num == "1")
    {
        firstPage.style.display = "";
        secondPage.style.display = "none";
        thirdPage.style.display = "none";
        
        panelSentReceived.innerHTML = "";
    }
    else if (num == "2")
    {
        firstPage.style.display = "none";
        secondPage.style.display = "none";
        thirdPage.style.display = "";
        
        ifrUrl = "http://gifts.lubarsky.org/sentreceivedgiftlistmanager.aspx?platformid=1&appid=160645800261&userid=" + currentUserId + "&action=sent";
        panelSentReceived.innerHTML = "<iframe src='" + ifrUrl + "' width='100%' height='700' id='content' name='content' frameborder='0'></iframe>";
    }
    else if (num == "3")
    {
        firstPage.style.display = "none";
        secondPage.style.display = "none";
        thirdPage.style.display = "";
        
        ifrUrl = "http://gifts.lubarsky.org/sentreceivedgiftlistmanager.aspx?platformid=1&appid=160645800261&userid=" + currentUserId + "&action=received";
        panelSentReceived.innerHTML = "<iframe src='" + ifrUrl + "' width='100%' height='700' id='content' name='content' frameborder='0'></iframe>";
    }
}

// app. entry point
function loadUser() 
{
    
}
    
//
function sendMessageSpot(targetId, itemId)
{
    selectedItemId = itemId;
    selectedTargetId = targetId;
    
    closeFriendSelector();
    // alert("targetId=" + targetId + "; itemId=" + itemId);

    var sequencer = new FB.BatchSequencer();
    
    // To force sequencial executions on the server, uncomment the following code
    // sequencer.isParallel = false;

    // target
    var sql1 = "SELECT name FROM user WHERE uid=" + targetId;
    var pendingTargetResult = FB.Facebook.apiClient.fql_query(sql1, sequencer);

    // from
    var sql2 = "SELECT name FROM user WHERE uid=" + currentUserId;
    var pendingFromResult = FB.Facebook.apiClient.fql_query(sql2, sequencer);

    // Actually execute the API that is queued inside the sequencer, passing a callback function that is called
    // when the batch operation is completed. When the callback function is called, the 'result' or 'exception' properties of 
    // pendingFriendsResult and pendingNotificationsResult are updated.
    sequencer.execute(function() 
    {
        var targetUserName = pendingTargetResult.result[0]['name'];
        var currentUserName = pendingFromResult.result[0]['name'];
        
        //
        // REQUEST
        // ["itemid"]["platformid"]["appid"]["useridfrom"]["namefrom"]["profileurlfrom"]["useridto"]["nameto"]["profileurlto"]
        var platformId = "1";
        var appId = "160645800261";
        var userIdFrom = currentUserId;
        var nameFrom = currentUserName;
        var profileUrlFrom = "http://www.facebook.com/profile.php?id=" + userIdFrom;
        var userIdTo = targetId;
        var nameTo = targetUserName;
        var profileUrlTo = "http://www.facebook.com/profile.php?id=" + targetId;
        
        var url = "http://www.onecone.com/pages/roses/facebook/sender.aspx";
        var vars = ""
        + "itemid=" + itemId 
        + "&platformid=" + platformId
        + "&appid=" + appId 
        + "&useridfrom=" + userIdFrom 
        + "&namefrom=" + escape(nameFrom)
        + "&profileurlfrom=" + escape(profileUrlFrom)
        + "&useridto=" + userIdTo
        + "&nameto=" + escape(nameTo)
        + "&profileurlto=" + escape(profileUrlTo);
            
        // alert(vars);
        postData(url, vars, handleSend);
    });
}

function handleSend(response) 
{
    // alert("Success!");
    displayMessage("Success sending toy - " + response);


    // publish to stream
    // attachment
    var attachment = {};
    var media = new Array();
    var media1 = {};
    media1["type"] = "image";
    media1["src"] = "http://images.x2line.com/apps/toys/feed90/toy" + selectedItemId + ".png";
    media1["href"] = appExternalUrl;
    media[0] = media1;
    attachment["name"] = "Baby toy for you";
    attachment["href"] = appExternalUrl;
    attachment["caption"] = "just sent a baby toy to you";
    attachment["description"] = "source: Baby Toys";
    attachment["media"] = media;
    
    // actionlinks
    var actionLinks = new Array();
    var actionLink1 = {};
    actionLink1["text"] = "Go to Baby Toys";
    actionLink1["href"] = appExternalUrl;
    actionLinks[0] = actionLink1;
    
    if ($("chkShare").checked)
    {
        FB.Connect.streamPublish("", attachment, actionLinks, selectedTargetId, null, publishSendCallback);
    }
    else
    {
        publishSendCallback();    
    }
}

function publishSendCallback()
{
    // var uids = new Array();
    // uids.push(selectedTargetId);

    // var data = {};
    // data["notification"] = "just sent you a baby toy via <a href='http://apps.facebook.com/babytoys/'>Baby Toys</a>!";
    // data["type"] = "user_to_user";
    // data["to_ids"] = uids;
    // FB.Facebook.apiClient.callMethod("notifications.send", data, function() { });    
}

function displayMessage(mess)
{
    var rsltDiv = $("rslt");
    rsltDiv.style.backgroundColor = '#ffff99';
    rsltDiv.style.border = '#ee0000 1px solid';
    rsltDiv.innerHTML = mess;
}

// select friends to invite
function showInviteFriendsDialog()
{
    var api = FB.Facebook.apiClient;   
    api.fql_query("SELECT uid FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1=" + currentUserId + ") and is_app_user=1", function(result, ex) {   
  
        var str = "";
        for (var i = 0; i < result.length; i++)   
        {   
            str += result[i].uid + ",";
        }

        var excludeIds = '';
        if (str.length > 0)
        {
            str = str.substring(0, str.length - 1);
            excludeIds = 'exclude_ids="' + str + '"';
        }
        
        //
        // produce to selector   
        var actn = location.href;
        
        var the_fbml = '<fb:fbml><fb:request-form action="' + actn + '" method="POST" invite="true" type="Baby Toys" content=""><fb:fbml-attribute name="content"><fb:intl>Come be friends with me on baby toys &lt;fb:req-choice url=&quot;' + appExternalUrl + '&quot; label=&quot;Confirm&quot; /&gt;</fb:intl></fb:fbml-attribute>  \
                <fb:multi-friend-selector rows="3" cols="4" max="60" showborder="true" email_invite="false" ' + excludeIds + ' bypass="cancel" actiontext="Invite Your Facebook Friends">  \
            </fb:request-form></fb:fbml>';
        var dlg = new FB.UI.FBMLPopupDialog('Invite Friends', the_fbml);
        dlg.setContentWidth(625);
        dlg.setContentHeight(400);
        dlg.set_placement(FB.UI.PopupPlacement.topCenter);
        dlg.show();  
    });
}

function loadFriends(toyId) 
{   
    if (currentUserId == null)
    {
        FB.Connect.requireSession();
        return;
    }

    var friendSelector = $("friendSelector");
    friendSelector.style.visibility = "visible";
    friendSelector.style.display = "block";
    friendSelector.style.zIndex = 1100;
    
    
    if ($("fcs"))
    {
        $("fcs").focus();
    }
    
    // alert("We are about to fetch your friends. It may take a while...");
                
    var api = FB.Facebook.apiClient;   
    api.fql_query("SELECT uid, name FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1 = "+currentUserId+") order by name", function(result3, ex3) {   
  
        var data = "<table>";
        data += "<tr><td><input type='button' value='close' onclick='closeFriendSelector();' /></td></tr>";
        
        for (i = 0; i < result3.length; i++)   
        {   
            data += "<tr><td><span style='cursor:pointer;text-decoration:underline;color:blue;' onclick='sendMessageSpot(" + result3[i].uid + ",\"" + toyId + "\");'><small>" + result3[i].name + "</small></span></td></tr>";
        }
        
        data += "</table>";   
           
        friendSelector.innerHTML = data;   
    });   
}

function closeFriendSelector()
{
    var friendSelector = $("friendSelector");
    friendSelector.style.visibility = "hidden";
    friendSelector.innerHTML = "";
}
