﻿
var J$ = jQuery.noConflict();
J$(document).ready(function() {

  
    try {
        var type = J$.url.param("t");
        var uid = J$.url.param("u");
        if (type != "") {
            DisassocaiteFacebookAccount(uid);
        }
    }
    catch (Error) {
        TraceError(Error.message, 'document.ready:fbconnect.js');

    }

});

// Unlink facebook user account form virtaul app user

function DisassocaiteFacebookAccount(userid) {
    try {
        var details = {
            userid: userid
        };
        var user_serialized = Sys.Serialization.JavaScriptSerializer.serialize(details);
        J$.ajax({
            url: Service_Path + 'FBConnect.svc/DisAssociateAccount',
            type: 'POST',
            contentType: 'application/json;charset=utf-8',
            data: user_serialized,
            success: function(response) {
                try {
                    var results = "";
                    results += "<div class='SmlPopMNBgCt'>";
                    results += "<div><img src='http://virtualevent.s3.amazonaws.com/images/common/sml_rndtopcrv.png' /></div>";
                    results += "<div class='SmlPopMnNpCtMN'>";
                    results += "<div class='SmlPopMidmnCT'>";
                    results += "<div class='SmlPopBlnkWhtCt'>";
                    results += "<div class='SmlPopUserMn'>";
                    results += "<div class='SmlPopMhed_MnCT'>";
                    results += "<div class='SmlPopHedCtMnCcn' style='width:250px;'>Facebook Account Disassociation</div>";
                    results += "<div class='SmlClostab'><a onclick=HidePopUp('popOnDemand') title='Close' style='cursor:pointer' ><img src='http://virtualevent.s3.amazonaws.com/images/common/rnd_close_icn.png' /></a></div>";
                    results += "</div>";
                    results += "<div class='SmlPopMidWknAra'>";
                    // results += "<div class='SmlPopLoder'><img src='http://virtualevent.s3.amazonaws.com/images/common/virlodim.gif' /></div>";
                    results += "<div class='RgIdTxtCT'>You have successfully unlinked from your facebook account.</div>";
                    results += "<div class='ThrdBmnCt'>";
                    results += "<div class='SmlPopDnw_btCt'><input onclick=HidePopUp('popOnDemand') name='' type='button' value='Ok' title='Ok' style='width:34px;height:28px' /></div>";
                    results += "</div></div></div></div></div>";
                    results += "<div><img src='http://virtualevent.s3.amazonaws.com/images/common/sml_rndbotcrv.png' /></div>";
                    results += "</div></div>";
                    J$('#popOnDemand').attr('innerHTML', results);
                    GetCenterPosition("popOnDemand");
                    J$('#popOnDemand').show(2000);
                }
                catch (Error) {
                    TraceError(Error.message, 'DisassocaiteFacebookAccount:fbconnect.js');

                }
            },
            failure: function(response) {
            }
        });
    }
    catch (Error) {
        TraceError(Error.message, 'DisassocaiteFacebookAccount:fbconnect.js');

    }
}


