﻿
//Gigya Area Ends -  User detail
var UGUID = -1; //Last  login user social network id
var CSUID = 0; //Last  login user coke studio id
var UNAME = ""; //Last  login user email
var UEMAIL = -1; //Last  login social network name
var SNNAME;
var sIn;

// This method is activated when page is loaded
function printResponse(response) {
    if (response.errorCode == 0) {
        //Log user logout time
        //alert('User has logged out');

    }
    else {
        //Log in databse on failure
        // alert('Error :' + response.errorMessage);    
    }
}
function onGigyaLoad() {
    // register for login event
    //console.log("inside gigya load function");

    gigya.services.socialize.addEventHandlers(conf, {
        context: { str: 'congrats on your' }
					, onLogin: onLoginHandler
					, onLogout: onLogoutHandler
    });

}

// onLogin Event handler


function onLoginHandler(eventObj) {
    //close fancybox
    $("#fancybox-close").trigger("click");

    //make ajax request on current page
    //var url = document.URL;
    //console.log(page);


    //  alert("out");
    //refresh page content by using ajax call


    /*  alert(eventObj.context.str + ' ' + eventObj.eventName + ' to ' + eventObj.provider
    + '!\n' + eventObj.provider + ' user ID: ' + eventObj.user.identities[eventObj.provider].providerUID);*/
    // verify the signature ...
    verifyTheSignature(eventObj.UID, eventObj.timestamp, eventObj.signature);
    GUID = eventObj.UID;
    UGUID = eventObj.UID;
    //create cookie now
    createCookie('guid_', UGUID, 7);

    SNNAME = eventObj.provider;
    //alert("guid1:" + GUID);
    //alert("eventObj.provider :"+eventObj.provider );
    //alert(('Your UIDA: ' + eventObj.UID + '\n timestamp: ' + eventObj.timestamp + '\n signature: ' + eventObj.signature));
    // Check whether the user is new by searching if eventObj.UID exists in your database

    // TestMethod(name, email, imgSrc);

    var param1 = new Array();
    //string firstName,string  lastName,string ,int ,string  ,string

    param1[0] = "UID :'" + eventObj.UID + " '"
    param1[1] = "provider :'" + SNNAME + " '"
    var URL = "CSUser.aspx/AddUserAndSocialNetwork";

    LocalizeSocialUser(URL, param1);

    var newUser = true; // lets assume the user is new

    if (newUser) {
        // 1. Register user 
        // 2. Store new user in DB
        // 3. link site account to social network identity
        //   3.1 first construct the linkAccounts parameters
        var dateStr = Math.round(new Date().getTime() / 1000.0); // Current time in Unix format
        //(i.e. the number of seconds since Jan. 1st 1970)

        var siteUID = 'uTtCGqDTEtcZMGL08w'; // siteUID should be taken from the new user record
        // you have stored in your DB in the previous step
        var yourSig = createSignature(siteUID, dateStr);

        var params = {
            siteUID: siteUID,
            timestamp: dateStr,
            signature: yourSig
        };

        //   3.1 call linkAccounts method:
        gigya.services.socialize.linkAccounts(conf, params);
    }

    // NOW get user information

    gigya.services.socialize.getUserInfo(conf, { callback: renderUI });

    //sIn = setInterval(timedRefresh, 2000);
    /* Selef executing recursive func based on 1 second time
    -------------------------------------------------------------------------------------------------*/
    var userID = 0;
    (function timedRefresh() {

        // alert("najam sikander awan" + this);
        userID = readCookie("userid_");
        if (userID == 0) {
            sIn = setTimeout(timedRefresh, 1000);
        }
        else {
            //cookie returning value
            //alert(userID);
            clearTimeout(sIn);
            ResizeGigya();
            LoggedIn();
            ajaxShowPage(page);
            GetPlayList();
            
        }
    })();
    
//    ResizeGigya();
//    LoggedIn();    
    //PlayListActionsUI(true);
}


//function timedRefresh() {
//    var userID = readCookie("userid_");
//    if (userID == 0)
//    { }
//    else {
//        ajaxShowPage(page);
//        GetPlayList();
//        clearInterval(sIn);
//    }
//}


