﻿var returnUrl;
function FBConnect(url) {
    //FB.init({ apiKey: '05380dc53a1d15d4f95e54225d642cfa' });
    returnUrl = url;
    //FB.login(handleConnectResponse, { perms: 'email, offline_access,publish_stream,read_stream' });
    FB.login(handleConnectResponse, { perms: 'email,user_birthday,status_update,publish_stream,read_stream,read_friendlists,user_relationships,user_photos,user_location,user_likes,user_online_presence, offline_access' });
}

function handleConnectResponse(response) {
    //showFBConnectPost()
    //alert(response.session + ' ' + response.status);
    if (!response.session) {
        return;
    }

    //alert(response.status);

    if (response.status == "connected") {

        sessionid = $('#spanSessionID').text();
        requesturl = $('#spanRequestUrl').text();
        ip = $('#spanIP').text();
        uid = response.session.uid;
        showFBConnectPending();

        // check if this uid is already shopnoon user
        WebService.IsShopNoonUser('' + uid,
            function(resultStr) {
                results = eval(resultStr);

                result = results[0];

                if (result.is_shopnoon_user) {

                    WebService.FBSignIn(uid, sessionid, requesturl, ip,
                            function(resultStr) {
                                results = eval(resultStr);
                                result = results[0];

                                if (result.success) {
                                    //alert('returnUrl:' + returnUrl + ':');
                                    //if (returnUrl.length <= 0) returnUrl = 'default.aspx';
                                    window.location.href = returnUrl;
                                }
                                else
                                    showFBConnectFail();
                            },
                            function(error) {
                                showFBConnectFail();
                            });
                }
                else {
                    var queryTmpl = 'select sex from user where uid={0}';  //+ response.session.uid;
                    var u1 = FB.Data.query(queryTmpl, response.session.uid);

                    FB.Data.waitOn([u1], function(args) {
                        FB.api('/' + response.session.uid, { fields: 'first_name, last_name, email, birthday' }, function(userinfo) {
                            if (typeof (WebService) != "undefined") {
                                $('#span_userinfo_uid').text(uid);
                                $('#span_userinfo_firstname').text(userinfo.first_name);
                                $('#span_userinfo_lastname').text(userinfo.last_name);
                                $('#span_userinfo_sex').text(u1.value[0].sex);
                                $('#span_userinfo_birthday').text(userinfo.birthday);

                                /*
                                bIsMale = null;
                                if (u1.value[0].sex == "male") bIsMale = true;
                                if (u1.value[0].sex == "female") bIsMale = false;
                                birth = typeof (userinfo.birthday) != "undefined" ? userinfo.birthday : '';
                                //email = typeof (userinfo.email) != "undefined" ? userinfo.email : response.session.uid + '@facebook.com';
                                */
                                email = '';
                                if (typeof (userinfo.email) == "undefined")
                                    $('#div_postconnect_email').show();
                                else
                                    email = userinfo.email;
                                
                                //alert(email);

                                $('#txt_postconnect_email').val(email);

                                getFriendList();
                                //alert('got friend list');
                                hideFBConnectPending();
                                showFBConnectPost();

                            }
                            else {
                                //alert('webservice for fbconnect not defined');
                                showFBConnectFail();
                            }
                            //alert(u1.value[0].sex + ' ' + response.first_name + ' ' + response.email);
                        });
                    });
                    //WebService.FBConnect(
                }

            },
            function(error) {
                alert('error in calling IsShopNoonUser()');
            });




    }
    else {
        // response.status is not "connected"
        alert('not connected. please try again.');
    }
}

function OnSuccessFBConnect(resultStr) {
    // redirect
    //alert('success');
    
}

function OnFailFBConnect(error) {
    // show error message
    alert('OnFailFBConnect:' + error.message);
    showFBConnectFail();
}

function OnFailFBConnectPost(error) {
    // show error message
    hideFBConnectPending();
    alert('failed to create shopnoon account and/or import friends. ' + error.message);
    
}

function showFBConnectFail() {
    alert("Unfortunately we could not connect with your facebook account. Please try again.");
}


function OnSuccessFBSignIn(resultStr) {//alert('onsuccess');
    results = eval(resultStr);

    result = results[0];

    if (result.success) {
        window.location.href = result.url;
    }
}

function OnFailFBSignIn(error) {//alert('onfail');
    // do nothing because this happens background
}

function getUserInfoBasic(uid) {
    var userinfo = {};
    FB.init({ apiKey: '05380dc53a1d15d4f95e54225d642cfa' });
    
    FB.api('/' + uid, { fields: 'first_name, last_name, email, birthday' }, function(response) {
        userinfo.first_name = response.first_name;
        userinfo.last_name = response.last_name;
        userinfo.email = typeof (response.email) == "undefined" ? '' : response.email;
        userinfo.birthday = response.birthday;
        //alert(response.first_name + ' ' + response.email + ' ' + response.picture);
    });

    FB.api(
          {
              method: 'fql.query',
              query: 'SELECT sex FROM user WHERE uid=' + uid
          },
          function(response) {
              userinfo.ismale = response[0].sex == 'male';
          });

          return userinfo;
}