function LoginUser(confid) {
    confid = 1;
    if (ValidateUser()) {
        if (confid == "") {
            ShowAlertPopUp("Some error in login please refresh your page");
        }
        else {
            J$("#loginDiv").attr("innerHTML", "<input id='btnlogin' type='button' value='Logging...' style='width:80px; height:30px' />&nbsp;<img id='loadingimg' src='http://virtualevent.s3.amazonaws.com/images/common/virlodim.gif'  />");
        }
        var user = {
            confrenceid: confid,
            login: J$.trim(J$('#emailtxt').val()),
            password: J$.trim(J$('#passtxt').val()),
            authmode: 1
        };


        var user_serialized = Sys.Serialization.JavaScriptSerializer.serialize(user);
        J$.ajax({
            url: Service_Path + 'Authentication.svc/GetOneUserAuthentication',
            type: 'POST',
            contentType: 'application/json;charset=utf-8',
            data: user_serialized,
            success: function(response) {
                if (eval(response)[0].Message[0].StatusCode == "101") {
                    var xmlstring = eval(response)[0].Message[0].ReturnValue;
                    var xmlRes = ffLoadXMLBrowser(xmlstring);
                    var user = {
                        Password: J$.trim(J$('#passtxt').val()),
                        HashPassword: xmlRes.childNodes[0].getElementsByTagName('Password')[0].childNodes[0].nodeValue
                    };
                    var users = Sys.Serialization.JavaScriptSerializer.serialize(user);
                    J$.ajax({
                        url: Service_Path + 'Exhibithall.svc/GetEncryptPass',
                        type: 'POST',
                        contentType: 'application/json;charset=utf-8',
                        data: users,
                        success: function(result) {
                            if (eval(result)[0].CompareResult != null) {
                                if (eval(result)[0].CompareResult == "Excep" || eval(result)[0].CompareResult == "False") {
                                    ShowAlertPopUp("Your password and email does not match.");
                                    J$("#loginDiv").attr("innerHTML", "<input id='btnlogin' type='button' value='Login' onclick=LoginUser(" + confid + ") style='width:80px; height:30px' />");
                                }
                                else {
                                    J$.post(Domain_Path + "GlobalHandler.ashx?ConfId=1&UserId=" + xmlRes.getElementsByTagName("UserId")[0].childNodes[0].nodeValue,
                                                                                   { post: xmlRes.getElementsByTagName("UserId")[0].childNodes[0].nodeValue },

                                                                              function(resp) {
                                                                                  UpdateOneUserLoginHistory(xmlRes.getElementsByTagName("UserId")[0].childNodes[0].nodeValue);
                                                                                  if (J$('#hdUrl').val() != "") {
                                                                                      top.location.href = J$('#hdUrl').val();
                                                                                  }
                                                                                  else {
                                                                                      top.location.href = Domain_Path + "SChk.aspx";

                                                                                  }

                                                                                  J$('#hdUrl').val("");
                                                                              }

                                                                            );
                                }
                            }
                        },
                        failure: function(response) {
                            ShowAlertPopUp("Your password and email does not match.")
                            J$("#loginDiv").attr("innerHTML", "<input id='btnlogin' type='button' value='Login' onclick=LoginUser(" + confid + ") style='width:80px; height:30px' />");
                        }
                    });
                }
                else {
                    ShowAlertPopUp(eval(response)[0].Message[0].Description)
                    J$("#loginDiv").attr("innerHTML", "<input id='btnlogin' type='button' value='Login' onclick=LoginUser(" + confid + ") style='width:80px; height:30px' />");
                }
            },
            failure: function(response) {
                ShowAlertPopUp("Please enter your email address and password to login.");
                J$("#loginDiv").attr("innerHTML", "<input id='btnlogin' type='button' value='Login' onclick=LoginUser(" + confid + ") style='width:80px; height:30px' />");
            }
        });
    }
    else {
        J$("#loginDiv").attr("innerHTML", "<input id='btnlogin' type='button' value='Login' onclick=LoginUser(" + confid + ") style='width:80px; height:30px' />");
        return false;
    }
}

function ValidateUser(confid) {
    try {
        if (J$.trim(J$('#emailtxt').val()) == "" && J$.trim(J$('#passtxt').val()) == "") {
            ShowAlertPopUp("Please enter your email address and password to login.");
            return false;
        }
        else if (J$.trim(J$('#emailtxt').val()) == "") {
            ShowAlertPopUp("Please enter your email address to login.");
            return false;
        }
        else if (CheckEmail('emailtxt') != true) {
            ShowAlertPopUp("Please enter a valid email address to login.");
            return false;
        }

        else if (J$.trim(J$('#passtxt').val()) == "") {
            ShowAlertPopUp("Please enter your password to login.");
            return false;
        }

        else if (validateHtmlTags('emailtxt') != true) {
            J$('#emailtxt').focus();
            ShowAlertPopUp("You cannot put html tag into email address");
            return false;
        }
        else if (validateHtmlTags('passtxt') != true) {
            J$('#passtxt').focus();
            ShowAlertPopUp("You cannot put html tag into password");
            return false;
        }
    }
    catch (Error) {
        TraceError(Error.message, 'ValidateUser:fbconnect.js');
        return false;
    }
    return true;
}
function ffLoadXMLBrowser(xmlData) {
    try { //Internet Explorer
        xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async = "false";
        xmlDoc.loadXML(xmlData);
    } catch (e) { //Firefox et. all
        try {
            parser = new DOMParser();
            xmlDoc = parser.parseFromString(xmlData, "text/xml");
        } catch (e) {
            //alert(e.message)
        }
    }
    return xmlDoc;
}



