function refresh_page() {
    setTimeout("window.location = 'http://www.scholarships.com/';", 1000);


}


/*
* Prompts the user to grant a permission to the application.
*/
function facebook_prompt_permission(permission) {
    FB.ensureInit(function() {
        FB.Connect.showPermissionDialog(permission);
    });
}


/*
* On facebook login button check if user is already connected with SCH.
* If user connected, log in; if not, redirect to the connect page.
*/

function fbredirect() {
    FB.ensureInit(function() {
        FB.Facebook.get_sessionState().waitUntilReady(function() {

            if (FB.Connect != null) {
                var viewer = FB.Facebook.apiClient.fql_query(
                'SELECT  first_name, last_name, pic_square  FROM user WHERE uid=' + FB.Facebook.apiClient.get_session().uid,
                function(results) {
                    if (results != 0) {
                        //setTimeout("loadfb_rdata(results[0].first_name, results[0].last_name);", 5000);
                        loadfb_rdata(results[0].first_name, results[0].last_name, results[0].pic_square);
                    }

                });
            }
        });
    });
}

function loadfb_rdata(fname, lname, pic_square) {

    var sess = FB.Facebook.apiClient.get_session();
    var param = sess.uid;
    var fnfname = fname;
    var fblname = lname;
    $.ajax({
        type: "POST",
        url: "/fbRedirectUrl.aspx",
        data: "fbid=" + param + "&fname=" + fnfname + "&lname=" + fblname.charAt(0) + "&fbpic=" + pic_square,
        dataType: "json",
        success: function(msg) {
            alertUser(msg);
        }

    });

}

function alertUser(transport) {
    var json = transport;
    window.location = json.url;
    setTimeout("", 3000);

}



/*
* Start Publish Status Update
*/

function fbUpdateStatus() {
    FB.ensureInit(function() {
        FB.Facebook.get_sessionState().waitUntilReady(function() {
            if (FB.Connect != null) {
                if (FB.Facebook.apiClient.get_session().uid != null) {
                    var sess = FB.Facebook.apiClient.get_session();
                    var param = sess.uid;

                    $.ajax({
                        type: "POST",
                        url: "/facebookPublish.aspx",
                        data: "fbid=" + param,
                        dataType: "json",
                        success: function(msg) {
                            fbReturnUpdateStatus(msg);
                        }
                    });
                }

            }
        });
    });

}

function fbReturnUpdateStatus(transport) {
    var json = transport;
    if (json.fbpublish != 0) { fbPublish(); }


}

function fbPublish() {

     var message = 'just logged in using scholarships.com.';
     var attachment = { 'name': 'Scholarships.com',
         'href': 'http://www.scholarships.com/tellafriend.aspx',
         'description': 'Enter The Scholarships.com "Tell A Friend" $1,000 Sweepstakes'
     };
                   FB.Connect.streamPublish(message, attachment, '', '', '', null, true, null);


}

/*
* End Publish Status Update
*/




function update_user_box() {
    FB.ensureInit(function() {
        FB.Connect.requireSession(function() {
            FB.Facebook.get_sessionState().waitUntilReady(function() {
            if (window.location.href == 'http://www.scholarships.com/main.aspx?action=fblogout') { FB.Connect.logout(function() { setTimeout("refresh_page();", 1000); return false; }); }
            if (window.location.href != 'http://www.scholarships.com/main.aspx?action=logout') {
                    if ((FB.Connect != null) || (FB.Facebook.apiClient.get_session().uid != null)) {
                        setTimeout("fbrefresh();", 1000); // To detect if user logged in to fb and already connected with sch.
                        fbUpdateStatus(); //Check when was last status update done.  
                    }
                }
            });
        });
    });

}

//    function load_namedata(first_name, last_name) {
//        var user_box = document.getElementById("userbox");
//        user_box.innerHTML =
//                    "<span>"
//                    + "<fb:login-button size='small' background='light'  length='short' onclick='goTofacebookConnect();'></fb:login-button> "
//        // + "<fb:name uid='loggedinuser' useyou='false' ></fb:name>"
//                    + "<strong style='color:#144895'>"
//                   + first_name
//                   + " "
//                   + last_name.charAt(0)
//                   + "</strong>"
//                    + " connected via Facebook."
//                    + "</span>"
//        FB.XFBML.Host.parseDomTree();                     
//        
//    }

function fbrefresh() {
FB.ensureInit(function() {
    FB.Facebook.get_sessionState().waitUntilReady(function() {
        if (FB.Connect != null) {
            var viewer = FB.Facebook.apiClient.fql_query(
                'SELECT  first_name, last_name,pic_square FROM user WHERE uid=' + FB.Facebook.apiClient.get_session().uid,
                function(results) {
                    if (results != null) {
                        loadfb_data(results[0].first_name, results[0].last_name, results[0].pic_square)
                    }
                });
        }
    });
});

}


function loadfb_data(fname, lname, pic_square) {
    FB.Facebook.get_sessionState().waitUntilReady(function() {
        if (FB.Connect != null) {
            var currentwindow = window.location;
            var sess1 = FB.Facebook.apiClient.get_session();
            var fnfname = fname;
            var fblname = lname;
            if (FB.Connect != null) {
                var param = sess1.uid;

                $.ajax({
                    type: "POST",
                    url: "/fbRefreshIndex.aspx",
                    data: "fbid=" + param + "&currentwindow=" + currentwindow + "&firstTimeConnect=" + "No" + "&fname=" + fnfname + "&lname=" + fblname.charAt(0) + "&fbpic=" + pic_square,
                    dataType: "json",
                    success: function(msg) {
                        pagerefresh(msg);
                    }
                });
            }
        }

    });

}

function pagerefresh(transport) {

    var json = transport;
    window.location = json.url;

}


