// reference path for VS2010 Intellisense
/// <reference path="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.js" />
/// <reference path="http://connect.facebook.net/en_US/all.js" />
var Callback =
{
    call: function (callback) {
        if (typeof (callback) != "function") {
            throw new Error("callback must be a function");
        }

        var args = new Array();
        for (var i = 1; i < arguments.length; i++) {
            args.push(arguments[i]);
        }
        callback.apply(callback, args);
    }
}

var FacebookAssetGraph = {

    //config defaults
    config:
    {
        numAlbumsPerPage: 25,
        numPhotosPerPage: 25,
        numVideosPerPage: 25
    },

    configure: function (options) {
        $.extend(FacebookAssetGraph.config, options);
    },

    getPageOfAlbums: function (page, success, failure) {
        FB.api('/me/albums',
            {
                limit: FacebookAssetGraph.config.numAlbumsPerPage + 1,
                offset: FacebookAssetGraph.config.numAlbumsPerPage * page
            },
            function (response) {
                if (typeof (response.error) != "undefined") {
                    if (typeof (failure) == 'function') {
                        Callback.call(failure, response);
                    }
                    return;
                }

                if (page > 0) {
                    response.previous = page - 1;
                }

                if (response.data.length == FacebookAssetGraph.config.numAlbumsPerPage + 1) {
                    response.next = page++;
                    //remove the extra to evaluate if there are any more pages
                    var facebookData = response.data;
                    response.data = new Array();

                    for (var i = 0; i < FacebookAssetGraph.config.numAlbumsPerPage; i++) {
                        response.data[i] = facebookData[i];
                    }
                }

                //get cover img urls
                $.each(response.data, function (i, el) {
                    var coverUrl = "https://graph.facebook.com/" + el.id + "/picture?access_token=" + FB.getSession().access_token;
                    el.cover_url = coverUrl;
                });

                //remove paging element
                var temp = response;
                response = null;
                response =
                {
                    data: temp.data,
                    previous: temp.previous,
                    next: temp.next
                };
                Callback.call(success, response);
            });
    },

    getPageOfPhotosInAlbum: function (albumId, page, success, failure) {
        FB.api(albumId + '/photos',
            {
                limit: FacebookAssetGraph.config.numPhotosPerPage + 1,
                offset: FacebookAssetGraph.config.numPhotosPerPage * page
            },
            function (response) {
                if (typeof (response.error) != "undefined") {
                    if (typeof (failure) == 'function') {
                        Callback.call(failure, response);
                    }
                    return;
                }

                if (page > 0) {
                    response.previous = page - 1;
                }

                if (response.data.length == FacebookAssetGraph.config.numPhotosPerPage + 1) {
                    response.next = page++;
                    //remove the extra value
                    var facebookData = response.data;
                    response.data = new Array();

                    for (var i = 0; i < FacebookAssetGraph.config.numPhotosPerPage; i++) {
                        response.data[i] = facebookData[i];
                    }
                }

                Callback.call(success, response);
            });

    },

    getPageOfPhotos: function (page, success, failure) {
        FB.api("/me/photos",
            {
                limit: FacebookAssetGraph.config.numPhotosPerPage,
                offset: FacebookAssetGraph.config.numPhotosPerPage * page
            },
            function (response) {
                if (typeof (response.error) != "undefined") {
                    if (typeof (failure) == 'function') {
                        Callback.call(failure, response);
                    }
                    return;
                }

                if (page > 0) {
                    response.previous = page - 1;
                }

                if (response.data.length == FacebookAssetGraph.config.numPhotosPerPage + 1) {
                    response.next = page++;
                    //remove the extra value
                    var facebookData = response.data;
                    response.data = new Array();

                    for (var i = 0; i < FacebookAssetGraph.config.numPhotosPerPage; i++) {
                        response.data[i] = facebookData[i];
                    }
                }

                Callback.call(success, response);
            });


    },

    getPhotoById: function (photoId, success, failure) {
        FB.api(photoId, function (response) {
            if (typeof (response.error) != "undefined") {
                if (typeof (failure) == 'function') {
                    Callback.call(failure, response);
                }
                return;
            }

            Callback.call(success, response);
        });

    }
};

var FacebookAssetFQL =
{
    getAlbumsForUser: function (userId, callback) {
        var query = FB.Data.query('SELECT aid, cover_pid, object_id, name, size FROM album WHERE owner = {0} ORDER BY modified DESC', userId);
        query.wait(function (rows) {
            Callback.call(callback, rows);
        });
    },

    getPhotosInAlbum: function (userId, albumId, callback) {
        var query = FB.Data.query('SELECT pid, aid, object_id, src_small, src_big, caption FROM photo WHERE owner = {0} AND aid = "{1}" ORDER BY modified DESC', userId, albumId);
        query.wait(function (rows) {
            Callback.call(callback, rows);
        });
    },

    getPhoto: function (userId, photoId, callback) {
        var query = FB.Data.query('SELECT pid, aid, object_id, src_small, src_big, caption FROM photo WHERE owner = {0} AND pid = "{1}"', userId, photoId);
        query.wait(function (rows) {
            Callback.call(callback, rows);
        });
    },

    getTaggedPhotos: function (userId, callback) {
        var query = FB.Data.query('SELECT pid, aid, object_id, src_small, src_big, caption FROM photo WHERE pid IN (select pid from photo_tag where subject = {0}) ORDER BY modified DESC', userId);
        query.wait(function (rows) {
            Callback.call(callback, rows);
        });
    },

    getVideos: function (userId, callback) {
        var query = FB.Data.query('SELECT vid, owner, title, description, thumbnail_link, embed_html, src, src_hq FROM video WHERE owner = {0} ORDER BY modified DESC', userId);
        query.wait(function (rows) {
            Callback.call(callback, rows);
        });
    },

    getTaggedVideos: function (userId, callback) {
        var query = FB.Data.query('SELECT vid, owner, title, description, thumbnail_link, embed_html, src, src_hq FROM video WHERE vid in (SELECT vid FROM video_tag WHERE subject = {0}) ORDER BY modified DESC', userId);
        query.wait(function (rows) {
            Callback.call(callback, rows);
        });
    },

    getVideo: function (videoId, callback) {
        var query = FB.Data.query('SELECT vid, owner, title, description, thumbnail_link, embed_html, src, src_hq FROM video WHERE vid = "{0}"', videoId);
        query.wait(function (rows) {
            Callback.call(callback, rows);
        });
    }
};