function facebook_onload(already_logged_into_facebook) {
    try {
        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 == already_logged_into_facebook) {

                    return;
                }

                refresh_page();
            });
        });
    }
    catch (Error) {
        TraceError(Error.message, 'facebook_onload:fbconnect.js');
     
    }
}


function facebook_onlogin_ready() {
    try {
        refresh_page();
    }
    catch (Error) {
        TraceError(Error.message, 'facebook_onlogin_ready:fbconnect.js');

    }
}


function refresh_page() {
    try {
        var i = 0;
        var sessionkey = FB.Facebook.apiClient.get_session() ? FB.Facebook.apiClient.get_session().session_key : null;
        var Fbuid = FB.Facebook.apiClient.get_session() ? FB.Facebook.apiClient.get_session().uid : null;
        CheckAvailbility(sessionkey, Fbuid);
    }
    catch (Error) {
        TraceError(Error.message, 'refresh_page:fbconnect.js');

    }
}



function CheckAvailbility(sessionkey, Fbuid) {
    try {
        var reqParams = {
            confrenceid: 1,
            login: Fbuid,
            authmode: 2
        };

        var reqParams_Serialized = Sys.Serialization.JavaScriptSerializer.serialize(reqParams);
        J$.ajax({
            url: Service_Path + 'Authentication.svc/GetOneUserAuthentication',
            type: 'Post',
            contentType: 'application/json;charset=utf-8',
            data: reqParams_Serialized,
            success: function(response) {
                var post = "";
                try {
                    var status_code = eval(response)[0].Message[0].StatusCode;
                    if (status_code == "-101") {
                        FB.Connect.logout();
                        ShowAlertPopUp("You are not authenticated user.");
                        //top.location.href = Domain_Path + "Microsite/FbReg.aspx?sessionkey=" + sessionkey + "&uid=" + Fbuid;
                    }
                    else if (status_code == "-102") {
                        ShowAlertPopUp("Error coming please try again.");
                    }
                    else {

                        var xmlstring = eval(response)[0].Message[0].ReturnValue;
                        var xmlRes = ffLoadXMLBrowser(xmlstring);
                        var userid = xmlRes.getElementsByTagName("UserId")[0].childNodes[0].nodeValue;

                        J$.post(Domain_Path + "GlobalHandler.ashx?ConfId=1&UserId=" + userid + "&Fbuid=" + Fbuid + "&sessionkey=" + sessionkey,
                       { post: userid },
                  function(resp) {
                      top.location.href = Domain_Path + "SChk.aspx";
                  });
                    }
                }
                catch (Error) {
                    TraceError(Error.message, 'CheckAvailbility:fbconnect.js');

                }
            },
            failure: function(response) {
                res = response;
            }
        });
    }
    catch (Error) {
        TraceError(Error.message, 'CheckAvailbility:fbconnect.js');

    }
}


function SetLogin(e) {
    try {
        var keyCode = e.keyCode;
        if (keyCode == 13) {
           

            $("#btnlogin2").click();
        }
    }
    catch (Error) {
        TraceError(Error.message, 'SetLogin:fbconnect.js');

    }

}

