var flashID = "";
var api;
var flashObject;

function initFB( flash_id, thekey, crossdomainfile)
{
    FB.init( thekey, crossdomainfile );
    flashID = flash_id;

}

function loginFB(isAuto){

    if ( isAuto == "false" ){
        FB.Connect.requireSession( checkFB );
    }else
    {
        FB.Facebook.get_sessionState().waitUntilReady(function(session)
        {
            if(session){
               checkFB();
            }
        });
    }
 
}

function checkFB(){
    var uid = FB.Facebook.apiClient._session.uid;
    var ajaxConn = new XHConn();
    ajaxConn.connect("/profile.php","get",
        "action=check_by_facebook_id&id="+uid,facebookResponse);
}


function facebookResponse(XML)
{
    if(XML.responseText=='<success/>'){
        onLogin();
    }else{
        facebookExist();
    }

}


function autologinFB()
{
    FB.Connect.requireSession( autoLogin );
    FB.Facebook.get_sessionState().waitUntilReady(function(session)
    {
        if(session)
            autoLogin();
    });

}

function autoLogin()
{
    api = FB.Facebook.apiClient;
    var flashObject = document.getElementById(flashID);
    flashObject.autoLogin(api._session.uid);
}

function onLogin()
{
    api = FB.Facebook.apiClient;

    var profileData = ["first_name", "last_name", "uid", "birthday_date"];

    getUserInfo(api._session.uid,profileData);
}


function getUserInfo(userId, arrProfileData)
{
    var jsonString = "";
    api.users_getInfo(userId, arrProfileData, function(result, ex)
    {
        var firstName = result[0]['first_name'];
        var lastName = result[0]['last_name'];
        var uid = result[0]['uid'];
        var birthday = result[0]['birthday_date'];

        jsonString += firstName + ",";
        jsonString += lastName + ",";
        jsonString += uid + ",";
        jsonString += birthday;
        populate(jsonString);
    });

}

function getFriends(){

    var status = true;

    try{
        var uid = FB.Facebook.apiClient._session.uid;

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

                data = "";
                for (i=0;i<result.length;i++)
                {
                    data +=  result[i].uid+","+result[i].first_name + " " + result[i].last_name+","+result[i].pic_square;

                    if(i<result.length-1){
                        data += "#|#";
                    }
                }

                populateFriends(data);

            });


    }catch(err){
        status = false;
    }

    return status;
}

function populateFriends(data){
    flashObject = document.getElementById(flashID);
    flashObject.populateFriends(data);
}

function facebookExist(){
    flashObject = document.getElementById(flashID);
    flashObject.facebookError();
}

function populate(userData){
    var flashObject = document.getElementById(flashID);
    flashObject.populate(userData);
}


function sendNotification(idList,promLink){

    var arrayId = new Array();
    arrayId = idList.split(',');

    api.notifications_send(arrayId,"I invite you to virtual prom here <a href=\""+promLink+"\">"+promLink+"</a>",function(result,ex){

        });

}


/** XHConn - Simple XMLHTTP Interface - bfults@gmail.com - 2005-04-08        **
 ** Code licensed under Creative Commons Attribution-ShareAlike License      **
 ** http://creativecommons.org/licenses/by-sa/2.0/                           **/
function XHConn()
{
    var xmlhttp, bComplete = false;
    try {
        xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch (e) {
        try {
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        catch (e) {
            try {
                xmlhttp = new XMLHttpRequest();
            }
            catch (e) {
                xmlhttp = false;
            }
        }
    }
    if (!xmlhttp) return null;
    this.connect = function(sURL, sMethod, sVars, fnDone)
    {
        if (!xmlhttp) return false;
        bComplete = false;
        sMethod = sMethod.toUpperCase();
        try {
            if (sMethod == "GET")
            {
                xmlhttp.open(sMethod, sURL+"?"+sVars, true);
                sVars = "";
            }
            else
            {
                xmlhttp.open(sMethod, sURL, true);
                xmlhttp.setRequestHeader("Method", "POST "+sURL+" HTTP/1.1");
                xmlhttp.setRequestHeader("Content-Type",
                    "application/x-www-form-urlencoded");
            }
            xmlhttp.onreadystatechange = function(){
                if (xmlhttp.readyState == 4 && !bComplete)
                {
                    bComplete = true;
                    fnDone(xmlhttp);
                }
            };
            xmlhttp.send(sVars);
        }
        catch(z) {
            return false;
        }
        return true;
    };
    return this;
}