function renderUI(res) {    

    //console.log(res);
    
    
    if (res.user != null && res.user.isConnected) {        
 
        UNAME = res.user.firstName + " " + res.user.lastName;
        UEMAIL = res.user.email;

        eraseCookie("UNAME_");
        eraseCookie("UEMAIL_");
   
        if (UNAME.length > 0)
            createCookie('UNAME_', UNAME, 7);
        if (UEMAIL.length > 0)
            createCookie('UEMAIL_', UEMAIL, 7);
            
            

        var imgSrc = "http://cdn.gigya.com/site/images/bsAPI/Placeholder.gif";

        if (res.user.thumbnailURL.length > 0)
            imgSrc = res.user.thumbnailURL;

        var param = new Array();
        //string firstName,string  lastName,string ,int ,string  ,string
        param[0] = "firstName:'" + res.user.firstName + " '"
        param[1] = "lastName :'" + res.user.lastName + " '"
        param[2] = "email :'" + UEMAIL + " '"
        param[3] = "NetworkName :'" + SNNAME + " '"
        param[4] = "profileimg :'" + imgSrc + " '"
        param[5] = "UID :'" + GUID + " '"

    
        var URL = "CSUser.aspx/AddEditWithSocialNetwork";
        var useridd = LocalizeSocialUser(URL, param);
        useridd = readCookie("userid_");
        //adding user profile info on First time login
        var profileURL = "Users/EditProfile.aspx/AddProfileOnLogin";
        //AddEditProfile(profileURL, userId, email, mobile, streetAddress1, streetAddress2, city, country, zipCode, webSite, bio, favQuote, profileImage, gender, dateOfBirth);

        AddEditProfile(profileURL, readCookie("userid_"), UEMAIL, "", "", "", "", "", "", "", "", "", imgSrc, "", "", "", "");
       
        PopulateUserInfo("loginForm");
        $("#btnLogout").removeClass("none");

        //make ajax call and refresh the page
        //  alert(document.URL);
        //window.location = document.URL;

    } else {

        //do nothing
        // document.getElementById("profile").style.display = "none";
    }
}

// Note: the actual signature calculation implementation should be on server side
function createSignature(UID, timestamp) {
    return '';
}

// Note: the actual signature calculation implementation should be on server side
function verifyTheSignature(UID, timestamp, signature) {

    //alert('Your UID: ' + UID + '\n timestamp: ' + timestamp + '\n signature: ' + signature);
}

// Logout from Gigya platform. This method is activated when "Logout" button is clicked
function logoutFromGS() {
    //alert("df");
    eraseCookie('userid_');
    eraseCookie('guid_');
    eraseCookie('UNAME_');
    eraseCookie('UEMAIL_');
    eraseCookie('userid_');
    $("#btnLogout").addClass("none");
    gigya.services.socialize.logout(conf, { callback: printResponse/*no required params*/
    }); // logout from Gigya platform
}

// onLogout Event handler
function onLogoutHandler(eventObj) {

    $("#user").html("");
    eraseCookie('guid_');
    eraseCookie('UNAME_');
    eraseCookie('UEMAIL_');
    eraseCookie('userid_');

    //refresh the page after logout
    //alert(page.toLowerCase());
    //users / MyCokeStudio.aspx
    //Users / Profile.aspx
    var userPage = page.toLowerCase().indexOf("users/");
    //alert(page.toLowerCase().indexOf("users/"));
    
    //Redirect user on home page if user logout from his/her personal page
    if (userPage == "-1") {
        ajaxShowPage(page);
    }
    else {        
        var URL = "http:// " + window.location.hostname + "/default.aspx";        
        window.location = "default.aspx";
    }
    
    //    document.getElementById('status').style.color = "red";
    //    document.getElementById('status').innerHTML = "Status: You are now signed out";
    ResizeGigya();
    LoggOut();
    GetPlayList();
    //PlayListActionsUI(false);
}



try {
    gigya.services.socialize.showLoginUI(conf, {
        height: '85'
	        , width: '360'
			, showTermsLink: false // remove 'terms' link
			, useHTML: true  // Use the HTML implementation of widget (rather then Flash implementation)
			, buttonsStyle: 'standard' // Change the default buttons design to "Full Logos" design
			, showWhatsThis: true // Pop-up a hint describing the Login Widget, when the user rolls over the Gigya link.
	        , containerID: 'loginDiv' // The component will embed itself inside the loginDiv Div
	        , enabledProviders: 'facebook, myspace, twitter, google'
	        , UIConfig: '<config><body><controls><snbuttons buttonsize="15"></snbuttons></controls></body></config>'
    });
}
catch (e) {
    // alert(e); eat exception
}

jQuery(function($) {



});  
       