function ForgotPass() {
    try {

        var fhtml = "<div id='FPopOutContVrp'>";
        fhtml += "<div><img src='http://virtualevent.s3.amazonaws.com/images/common/tpcrve215img.png' width='415' /></div>";
        fhtml += "<div id='FPopColrContvpr' >";
        fhtml += "<div id='FPopColorWhtContVpr' style='width:415px; clear:both; margin:auto' >";
        fhtml += "<div id='PCmthedContVpr' style='width:395px;margin-left:10px'>";
        fhtml += "<div class='cmtheadcongtvpr' style='width:200px'>Forgot Password</div>";
        fhtml += "<div style='width:30px; float:left; display:none' id='dvResLoad'><img src='http://virtualevent.s3.amazonaws.com/images/common/virlodim.gif' /></div>";
        fhtml += "<div class='ClsNwRndCt' ><a style='cursor:pointer' onclick='HideFPassPopup()'  title='Close'><img src='http://virtualevent.s3.amazonaws.com/images/common/rnd_close_icn.png' /></a></div>";
        fhtml += "</div>";
        fhtml += "<div class='PswdMidWokCt'>";
        fhtml += "<div class='PsSucEmCt'>Your passoword will be sent to your registerd email address.</div>";
        fhtml += "<input type='text' value='Enter Your Registered Email Address' onfocus=ChangeResetText('focus'); onblur=ChangeResetText('blur');  id='txtFPassMail'/>";
        fhtml += "</div>";
        fhtml += "<div class='RestpswBt'>";
        fhtml += "<input type='button' value='Reset Password' class='FPopButnw' onclick='checkFPassdata();' />";
        fhtml += "</div>";
        fhtml += "</div>";
        fhtml += "</div>";
        fhtml += "<div><img src='http://virtualevent.s3.amazonaws.com/images/common/btcrve215img.png' width='415' /></div>";
        fhtml += "</div>";

        J$("#dvForgotpass").attr("innerHTML", fhtml);
        centerAlertPopup("dvForgotpass");
        J$("#dvForgotpass").show(1000);
    }
    catch (Error) {
        TraceError(Error.message, 'ForgotPass:fbconnect.js');
    }

}

function HideFPassPopup() {
    J$("#dvForgotpass").hide(1000);
    J$("#txtFPassMail").val("Enter Your Registered Email Address");
}

function CheckEmail(id) {
    try {
        var str = J$.trim(J$("#" + id).val());
        var filter = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
        if (filter.test(str))
            return true;
        else {
            return false;
        }
    }
    catch (Error) {
        TraceError(Error.message, 'FBConnect.js:CheckEmail');
        return false;
    }
}

function checkFPassdata() {
    try {
        if (J$.trim(J$("#txtFPassMail").val()) != "" && J$("#txtFPassMail").val() != "Enter Your Registered Email Address") {
            if (CheckEmail("txtFPassMail")) {
                J$("#dvResLoad").show();
                ResetForgotPass();
            }
            else {
                ShowAlertPopUp("Enter correct email address");
                return false;
            }
        }
        else {
            ShowAlertPopUp("Enter your email address");
            return false;
        }
    }
    catch (Error) {
        TraceError(Error.message, 'checkFPassdata:fbconnect.js');
        return false;
    }
}

function ResetForgotPass() {
    try {
        var pass = randomString(8, 'abcdefghijklmnopqrstuvwxyz0123456789');
        var FPass = {
            ConferenceId: 1,
            Email: J$("#txtFPassMail").val(),
            OldPassword: pass
        }
        var json = Sys.Serialization.JavaScriptSerializer.serialize(FPass);
        J$.ajax({
            url: Service_Path + "Authentication.svc/ForgotPassword",
            type: 'Post',
            contentType: 'application/json;charset=utf-8',
            data: json,
            success: function(response) {
                try {
                    var data = eval(response);
                    if (data[0].Message != null) {
                        if (data[0].Message[0].StatusCode == "101") {
                            J$("#dvForgotpass").hide();
                            ShowAlertPopUp("Your password has been reset.<br />An email has been sent to <b>" + J$("#txtFPassMail").val() + "</b> ");
                            var FMail = {
                                ConfTitle: "Social27 Password Reset Confirmation",
                                SenderEmail: "social27@virtual.com",
                                RecieverEmail: J$("#txtFPassMail").val(),
                                SenderName: "Social27",
                                RecieverName: "",
                                Message: "You recently requested a new password.<br /><br />Here is your reset password<br />" + pass + ""
                            }
                            J$("#txtFPassMail").val("Enter Your Registered Email Address");
                            var json = Sys.Serialization.JavaScriptSerializer.serialize(FMail);
                            J$.ajax({
                                url: Service_Path + "Exhibithall.svc/SendMessageByEmail",
                                type: 'Post',
                                contentType: 'application/json;charset=utf-8',
                                data: json,
                                success: function(response) {
                                },
                                failure: function(response) {
                                    ShowAlertPopUp(response);
                                }
                            });
                        }
                        else {
                            ShowAlertPopUp("Your email address is not correct");
                        }
                    }
                }
                catch (Error) {
                    TraceError(Error.message, 'ResetForgotPass:fbconnect.js');
                  
                }
            },
            failure: function(response) {
                ShowAlertPopUp(response);

            }
        });
    }
    catch (Error) {
        TraceError(Error.message, 'ResetForgotPass:fbconnect.js');
      
    }
}