function FBLogout() {
    FB.logout(function(response) {
        //alert('logout...');
});
    /*
    if (typeof (WebService) != "undefined") {
        WebService.SignOut(OnSuccessSignOut, OnFailSignOut);

  }
  */
}

function OnSuccessSignOut(resultStr) {//alert('success');
    //FB.init({ apiKey: '05380dc53a1d15d4f95e54225d642cfa' });
    FB.logout(function(response) {
        //alert('logout...');
    });
}

function OnFailSignOut(error) {
}

function showFBConnectPending() {
    $('#divFBConnectPending').show();
    Move2CenterMiddle('divFBConnectPending');
}

function hideFBConnectPending() {
    $('#divFBConnectPending').hide();
}


function showFBConnectPost() {
    $('#divFBConnectPost').show();
    Move2CenterMiddle('divFBConnectPost');
}

function hideFBConnectPost() {
    $('#divFBConnectPost').hide();
}

function handleFBConnectPost(bAccount, bSP, returnUrl) {
    if (bAccount) {
        $('#divPDSubmit').show();
        sessionid = $('#spanSessionID').text();
        requesturl = $('#spanRequestUrl').text();
        ip = $('#spanIP').text();
        var uid = $('#span_userinfo_uid').text();
        var email = $('#txt_postconnect_email').val();
        
        var first_name = $('#span_userinfo_firstname').text();
        var last_name = $('#span_userinfo_lastname').text();
        var birth = $('#span_userinfo_birthday').text();
        
        var bIsMale = null;
        var sex = $('#span_userinfo_sex').text();
        if (sex.length > 0)
            bIsMale = sex == 'male';

        //alert(email);
        var friendlist = Array();
        if (bSP) {
            $('#div_postconnect_friend .div_fb_friend').each(function() {
                //alert($(this).find('input:checked').length);
                if ($(this).find('input:checked').length > 0) {
                    var f_uid = $(this).find('#span_uid').text();
                    var f_firstname = $(this).find('#span_firstname').text();
                    var f_lastname = $(this).find('#span_lastname').text();
                    var f_birthday = $(this).find('#span_birthday').text();
                    var f_sex = $(this).find('#span_sex').text();
                    //alert(f_uid + ' ' + f_firstname + ' ' + f_lastname + ' ' + f_birthday + ' ' + f_sex);
                    afriend = [f_uid, f_firstname, f_lastname, f_birthday, f_sex];
                    friendlist.push(afriend);
                }
            });
        }

        //alert(uid + ' ' + email + ' ' + first_name + ' ' + last_name + ' ' + bIsMale + ' ' + birth + ' ' + sessionid + ' ' + requesturl + ' ' + ip);
        WebService.FBConnect(uid, email, first_name, last_name, bIsMale, birth, sessionid, requesturl, ip, friendlist,
        function(resultStr) {
            hideFBConnectPending();
            results = eval(resultStr);
            result = results[0];
            if (result.success) {
                if (returnUrl.length > 0)
                    window.location.href = returnUrl;
                else
                    window.location.href = "myaccount_home.aspx?bid=" + result.buyerid;
            }
            else {
                //alert('reason:' + result.reason);
                showFBConnectFail();
            }
        },
        OnFailFBConnectPost);
    }
}

var fb_max_friend = 50;
var fb_profile_url_prefix = 'http://www.facebook.com/profile.php?id=';
function getFriends(photoareaid, imgwidth) {
    if (!imgwidth) imgwidth = 28;
    //alert('hi');
    /*
    FB.api('/me/friends', { fields: 'id, name, picture' }, function(response) {
        $('#spannumfriend').text(response.data.length);
        //if (response.data.length > 0) $('#imgFriend').attr('src', response.data[0].picture);

        var max = Math.min(response.data.length, fb_max_friend);
        for (var i = 0; i < max; i++) {
            var img = '<a href="' + fb_profile_url_prefix + response.data[i].id + '"><img src="' + response.data[i].picture + '" width="' + imgwidth + '" style="padding:1px; background-color:cccccc;"/></a>';
            $('#' + photoareaid).append(img);
        }

    });
    */

    FB.getLoginStatus(function(response) {
        if (response.session) {
            var queryTmpl = 'select uid2 from friend where uid1={0}';  //+ response.session.uid;
            var u1 = FB.Data.query(queryTmpl, response.session.uid);

            FB.Data.waitOn([u1], function(args) {


                if (typeof (WebService) != "undefined") {

                    uidlist = Array();
                    for (var i = 0; i < u1.value.length; i++) {
                        uidlist.push(u1.value[i].uid2);
                    }

                    WebService.GetFriendsShopNoonStatus(uidlist,
                        function(resultStr) {
                            $('#divFriendFetching').hide();
                            results = eval(resultStr);

                            result = results[0];

                            if (result.success) {
                                data = result.data;
                                for (var i = 0; i < data.length; i++) {
                                    link = data[i].status == "notMember" ? (fb_profile_url_prefix + data[i].uid) : ('home.aspx?bid=' + data[i].bid);
                                    var img = '<a href="' + link + '"><img src="https://graph.facebook.com/' + data[i].uid + '/picture" id="pic_' + data[i].uid + '" class="' + data[i].status + '" width="' + imgwidth + '"/></a>';
                                    $('#' + photoareaid).append(img);
                                    if (data[i].status == 'logined') {
                                        $('#shopnoonactivity').append('<li id="activity_' + data[i].uid + '">' + data[i].lastactivity + '</li>');
                                        $('#shopnoondate').append('<li id="date_' + data[i].uid + '">' + data[i].date + '</li>');
                                        
                                        $('#shopnoonimgurl').append('<li id="imgurl_' + data[i].uid + '">' + data[i].imgurl + '</li>');
                                        $('#shopnoonlinkurl').append('<li id="linkurl_' + data[i].uid + '">' + data[i].linkurl + '</li>');
                                    }
                                }
                            }
                            else {
                                alert('result fail');
                                for (var i = 0; i < u1.value.length; i++) {
                                    var img = '<a href="' + fb_profile_url_prefix + u1.value[i].uid2 + '"><img src="https://graph.facebook.com/' + u1.value[i].uid2 + '/picture" width="' + imgwidth + '" style="padding:1px; background-color:cccccc;"/></a>';
                                    $('#' + photoareaid).append(img);
                                }
                            }
                        },
                        function(error) {
                            $('#divFriendFetching').hide();
                            alert('call web service error');
                            for (var i = 0; i < u1.value.length; i++) {
                                var img = '<a href="' + fb_profile_url_prefix + u1.value[i].uid2 + '"><img src="https://graph.facebook.com/' + u1.value[i].uid2 + '/picture" width="' + imgwidth + '" style="padding:1px; background-color:cccccc;"/></a>';
                                $('#' + photoareaid).append(img);
                            }
                        });
                }
            });
        }
        else {
        }
    });
}

