
jQuery.fn.center = function () {
    this.css("position","absolute");
    this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px");
    this.css("left", ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px");
    return this;
}

var usernameisvalid = true;
var fbapikey = "";
var alreadylogin = true;

function submitFB(sForm) {
    var sForms = document.getElementById("Form2");    
    sForms.hdFBLogin.value = "1";
    sForms.submit();    
}
function checkFBLogin() {
    try {
        if (FB.Connect.get_loggedInUser() != null) {
            alreadylogin = true;			
        }
        else {	
            alreadylogin = false;
        }
        FB.Connect.requireSession(promptUser, function() { alert('user cancelled operation') });
    }
    catch (err) {
		alert(err);
        //setTimeout("checkFBLogin()", 500);
    }
}

function test() {

	FB.init({
     appId  : fb_apikey,
     status : true, // check login status
     cookie : true, // enable cookies to allow the server to access the session
     xfbml  : true  // parse XFBML
   });
   
	FB.getLoginStatus(function(response) {
	  if (response.session) {
	    // logged in and connected user, someone you know
	  } else {
	    // no user session available, someone you dont know
	  }
	  });


}

function ShowJQueryNotice(dv, width, height, msg , title) {

    if ($("#" + dv).length == 0) { 
        $("body").append("<div id='" + dv + "'></div>");
    }

    $("#" + dv).html(msg);

    $("#" + dv).dialog({ autoOpen: false, width: width, height: height, modal: true, zIndex: 35000 });
    $("#" + dv).css("max-height", height + "px");
    if (title) {
        $("#" + dv).dialog("option", "title", title);
    }
    $("#" + dv).dialog("open");
}

function ShowRegisterMemberIdFaceBook()
{
	/*var container =	$("#registermemberid_facebook");
	$("#fade").show();	
	container.css("position","absolute");
    container.css("top", ( $(window).height() - container.height() ) / 2+$(window).scrollTop() + "px");
    container.css("left", ( $(window).width() - container.width() ) / 2+$(window).scrollLeft() + "px");
	$("#registermemberid_facebook").fadeIn("slow");	*/
		
	/*$.ajax({
	    type: "POST",
	    url: "facebook_login.asp",
	    data: {
			"task": "GetValidName",
			"name": resultUser[0]['first_name'] + resultUser[0]['last_name']			
		},		
	    success: function(msg) {
	        $("#txtMemberIdFacebook").val(msg);
			$("#registermemberid_facebook").dialog({ autoOpen: false, width: 300, height: 300, modal: true, zIndex: 35000 });
			$("#registermemberid_facebook").dialog("option", "title", "Register");
			$("#registermemberid_facebook").dialog("open");
	    }
	});*/
	
	$("#registermemberid_facebook").dialog({ autoOpen: false, width: 500, height: 500, modal: true, zIndex: 35000 });
	$("#registermemberid_facebook").dialog("option", "title", "Register");
	$("#registermemberid_facebook").dialog("open");
}


function CheckUserAvailable(username) {
    if (username != "") {
        $.ajax({
            type: "GET",
            url: "facebook_login.asp",
            data: {
                task: "checkusername",
                usn: username,
				firstname: obj.first_name,
				lastname: obj.last_name
            },
            success: function (msg) {
                if (msg.indexOf("result=yes") > -1) {
                    $("#notavailable").show();
                    usernameisvalid = false;
                }
                else {
                    $("#notavailable").hide();
                    usernameisvalid = true;
                }
            }
        });
    }
}


function CheckUserNameHasExist(usn)
{
	if (CheckFieldEmpty(document.getElementById("txtMemberIdFacebook"), "Username"))
		return false;	
	if(CheckUsername(document.getElementById("txtMemberIdFacebook"),"Username") == false )
		return false;	
	
	var lbl = $("#registermemberid_facebook_notice");	
	$.ajax({
		   type: "GET",
		   url: "facebook_login.asp",
		   data: "task=checkusername&usn=" + usn,
		   success: function(msg){						   
				if(msg.indexOf("result=yes") > -1) {
					usernameisvalid = false;
					lbl.html("<div id='errorMsg'>Username already exists. Please type another.</div>");		
				}
				else {
					usernameisvalid = true;
					lbl.html("<div id='successMsg'>Username is available.</div>")		
				}
		   }
		 });	
}

function UpdateMemberIdFaceBook()
{
	if (CheckFieldEmpty(document.getElementById("txtMemberIdFacebook"), "Username"))
		return false;	
	if(CheckUsername(document.getElementById("txtMemberIdFacebook"),"Username") == false )
		return false;

	var txtUsername = $("#txtMemberIdFacebook");
	var lbl = $("#registermemberid_facebook_notice");

	postingdata.task = "addnewmember";
	postingdata.usn = txtUsername.val();
	postingdata.From = 2;


	$.ajax({
	    type: "POST",
	    url: "facebook_login.asp",
	    data: postingdata,		
	    success: function(msg) {
	        if (msg.indexOf("result=yes") > -1) {			
				//window.location.href = "fan_update.asp";
				if (window.location.href.indexOf("fan_register.asp") > -1) 
					window.location.href = "contest_directory.asp";
				else	
					window.location.href = window.location.href;
	        }
	        else {
	            lbl.html("<div id='errorMsg'>Username already exists. Please type another.</div>");
	        }
	    }
	});	
}

function validateEmail(email) {
    var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
    return email.match(re)
}
function RegisterMember(){
	var txtUsername = $("#Txt_FBUserName").val();
	
	if(CheckUsername($("#Txt_FBUserName").get(0),"Username")==false)
		return false;

	if (!usernameisvalid) {
	    alert("Username is not available. Please enter other username.");
	    return false;
    }
	
	var lbl = $("#notice");
    var dt = new Date();

    $.ajax({
        type: "POST",
        url: "facebook_login.asp?rdn=" + dt.getMilliseconds(),
        cache: false,
        data: {
            task: "addnewmember",
            usn: txtUsername,
            firstname: obj.first_name,
            lastname: obj.last_name,
            gender: obj.gender,
            email: obj.email,
            fb_id: obj.id,
            fb_apikey: fbapikey,
			From: 1	//FB app
        },
        success: function (msg) {
            if (msg.indexOf("result=yes") > -1) {
                ShowVideo();
            }
            else if (msg.indexOf("result=no") > -1) {
                $("#notavailable").show();
                lbl.html("");
            }
            else if (msg.indexOf("result=emailnull") > -1) {
                $("#notavailable").hide();

                lbl.html("<div class='errorMsg'>Can not get Facebook email.</div>");

                ShowHelp();

            }
            else {
                $("#notavailable").hide();

                lbl.html("<div class='errorMsg'>Unhandled error!!!</div>");
            }
        }
    });	
	return false;
}
  
var gLoginCode;
var postingdata = {};
var resultUser;
getInfoComplete = function (result, exception) {    
	
	postingdata = {
        "fb_id": result[0]['uid'],
        "firstname": result[0]['first_name'],
        "lastname": result[0]['last_name'],
        "gender": result[0]['sex'],
        "email": result[0]['email'],
        "apikey": fbapikey,
        "task": "login"
    }
	
	if (result[0]['email'] == "" ||result[0]['email'] == null )
		return;
		
	resultUser = result;

    var emailnullmsg = "Can not get your Facebook email.In order to continue this work, please remove MAS app with folowing steps:<br/><br/>";
    emailnullmsg += "1. Go to the Privacy Settings page from the \"Account\" drop-down menu located at the top of any page on Facebook.<br/>"
    emailnullmsg += "2. Click the \"Edit your settings\" link under the Applications and Websites section towards the bottom of the page.<br/>"
    emailnullmsg += "3. Click on the application you'd like to remove. If you don’t see the application listed, you can find it by clicking the Edit Settings button towards the top right-hand side of the page.<br/>"
    emailnullmsg += "4. You’ll then see an expanded view of your settings for that application. From here, you can click the \"Remove application\" link. Once you confirm you’d like to remove the application, it will no longer have access to your data and be removed from your profile, bookmarks, and your Applications and Games Dashboards.<br/>"


    if (alreadylogin == false) {
        FB.Connect.logout(function () {
            $.ajax({
                type: "GET",
                url: "facebook_login.asp",
                data: postingdata,
                success: function (msg) {
                    if (msg.indexOf("result=yes") > -1) {
                        //window.location.reload();
						if (window.location.href.indexOf("fan_register.asp") > -1) 
							window.location.href = "contest_directory.asp";
						else	
							window.location.href = window.location.href;
                    }
                    else if (msg.indexOf("result=disabled") > -1) {
                        alert("Your account is diabled.Please contact with Adminitrator.");
                    }
                    else if (msg.indexOf("result=emailnull") > -1) {
                        ShowJQueryNotice("dvNoticeEmailNull", 600, 300, "<div style='padding-top:5px;font-size:10pt'>" + emailnullmsg + "</div>", "Notice");
                    }
                    else // promt user for username
                        ShowRegisterMemberIdFaceBook();
                }
            });

        });
    }
    else {
        $.ajax({
            type: "GET",
            url: "facebook_login.asp",
            data: postingdata,
            success: function (msg) {
                if (msg.indexOf("result=yes") > -1) {
                    //window.location.reload();
                    //window.location.href = window.location.href;
                    //window.location.href = "fan_update.asp";
					
					if (window.location.href.indexOf("fan_register.asp") > -1) 
							window.location.href = "contest_directory.asp";
						else	
							window.location.href = window.location.href;
					
                }
                else if (msg.indexOf("result=disabled") > -1) {
                    alert("Your account is diabled.Please contact with Adminitrator.");
                }
                else if (msg.indexOf("result=emailnull") > -1) {
                    ShowJQueryNotice("dvNoticeEmailNull", 600, 300, "<div style='padding-top:5px;font-size:10pt'>" + emailnullmsg + "</div>", "Notice");
                }
                else // promt user for username
                    ShowRegisterMemberIdFaceBook();
            }
        });
    }
    //        FB.ApiClient.notifications_sendEmail(friends, "Testing proxy", "Testing proxy", "", mailSent);
};

promptUser = function() {  
	//check is user already granted for this permission or not       		
    facebook_prompt_permission('email', function(accepted) {
        if (accepted) {			
            // User (already) has permission					
            //fbapikey = FB.Facebook.apiKey;
            // set Method logout
            FB.Connect._logoutMethod = "no_ui";
            uid = FB.Connect.get_loggedInUser();
            var userInfo = 'uid,first_name,last_name,sex,proxied_email,email';
            FB.Facebook.apiClient.users_getInfo(uid, userInfo, getInfoComplete);
        }
        else {			
            //  User does not have permission
            alert(status + ' not granted');
        }
    });
}

var is_initialized = false;

// Ensure Facebook app is initialized and call callback afterward 
function ensure_init(callback) {	
	if (window.is_initialized) {
		callback();
    } else {
	
		FB_RequireFeatures(["XFBML"], function() {
            //FB.FBDebug.logLevel = 4;
            //FB.FBDebug.isEnabled = true;
            FB.Facebook.init(fb_apikey, 'xd_receiver.htm');
            window.is_initialized = true;
            callback();
        });		
    }
	
}
/*
* Prompts the user to grant a permission to the application.
*/
function facebook_prompt_permission(permission, callbackFunc) {
    ensure_init(function() {
        //check is user already granted for this permission or not
		FB.Facebook.apiClient.users_hasAppPermission(permission, function(result) {
			// prompt offline permission
			if (result == 0) {
				// render the permission dialog				
				FB.Connect.showPermissionDialog(permission, callbackFunc);
			} else {
				// permission already granted.				
				callbackFunc(true);
			}
		});
	});
}

/*FB SDK*/

function FBLogin() {
    try {
        FB.login(function (response) {
            if (response.authResponse) {
                FB.api('/me', function (response) {

                    var emailnullmsg = "Can not get your Facebook email.In order to continue this work, please remove MAS app with folowing steps:<br/><br/>";
                    emailnullmsg += "1. Go to the Privacy Settings page from the \"Account\" drop-down menu located at the top of any page on Facebook.<br/>"
                    emailnullmsg += "2. Click the \"Edit your settings\" link under the Applications and Websites section towards the bottom of the page.<br/>"
                    emailnullmsg += "3. Click on the application you'd like to remove. If you don’t see the application listed, you can find it by clicking the Edit Settings button towards the top right-hand side of the page.<br/>"
                    emailnullmsg += "4. You’ll then see an expanded view of your settings for that application. From here, you can click the \"Remove application\" link. Once you confirm you’d like to remove the application, it will no longer have access to your data and be removed from your profile, bookmarks, and your Applications and Games Dashboards.<br/>"

                    postingdata.fb_id = response.id;
                    postingdata.firstname = response.first_name;
                    postingdata.lastname = response.last_name;
                    postingdata.gender = response.gender;
                    postingdata.email = response.email;
                    postingdata.country = response.locale;
                    postingdata.birthday = response.birthday;
                    postingdata.task = "login";

                    $.ajax({
                        type: "GET",
                        url: "facebook_login.asp",
                        data: postingdata,
                        success: function (msg) {
                            if (msg.indexOf("result=yes") > -1) {
                                FB.logout(function (response) {
                                    if (window.location.href.indexOf("fan_register.asp") > -1)
                                        window.location.href = "contest_directory.asp";
                                    else
                                        window.location.href = window.location.href;
                                });
                            }
                            else if (msg.indexOf("result=disabled") > -1) {
                                FB.logout(function (response) {
                                    alert("Your account is diabled.Please contact with Adminitrator.");
                                });
                            }
                            else if (msg.indexOf("result=emailnull") > -1) {
                                ShowJQueryNotice("dvNoticeEmailNull", 600, 300, "<div style='padding-top:5px;font-size:10pt'>" + emailnullmsg + "</div>", "Notice");
                            }
                            else // promt user for username
                                ShowRegisterMemberIdFaceBook();
                        }
                    });

                });
            }
            else {
                console.log('User cancelled login or did not fully authorize.');
            }
        }, { scope: 'email' });
    }
    catch (e) { }
}

function Logout() {
    FB.logout(function (response) {
        console.log('Logged out.');
    });
}