function randomString(len, charSet) {
    charSet = charSet || 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    var randomString = ''; for (var i = 0; i < len; i++) {
        var randomPoz = Math.floor(Math.random() * charSet.length);
        randomString += charSet.substring(randomPoz, randomPoz + 1);
    }
    return randomString;
}


function ChangeResetText(action) {
    try {
        if (action == "focus") {
            if (J$("#txtFPassMail").val() == "Enter Your Registered Email Address") {
                J$("#txtFPassMail").val("");
            }
        }
        else {
            if (J$("#txtFPassMail").val() == "") {
                J$("#txtFPassMail").val("Enter Your Registered Email Address");
            }
        }
    }
    catch (Error) {
        TraceError(Error.message, 'ChangeResetText:fbconnect.js');

    }
}


function TraceError(desc, fname) {
    try {
        var obj = {
            shortdesc: desc,
            pagename: top.location.href,
            Browser: navigator.appName,
            comment: 'Error coming on ' + fname,
            projectname: 'Virtual Event Platform'

        };
        var json = Sys.Serialization.JavaScriptSerializer.serialize(obj);
        J$.ajax(
            {
                url: Service_Path + 'Settings.svc/TraceError',
                type: 'POST',
                contentType: 'application/json;charset=utf-8',
                data: json,
                success: function(response) {
                },
                failure: function(response) {
                }
            });
    }
    catch (Error) {
    }
}

function ShowAlertPopUp(value) {
    try {
        var fhtnl = "<div class='MinMsgCt'>";
        fhtnl += "<div><img src='http://virtualevent.s3.amazonaws.com/images/common/tpcrve215img.png' /></div>";
        fhtnl += "<div class='ManMsgInct'>";
        fhtnl += "<div class='ManMsgintxt' id='dvinnerval'></div>";
        fhtnl += "</div>";
        fhtnl += "<div><img src='http://virtualevent.s3.amazonaws.com/images/common/btcrve215img.png' /></div>";
        fhtnl += "</div>";
        J$("#dvAlertPop").attr("innerHTML", fhtnl);
        centerAlertPopup("dvAlertPop");
        J$("#dvAlertPop").show(1000);
        J$("#dvinnerval").attr("innerHTML", value);
        setTimeout("HideAlertPopup()", 2000);
    }
    catch (Error) {
        TraceError(Error.message, 'FBConnect.js:ShowAlertPopUp');
    }
}

function HideAlertPopup() {
    J$("#dvAlertPop").hide(1000);
}














function centerAlertPopup(divId) {
    try {
        var windowDim = getWindowSize();
        var popupHeight = J$("#" + divId).height();
        var popupWidth = J$("#" + divId).width();
        var scroll = getScrollXY();
        J$("#" + divId).css({
            "position": "absolute",
            "top": windowDim.Y / 2 - popupHeight / 2 + scroll.Y,
            "left": windowDim.X / 2 - popupWidth / 2 + scroll.X
        });
    }
    catch (Error) {
        TraceError(Error.message, 'FBConnect.js:centerAlertPopup');
    }

}