var Facebook =
{
    fbInitCalled: false,

    waitForFbInit: function (callback) {
        if (Facebook.fbInitCalled) {
            Callback.call(callback);
            return;
        }

        //check FB four times a second
        window.setTimeout(function () {
            Facebook.waitForFbInit(callback);
        }, 250);
    },

    waitForFB: function (callback) {
        //facebook is good call function
        if (typeof (FB) != 'undefined') {
            Callback.call(callback);
            return;
        }

        //check FB four times a second
        window.setTimeout(function () {
            Facebook.waitForFB(callback);
        }, 250);
    },

    isUserConnected: function () {
        if (FB.getSession() == null) {
            return false;
        }
        return true;
    },

    //reference http://developers.facebook.com/docs/authentication/permissions/ for permissions
    login: function (success, failure, perms) {
        FB.login(function (response) {
            if (response.session) {
                Callback.call(success, response);
            } else {
                Callback.call(failure, response);
            }
        }, { perms: perms });
    },

    tryFacebookLogin: function () {
        Facebook.waitForFB(
        function () {
            if (Facebook.isUserConnected()) {
                Facebook.getLoginStatus(function (response) {
                    if (response.session) {
                        $.ajax({
                            type: 'POST',
                            url: '/ajax/loginFacebook',
                            data: response.session,
                            dataType: 'json',
                            success: function (response) {
                                if (response.status == "loggedIn") {
                                    var url = document.URL;
                                    var url_parts = url.split('?');
                                    window.location = url_parts[0];
                                }
                                else {
                                    window.location = window.location.protocol + '//' + window.location.hostname + "?regLog=register";
                                }
                            },
                            error: function (response) { console.log(response.status); }
                        });
                    }
                });
            }
            else {
                Facebook.login(
                    function (response) {
                        Facebook.getLoginStatus(function (response) {
                            $.ajax({
                                type: 'POST',
                                url: '/ajax/loginFacebook',
                                data: response.session,
                                dataType: 'json',
                                success: function (response) { console.log(response); },
                                error: function (response) { console.log(response); }
                            });
                        });
                    },
                    function (response) { console.log(response); }, '');
            }
        });
    },

    getLoginStatus: function (success) {
        FB.getLoginStatus(function (response) {
            Callback.call(success, response);
        });
    },

    logout: function (success) {
        FB.logout(function (response) {
            Callback.call(success, response);
        });
    },

    //reference http://developers.facebook.com/docs/reference/dialogs/feed/ for options
    share: function (options, success, failure) {
        var opt = { method: 'feed' };
        //make sure method feed is most important
        $.extend(options, opt);
        FB.ui(
        options,
        function (response) {
            if (response && response.post_id) {
                Callback.call(success, response)
            }
            else {
                Callback.call(failure, response);
            }
        });
    },

    getUserStandardInfo: function (success) {
        FB.api('/me', function (response) {
            Callback.call(success, response);
        });
    },

    //permission is an array of permissions
    hasAppPermissions: function (permission, success, failure) {
        FB.api('/me/permissions', function (response) {
            if (response.error) {
                Callback.call(failure, response);
                return;
            }
            var data = response.data[0];
            for (var i = 0; i < permission.length; i++) {
                if (data[permission[i]] == 0 || typeof (data[permission[i]]) == "undefined") {
                    Callback.call(success, false);
                    return;
                }
            }

            Callback.call(success, true);
        });
    }
};

var FacebookApplication = {
    baseFacebookUrl: '',
    currentFacebookUrl: '',

    baseInit: function (initOptions, callback) {
        FB.init(initOptions);
        Facebook.fbInitCalled = true;
        if (typeof (callback) != "undefined") {
            Callback.call(callback);
        }
    },

    init: function (initOptions) {
        FacebookApplication.baseInit(initOptions);
    },

    init: function (initOptions, callback) {
        FacebookApplication.baseInit(initOptions, callback);
    },

    init: function (initOptions, baseFacebookUrl, currentFacebookUrl) {
        FacebookApplication.baseFacebookUrl = baseFacebookUrl;
        FacebookApplication.currentFacebookUrl = currentFacebookUrl;
        FacebookApplication.baseInit(initOptions);
    },

    init: function (initOptions, baseFacebookUrl, currentFacebookUrl, callback) {
        FacebookApplication.baseFacebookUrl = baseFacebookUrl;
        FacebookApplication.currentFacebookUrl = currentFacebookUrl;
        FacebookApplication.baseInit(initOptions, callback);
    },

    topRedirectUrl: function (path) {
        top.location.href = baseFacebookUrl + path;
    },

    topRedirectCurrent: function () {
        top.location.href = currentFacebookUrl;
    }
};