function publishPost() {//alert('publishExample');
    FB.ui(
        {
            method: 'stream.publish',
            message: '',
            attachment: {
                name: $('#attachmentTitle').text(),
                caption: $('#attachmentCaption').text(),
                description: $('#attachmentDescription').text(),
                href: $('#attachmentUrl').text(),
                media: [{ type: 'image', src: $('#attachmentMediaSrc').text(), href: $('#attachmentMediaUrl').text()}]
            },
            action_links: [
                { text: ' ' + $('#actionLinkTitle').text(), href: ' ' + $('#actionLinkUrl').text() }
            ],
            user_message_prompt: $('#messagePrompt').text()
        },
        function(response) {
            if (response && response.post_id) {
                alert('Post was published');
            }
            else {
                //alert('Post was not published.');
            }
        }
         );
    }

    function getFriendList() {
        //alert('will get friend list()');
        FB.getLoginStatus(function(response) {

            if (response.session) {
                //alert(response.session.uid);
                //var qryuid = FB.Data.query('select uid2 from friend where uid1 = {0}', response.session.uid);
                var qry = FB.Data.query('select uid, first_name, last_name, birthday, sex from user where uid in (select uid2 from friend where uid1 = {0})', response.session.uid);
                qry.wait(function(rows) {
                    //alert(rows.length);
                    for (var i = 0; i < rows.length; i++) {
                        var f = rows[i];
                        var birthday = '';
                        if (f.birthday) birthday = f.birthday;
                        var sex = '';
                        if (f.sex) sex = f.sex;
                        
                        var adiv = '<div class="div_fb_friend">\
                        <div style="display:none;"><span id="span_uid">' + f.uid + '</span> <span id="span_firstname">' + f.first_name + '</span> <span id="span_lastname">' + f.last_name + '</span> <span id="span_birthday">' + birthday + '</span> <span id="span_sex">' + sex + '</span></div>\
        <table width="72" border="0" cellpadding="0" cellspacing="0" style="display:inline; background-color:#e0e0e0;">\
                      <tr> \
                        <td valign="top"><input type="checkbox" class="chk_fb_friend" id="chk_friend_' + f.uid + '" checked="checked"/></td> \
                        <td style="padding:5px"><img src="https://graph.facebook.com/' + f.uid + '/picture" /></td> \
                      </tr> \
                      <tr> \
                        <td valign="top">&nbsp;</td> \
                        <td class="geneva" style="height: 30px; font-size:11px; padding-top:4px; padding-bottom:5px; line-height:11px">' + f.first_name + ' ' + f.last_name + '</td> \
                      </tr> \
                    </table> \
         </div>';
                        //var tr = '<tr><td><img src="https://graph.facebook.com/' + f.uid + '/picture" /></td><td>' + f.first_name + ' ' + f.last_name + ' ' + f.sex + ' ' + f.birthday + '</td><td><input type="checkbox" id="chk_friend_' + f.uid + '" checked="checked"/></td></tr>';
                        $('#div_postconnect_friend').append(adiv);
                    }

                    if (rows.length <= 0)
                        $('#table_import_friends').hide();
                    else
                        $('#div_postconnect_friend').show();

                    if (rows.length > 10)
                        $('#div_postconnect_friend').css('overflow', 'scroll');
                });
            }
            else {
                return [];
            }


        });
        
        
        
    }