function GetCenterPosition(elementid) {
    try {
        var windowDim = getWindowSize();
        var popupHeight = 300;
        var popupWidth = jQuery("#" + elementid).width();
        var scroll = getScrollXY();
        J$("#" + elementid).css({
            "top": windowDim.Y / 2 - popupHeight / 2 + scroll.Y,
            "left": windowDim.X / 2 - popupWidth / 2 + scroll.X
        });
        J$("#" + elementid).css({
            "height": popupHeight
        });
    }
    catch (Error) {
        TraceError(Error.message, 'FBConnect.js:GetCenterPosition');
    }
}


function getWindowSize() {
    try {
        var myWidth = 0, myHeight = 0;
        if (typeof (window.innerWidth) == 'number') {
            //Non-IE 
            myWidth = window.innerWidth;
            myHeight = window.innerHeight;
        } else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
            //IE 6+ in 'standards compliant mode' 
            myWidth = document.documentElement.clientWidth;
            myHeight = document.documentElement.clientHeight;
        } else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
            //IE 4 compatible 
            myWidth = document.body.clientWidth;
            myHeight = document.body.clientHeight;
        }
        return { X: myWidth, Y: myHeight }
    }
    catch (Error) {
        TraceError(Error.message, 'FBConnect.js:getWindowSize');
    }
}

function getScrollXY() {
    try {
        var scrOfX = 0, scrOfY = 0;
        if (typeof (window.pageYOffset) == 'number') {
            //Netscape compliant 
            scrOfY = window.pageYOffset;
            scrOfX = window.pageXOffset;
        } else if (document.body && (document.body.scrollLeft || document.body.scrollTop)) {
            //DOM compliant 
            scrOfY = document.body.scrollTop;
            scrOfX = document.body.scrollLeft;
        } else if (document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollTop)) {
            //IE6 standards compliant mode 
            scrOfY = document.documentElement.scrollTop;
            scrOfX = document.documentElement.scrollLeft;
        }
        return { X: scrOfX, Y: scrOfY };
    }
    catch (Error) {
        TraceError(Error.message, 'FBConnect.js:getScrollXY');
    }
}



function VerifyActivationCode(ActivationCode, conferenceID) {
    var reqParams = {
        ConferenceId: conferenceID,
        activationCode: ActivationCode
    };
    var reqParams_Serialized = Sys.Serialization.JavaScriptSerializer.serialize(reqParams);
    J$.ajax({
        url: Service_Path + 'Authentication.svc/ActivateOneUser',
        type: 'POST',
        contentType: 'application/json;charset=utf-8',
        data: reqParams_Serialized,
        cache: false,
        success: function(response) {
            try {
                response = eval(response);
                if (response.length > 0) {
                    if (response[0].Message[0].StatusCode == "101") {
                    }
                    else {
                        ShowAlertPopUp(response[0].Message[0].Description);
                    }
                }
                else {
                    FavBoothHtml += "<br /><div>no data return</div>";
                }
            }
            catch (Error) {
                TraceError(Error.message, 'FBConnect.js:VerifyActivationCode');
            }
        },
        failure: function(response) {
        }
    });
}



function validateHtmlTags(txtboxid) {
    var ret = false;
    try {
        str = J$("#" + txtboxid).val();
        if (str.match(/([\<])([^\>]{1,})*([\>])/i) != null) {
            ret = false;
        }
        ret = true;
    }
    catch (Error) {
        TraceError(Error.message, 'FBConnect.js:validateHtmlTags');
    }
    return ret;
}


function UpdateOneUserLoginHistory(userid) {
    try {
        var User = {
            UserId: userid
        }
        var json = Sys.Serialization.JavaScriptSerializer.serialize(User);
        J$.ajax({
            url: Service_Path + 'authentication.svc/UpdateOneUserLoginHistory',
            type: 'Post',
            contentType: 'application/json;charset=utf-8',
            data: json,
            success: function(response) {
            },
            failure: function(response) {
            }
        });
    }
    catch (Error) {
        TraceError(Error.message, 'FBConnect.js:UpdateOneUserLoginHistory');
    }
}