function goTofacebookConnect() {
    window.location = "/facebookConnect.aspx";
}




/*
* Scholarship-search.aspx
* Doesn't use updateloginlogout control
* Prepopulate fileds
*/
function update_user_box_ss() {
    var winloc = window.location;
    if (winloc.href == 'http://www.scholarships.com?action=logout') { FB.Connect.logout(function() { refresh_page() }); }
  $('#userboxlogin').hide();
  if (winloc.href != 'http://www.scholarships.com?action=logout') {
        fbrefresh();

   }
    FB.ensureInit(function() {
        FB.Facebook.get_sessionState().waitUntilReady(function(session) {
            var is_now_logged_into_facebook = session ? true : false;
            if (is_now_logged_into_facebook) {

                var viewer = FB.Facebook.apiClient.fql_query(
          'SELECT name, first_name, last_name, birthday_date,  current_location, education_history,  pic_square_with_logo ,profile_url FROM user WHERE uid=' + FB.Facebook.apiClient.get_session().uid,
                function(results) {
                    if (results != null) {
                        load_data(results[0].name, results[0].first_name, results[0].last_name, results[0].birthday_date, results[0].current_location, results[0].education_history, results[0].pic_square_with_logo, results[0].profile_url)
                    }
                });
            }
        });
    });

}

function load_data(name, first_name, last_name, birthday_date, current_location, image, url) {

    var user_box = document.getElementById("userbox");
    user_box.innerHTML =
                    "<span>"
                    + "<fb:profile-pic uid='loggedinuser' facebook-logo='true' width='18' height='16'></fb:profile-pic>"
    // + "<fb:login-button size='small' background='light'  length='short' onclick='goTofacebookConnect();'></fb:login-button> "
    // + "<fb:name uid='loggedinuser' useyou='false' ></fb:name>"
                    + "<strong style='color:#144895'> "
                   + first_name
                   + " "
                   + last_name.charAt(0)
                   + "</strong>"
                  //  + " <a href='facebookconnect.aspx'><img src='/images/fbconn.jpg' width='18' height='16' /></a>"
    // + "<br /><a href='#' onclick='FB.Connect.logout(function() { refresh_page(); });'>Logout</a>"
                    + "</span>"

    FB.XFBML.Host.parseDomTree();



    if (current_location != null) {
        document.getElementById("txtZipPostalCode").value = current_location.zip;
    }

    //***Load birthday month. FB retruns month/day/year where month is 05
    if (birthday_date != null) {
        var birthday_array = birthday_date.split("/");
        if (birthday_array[0] == "01") { birthday_array[0] = "January" }
        if (birthday_array[0] == "02") { birthday_array[0] = "February" }
        if (birthday_array[0] == "03") { birthday_array[0] = "March" }
        if (birthday_array[0] == "04") { birthday_array[0] = "April" }
        if (birthday_array[0] == "05") { birthday_array[0] = "May" }
        if (birthday_array[0] == "06") { birthday_array[0] = "June" }
        if (birthday_array[0] == "07") { birthday_array[0] = "July" }
        if (birthday_array[0] == "08") { birthday_array[0] = "August" }
        if (birthday_array[0] == "09") { birthday_array[0] = "September" }
        if (birthday_array[0] == "10") { birthday_array[0] = "October" }
        if (birthday_array[0] == "11") { birthday_array[0] = "November" }
        if (birthday_array[0] == "12") { birthday_array[0] = "December" }
        var dropdown = document.getElementById('lstMonthOfBirth');
        for (var i = 1; i < dropdown.length; i++) {
            if (dropdown.options[i].text == birthday_array[0]) {
                dropdown.options[i].selected = true;
            }
        }
        //***Load birthday day

        var dropdown2 = document.getElementById('lstDayOfBirth');
        if (birthday_array[1].charAt(0) == 0) {
            birthday_array[1] = birthday_array[1].substr(1);

        }
        for (var i = 1; i < dropdown2.length; i++) {
            if (dropdown2.options[i].value == birthday_array[1]) {
                dropdown2.options[i].selected = true;
            }
        }

        //***Load birthday year
        var dropdown3 = document.getElementById('lstYearOfBirth');
        for (var i = 1; i < dropdown3.length; i++) {
            if (dropdown3.options[i].value == birthday_array[2]) {
                dropdown3.options[i].selected = true;
            }
        }

    }

    if (current_location != null) {
        var dropdownCountries = document.getElementById('lstCountry');
        current_location.country = current_location.country.replace(/\s+/g, '');

        for (var i = 1; i < dropdownCountries.length; i++) {
            dropdownCountries.options[i].text = dropdownCountries.options[i].text.replace(/\s+/g, '');
            if (dropdownCountries.options[i].text == current_location.country) {
                dropdownCountries.options[i].selected = true;
            }
        }
    }

}



function suppressWindowOnFbClick() {
    if ((window.location.href == 'http://www.scholarships.com/') || (window.location.href == 'http://www.scholarships.com?action=logout')) {
        window.document.frmCommArea.hidSuppressPopUnder.value = 'yes';
        window.document.frmCommArea.hidSuppressExitPage.value = 'yes';
    }
    if (window.location.href == 'http://www.scholarships.com/scholarship-search.aspx') {
        window.document.frmBegin.hidSuppressPopUnder.value = 'yes';
      
       
    }
}

function fbInitialization() {

    var testapikey = '3418c03d204dddaf185707a874b5e580'; // facebook login kathy.gorman@yahoo.com-tesing api key
    var liveapikey = '1da6ab806506db4bd7c1ab38741f9349'; //facebook login rdj@eadmail.com-live -change application profile connect to scholarships.com

    if (location.hostname == 'localhost') {
        return testapikey;
    }
    else {
        return liveapikey;
    }

   
}
