public ActionResult Link(FormCollection fc)
        {
            SynapseResponse response = new SynapseResponse();

            if (MyUtility.isUserLoggedIn()) //User is logged in.
            {
                response.errorCode = (int)ErrorCodes.IsAlreadyAuthenticated;
                response.errorMessage = "User is already authenticated.";
                return this.Json(response, JsonRequestBehavior.AllowGet);
            }

            try
            {
                string EmailAddress = fc["EmailAddress"];
                string Password = fc["Password"];
                var context = new IPTV2Entities();
                var user = context.Users.FirstOrDefault(u => String.Compare(u.EMail, EmailAddress, true) == 0);
                if (user == null)
                {
                    response.errorCode = (int)ErrorCodes.UserDoesNotExist;
                    response.errorMessage = "User does not exist.";
                }
                else
                {
                    Password = MyUtility.GetSHA1(Password);
                    if (String.Compare(user.EMail, EmailAddress, true) == 0 && String.Compare(user.Password, Password, false) == 0)
                    {
                        /** notifyRegistration **/
                        Dictionary<string, object> regCollection = new Dictionary<string, object>();

                        regCollection.Add("siteUID", user.UserId.ToString());
                        if (!String.IsNullOrEmpty(fc["UID"]))
                        {
                            regCollection.Add("uid", Uri.UnescapeDataString(fc["UID"]));
                            regCollection.Add("cid", String.Format("{0} - New User", fc["provider"]));
                        }
                        GSResponse notifyRegistration = GigyaHelpers.createAndSendRequest("socialize.notifyRegistration", GigyaHelpers.buildParameter(regCollection));

                        if (notifyRegistration.GetErrorCode() == 0) //Successful link
                        {
                            GSResponse res = GetToken(user);
                            if (res != null)
                            {
                                SynapseToken token = new SynapseToken()
                                {
                                    uid = user.UserId.ToString(),
                                    token = res.GetString("access_token", String.Empty),
                                    expire = res.GetInt("expires_in", 0),
                                };

                                response.data = token;
                            }
                            response.errorCode = (int)ErrorCodes.Success;
                            response.errorMessage = "Linking successful!";
                            HttpCookie authCookie = SetAutheticationCookie(user.UserId.ToString());
                            SynapseCookie cookie = new SynapseCookie()
                            {
                                cookieName = authCookie.Name,
                                cookieDomain = authCookie.Domain,
                                cookiePath = authCookie.Path,
                                cookieValue = authCookie.Value
                            };
                            response.info = cookie;
                        }
                        else
                        {
                            response.errorCode = (int)ErrorCodes.FailedToLinkAccount;
                            response.errorMessage = "Unable to link your account. Please try again." + notifyRegistration.GetErrorMessage() + " " + notifyRegistration.GetErrorCode();
                        }
                    }
                    else
                    {
                        response.errorCode = (int)ErrorCodes.IsWrongPassword;
                        response.errorMessage = "Invalid email/password combination.";
                    }
                }
            }
            catch (Exception) { throw; }
            return this.Json(response, JsonRequestBehavior.AllowGet);
        }
        public ActionResult Register(FormCollection fc)
        {
            SynapseResponse response = new SynapseResponse();
            Dictionary<string, object> collection = new Dictionary<string, object>();

            response.errorCode = (int)ErrorCodes.IsAlreadyAuthenticated;
            response.errorMessage = @"Please go to http://tfc.tv to register.";
            return this.Json(response, JsonRequestBehavior.AllowGet);

            if (MyUtility.isUserLoggedIn()) //User is logged in.
            {
                response.errorCode = (int)ErrorCodes.IsAlreadyAuthenticated;
                response.errorMessage = "User is already authenticated.";
                return this.Json(response, JsonRequestBehavior.AllowGet);
            }

            if (String.IsNullOrEmpty(fc["Email"]))
            {
                response.errorCode = (int)ErrorCodes.IsEmailEmpty;
                response.errorMessage = MyUtility.getErrorMessage(ErrorCodes.IsEmailEmpty);
                return this.Json(response, JsonRequestBehavior.AllowGet);
            }
            if (String.Compare(fc["Password"], fc["ConfirmPassword"], false) != 0)
            {
                response.errorCode = (int)ErrorCodes.IsMismatchPassword;
                response.errorMessage = MyUtility.getErrorMessage(ErrorCodes.IsMismatchPassword);
                return this.Json(response, JsonRequestBehavior.AllowGet);
            }
            if (String.IsNullOrEmpty(fc["FirstName"]) || String.IsNullOrEmpty(fc["LastName"]) || String.IsNullOrEmpty(fc["CountryCode"]))
            {
                response.errorCode = (int)ErrorCodes.IsMissingRequiredFields;
                response.errorMessage = MyUtility.getErrorMessage(ErrorCodes.IsMissingRequiredFields);
                return this.Json(response, JsonRequestBehavior.AllowGet);
            }

            try
            {
                string FirstName = fc["FirstName"];
                string LastName = fc["LastName"];
                string CountryCode = fc["CountryCode"];
                string EMail = fc["Email"];
                string Password = fc["Password"];
                string City = fc["City"];
                string State = String.IsNullOrEmpty(fc["State"]) ? fc["StateDD"] : fc["State"];
                System.Guid userId = System.Guid.NewGuid();


                if (FirstName.Length > 32)
                {
                    response.errorCode = (int)ErrorCodes.LimitReached;
                    response.errorMessage = "First Name cannot exceed 32 characters.";
                    return this.Json(response, JsonRequestBehavior.AllowGet);
                }
                if (LastName.Length > 32)
                {
                    response.errorCode = (int)ErrorCodes.LimitReached;
                    response.errorMessage = "Last Name cannot exceed 32 characters.";
                    return this.Json(response, JsonRequestBehavior.AllowGet);
                }
                if (EMail.Length > 64)
                {
                    response.errorCode = (int)ErrorCodes.LimitReached;
                    response.errorMessage = "Email cannot exceed 64 characters.";
                    return this.Json(response, JsonRequestBehavior.AllowGet);
                }
                if (!String.IsNullOrEmpty(State))
                    if (State.Length > 30)
                    {
                        response.errorCode = (int)ErrorCodes.LimitReached;
                        response.errorMessage = "State cannot exceed 30 characters.";
                        return this.Json(response, JsonRequestBehavior.AllowGet);
                    }
                if (!String.IsNullOrEmpty(City))
                    if (City.Length > 50)
                    {
                        response.errorCode = (int)ErrorCodes.LimitReached;
                        response.errorMessage = "City cannot exceed 50 characters.";
                        return this.Json(response, JsonRequestBehavior.AllowGet);
                    }

                var context = new IPTV2Entities();
                User user = context.Users.FirstOrDefault(u => String.Compare(u.EMail, EMail, true) == 0);
                if (user != null)
                {
                    response.errorCode = (int)ErrorCodes.IsExistingEmail;
                    response.errorMessage = MyUtility.getErrorMessage(ErrorCodes.IsExistingEmail);
                    return this.Json(response, JsonRequestBehavior.AllowGet);
                }

                /***** CHECK FOR COUNTRY CODE ****/
                if (context.Countries.Count(c => String.Compare(c.Code, CountryCode, true) == 0) <= 0)
                {
                    response.errorCode = (int)ErrorCodes.IsMissingRequiredFields;
                    response.errorMessage = "Country Code is invalid.";
                    return this.Json(response, JsonRequestBehavior.AllowGet);
                }
                else if (GlobalConfig.ExcludedCountriesFromRegistrationDropDown.Split(',').Contains(CountryCode))
                {
                    response.errorCode = (int)ErrorCodes.IsMissingRequiredFields;
                    response.errorMessage = "Country Code is invalid.";
                    return this.Json(response, JsonRequestBehavior.AllowGet);
                }

                DateTime registDt = DateTime.Now;
                user = new User()
                {
                    UserId = userId,
                    FirstName = FirstName,
                    LastName = LastName,
                    City = City,
                    State = State,
                    CountryCode = CountryCode,
                    EMail = EMail,
                    Password = MyUtility.GetSHA1(Password),
                    GigyaUID = userId.ToString(),
                    RegistrationDate = registDt,
                    LastUpdated = registDt,
                    RegistrationIp = Request.GetUserHostAddressFromCloudflare(),
                    StatusId = 1,
                    ActivationKey = Guid.NewGuid(),
                    DateVerified = registDt
                };
                string CurrencyCode = GlobalConfig.DefaultCurrency;
                Country country = context.Countries.FirstOrDefault(c => String.Compare(c.Code, CountryCode, true) == 0);
                if (country != null)
                {
                    Currency currency = context.Currencies.FirstOrDefault(c => String.Compare(c.Code, country.CurrencyCode, true) == 0);
                    if (currency != null) CurrencyCode = currency.Code;
                }
                UserWallet wallet = user.UserWallets.FirstOrDefault(w => String.Compare(w.Currency, CurrencyCode, true) == 0);
                if (wallet == null) // Wallet does not exist. Create new wallet for User.
                {
                    wallet = ContextHelper.CreateWallet(0, CurrencyCode, registDt);
                    user.UserWallets.Add(wallet);
                }

                var transaction = new RegistrationTransaction()
                {
                    RegisteredState = user.State,
                    RegisteredCity = user.City,
                    RegisteredCountryCode = user.CountryCode,
                    Amount = 0,
                    Currency = CurrencyCode,
                    Reference = "New Registration (Mobile)",
                    Date = registDt,
                    OfferingId = GlobalConfig.offeringId,
                    UserId = user.UserId,
                    StatusId = GlobalConfig.Visible
                };

                user.Transactions.Add(transaction);

                context.Users.Add(user);
                if (context.SaveChanges() > 0)
                {
                    if (!String.IsNullOrEmpty(fc["UID"]))
                    {
                        Dictionary<string, object> GigyaCollection = new Dictionary<string, object>();
                        collection.Add("uid", fc["UID"]);
                        collection.Add("siteUID", userId);
                        collection.Add("cid", String.Format("{0} - New User", fc["provider"]));
                        GSResponse res = GigyaHelpers.createAndSendRequest("socialize.notifyRegistration", GigyaHelpers.buildParameter(collection));
                    }
                    else
                    {
                        Dictionary<string, object> userInfo = new Dictionary<string, object>();
                        userInfo.Add("firstName", user.FirstName);
                        userInfo.Add("lastName", user.LastName);
                        userInfo.Add("email", user.EMail);
                        Dictionary<string, object> gigyaCollection = new Dictionary<string, object>();
                        gigyaCollection.Add("siteUID", user.UserId);
                        gigyaCollection.Add("cid", "TFCTV - Registration");
                        gigyaCollection.Add("sessionExpiration", "0");
                        gigyaCollection.Add("newUser", true);
                        gigyaCollection.Add("userInfo", MyUtility.buildJson(userInfo));
                        GSResponse res = GigyaHelpers.createAndSendRequest("socialize.notifyLogin", GigyaHelpers.buildParameter(gigyaCollection));
                        GigyaHelpers.setCookie(res, this.ControllerContext);
                    }

                    //setUserData
                    User usr = context.Users.FirstOrDefault(u => String.Compare(u.EMail, EMail, true) == 0);
                    setUserData(usr.UserId.ToString(), usr);


                    if (usr.IsTVERegistrant == null || usr.IsTVERegistrant == false)
                    {
                        int freeTrialProductId = 0;
                        if (GlobalConfig.IsFreeTrialEnabled)
                        {
                            freeTrialProductId = MyUtility.GetCorrespondingFreeTrialProductId();
                            context = new IPTV2Entities();
                            if (GlobalConfig.TfcTvFree2StartDate < registDt && GlobalConfig.TfcTvFree2EndDate > registDt)
                            {
                                string UserCountryCode = user.CountryCode;
                                if (!GlobalConfig.isUAT)
                                    try { UserCountryCode = MyUtility.GetCountryCodeViaIpAddressWithoutProxy(); }
                                    catch (Exception) { }

                                var countryList = GlobalConfig.TfcTvFree2CountryWhiteList.Split(',');
                                if (countryList.Contains(UserCountryCode) && String.Compare(user.CountryCode, UserCountryCode, true) == 0)
                                    freeTrialProductId = GlobalConfig.TfcTvFree2ProductId;
                            }
                            //if (user.StatusId == GlobalConfig.Visible)
                            PaymentHelper.PayViaWallet(context, userId, freeTrialProductId, SubscriptionProductType.Package, userId, null);
                        }
                    }

                    //Publish to Activity Feed
                    List<ActionLink> actionlinks = new List<ActionLink>();
                    actionlinks.Add(new ActionLink() { text = SNSTemplates.register_actionlink_text, href = SNSTemplates.register_actionlink_href });
                    UserAction action = new UserAction()
                    {
                        actorUID = userId.ToString(),
                        userMessage = SNSTemplates.register_usermessage,
                        title = SNSTemplates.register_title,
                        subtitle = SNSTemplates.register_subtitle,
                        linkBack = SNSTemplates.register_linkback,
                        description = String.Format(SNSTemplates.register_description, FirstName),
                        actionLinks = actionlinks
                    };

                    GigyaMethods.PublishUserAction(action, userId, "external");
                    action.userMessage = String.Empty;
                    action.title = String.Empty;
                    GigyaMethods.PublishUserAction(action, userId, "internal");
                    //string verification_email = String.Format("{0}/User/Verify?email={1}&key={2}", GlobalConfig.baseUrl, EMail, user.ActivationKey.ToString());
                    //string emailBody = String.Format(GlobalConfig.EmailVerificationBodyTextOnly, FirstName, EMail, verification_email);

                    //if (!Request.IsLocal)
                    //    try { MyUtility.SendEmailViaSendGrid(EMail, GlobalConfig.NoReplyEmail, "Activate your TFC.tv account", emailBody, MailType.TextOnly, emailBody); }
                    //    catch (Exception e) { MyUtility.LogException(e, "Unable to send email via SendGrid"); }

                    response.errorCode = (int)ErrorCodes.Success;
                    response.errorMessage = "Registration successful.";

                    GSResponse gres = GetToken(user);
                    if (gres != null)
                    {
                        SynapseToken token = new SynapseToken()
                        {
                            uid = user.UserId.ToString(),
                            token = gres.GetString("access_token", String.Empty),
                            expire = gres.GetInt("expires_in", 0),
                        };

                        response.data = token;
                    }

                    HttpCookie authCookie = SetAutheticationCookie(user.UserId.ToString());
                    SynapseCookie cookie = new SynapseCookie()
                    {
                        cookieName = authCookie.Name,
                        cookieDomain = authCookie.Domain,
                        cookiePath = authCookie.Path,
                        cookieValue = authCookie.Value
                    };
                    response.info = cookie;
                }
                else
                {
                    response.errorCode = (int)ErrorCodes.EntityUpdateError;
                    response.errorMessage = "Unable to register user";
                }
            }
            catch (Exception e)
            {
                response.errorCode = (int)ErrorCodes.UnknownError;
                response.errorMessage = e.Message;
            }
            return this.Json(response, JsonRequestBehavior.AllowGet);
        }
        public JsonResult vLogin(string email, string pw)
        {
            SynapseResponse response = new SynapseResponse();
            response.callId = MyUtility.GetSHA1((String.Format("{0}{1}", Guid.NewGuid().ToString(), DateTime.Now.ToString()))).ToLower();
            try
            {
                string EmailAddress = email;
                string Password = pw;
                var context = new IPTV2Entities();

                if (String.IsNullOrEmpty(EmailAddress))
                {
                    response.errorCode = (int)ErrorCodes.IsMissingRequiredFields;
                    response.errorMessage = "Email address is required.";
                }

                if (String.IsNullOrEmpty(Password))
                {
                    response.errorCode = (int)ErrorCodes.IsMissingRequiredFields;
                    response.errorMessage = "Password is required.";
                }

                var user = context.Users.FirstOrDefault(u => String.Compare(u.EMail, EmailAddress, true) == 0);
                if (user == null)
                {
                    response.errorCode = (int)ErrorCodes.UserDoesNotExist;
                    response.errorMessage = "User does not exist";
                }
                else
                {
                    Password = MyUtility.GetSHA1(Password);
                    if (String.Compare(user.EMail, EmailAddress, true) == 0 && String.Compare(user.Password, Password, false) == 0)
                    {
                        SynapseUserInfo uInfo = new SynapseUserInfo() { firstName = user.FirstName, lastName = user.LastName, email = user.EMail };
                        Dictionary<string, object> collection = new Dictionary<string, object>();
                        collection.Add("client_id", GlobalConfig.GSapikey);
                        collection.Add("client_secret", GlobalConfig.GSsecretkey);
                        collection.Add("grant_type", "none");
                        collection.Add("x_siteUID", user.UserId);
                        collection.Add("x_sessionExpiration", 0);
                        collection.Add("x_userInfo", JsonConvert.SerializeObject(uInfo));
                        GSResponse res = GigyaHelpers.createAndSendRequest("socialize.getToken", GigyaHelpers.buildParameter(collection));
                        SynapseCookie cookie = new SynapseCookie()
                        {
                            cookieName = FormsAuthentication.FormsCookieName,
                            cookiePath = FormsAuthentication.FormsCookiePath,
                            cookieDomain = FormsAuthentication.CookieDomain
                        };
                        if (res.GetErrorCode() == 0)
                        { // Successful login to Gigya
                            HttpCookie authCookie = SetAutheticationCookie(user.UserId.ToString());
                            cookie.cookieValue = authCookie.Value;
                            ContextHelper.SaveSessionInDatabase(context, user, authCookie.Value);
                            SynapseToken token = new SynapseToken()
                            {
                                uid = user.UserId.ToString(),
                                token = res.GetString("access_token", String.Empty),
                                expire = res.GetInt("expires_in", 0),
                            };
                            response.data = token;
                            response.info = cookie;
                        }
                        else
                        {
                            response.errorCode = res.GetErrorCode();
                            response.errorMessage = "Gigya encountered an error logging you in, please try again";
                            response.errorDetails = res.GetErrorMessage();
                        }
                    }
                    else
                    {
                        response.errorCode = (int)ErrorCodes.IsWrongPassword;
                        response.errorMessage = MyUtility.getErrorMessage(ErrorCodes.IsWrongPassword);
                    }
                }
            }
            catch (Exception e) { response.errorCode = (int)ErrorCodes.UnknownError; response.errorMessage = "System encountered an unspecified error, please try again"; response.errorDetails = e.Message; }
            return this.Json(response, JsonRequestBehavior.AllowGet);
        }
        public ActionResult Social()
        {
            NameValueCollection qs = Request.Params;
            SynapseResponse response = new SynapseResponse();
            string gigyaUID = Uri.UnescapeDataString(qs["UID"]);
            bool isRequestValid = SigUtils.ValidateUserSignature(gigyaUID, Uri.UnescapeDataString(qs["timestamp"]), GlobalConfig.GSsecretkey, Uri.UnescapeDataString(qs["signature"]));
            if (isRequestValid)
            {
                var isNewUser = !Convert.ToBoolean(qs["isSiteUID"]); // If isSiteUID=='false' , this means the UID was generated by Gigya, hence the user is new. !(false) == true
                if (isNewUser)
                {
                    //TempData["qs"] = qs; //bring the parameters to the next view
                    //return RedirectToAction("Index");

                    response.errorCode = (int)ErrorCodes.IsNewSiteUser;
                    response.errorMessage = "Register the user";
                    response.data = qs;
                }
                else
                {
                    //FormsAuthentication.SetAuthCookie(gigyaUID, true); //Authenticate user to our site.
                    SetAutheticationCookie(gigyaUID);
                    var context = new IPTV2Entities();
                    User user = context.Users.FirstOrDefault(u => u.UserId == new System.Guid(gigyaUID));
                    if (user != null)
                    {
                        SynapseCookie cookie = new SynapseCookie()
                        {
                            cookieName = FormsAuthentication.FormsCookieName,
                            cookiePath = FormsAuthentication.FormsCookiePath,
                            cookieDomain = FormsAuthentication.CookieDomain
                        };
                        HttpCookie authCookie = SetAutheticationCookie(user.UserId.ToString());
                        cookie.cookieValue = authCookie.Value;
                        response.errorCode = (int)ErrorCodes.Success;
                        response.errorMessage = "Login success";
                        response.info = cookie;
                        GSResponse res = GetToken(user);
                        if (res != null)
                        {
                            SynapseToken token = new SynapseToken()
                            {
                                uid = user.UserId.ToString(),
                                token = res.GetString("access_token", String.Empty),
                                expire = res.GetInt("expires_in", 0),
                            };

                            response.data = token;
                        }
                    }
                    else
                    {
                        response.errorCode = (int)ErrorCodes.UserDoesNotExist;
                        response.errorMessage = "User does not exist";
                    }
                }
            }
            else
            {
                response.errorCode = (int)ErrorCodes.IsInvalidRequest;
                response.errorMessage = "User does not exist";
            }
            return this.Json(response, JsonRequestBehavior.AllowGet);
        }
        public JsonResult GSocialize()
        {
            var ReturnCode = new SocializeReturnCodeObj()
            {
                StatusCode = (int)ErrorCodes.UnknownError,
                StatusMessage = String.Empty
            };

            var registDt = DateTime.Now;
            var skipValidation = false;
            try
            {
                if (!String.IsNullOrEmpty(Request.QueryString["sv"]))
                {
                    var svTemp = Convert.ToInt32(Request.QueryString["sv"]);
                    if (svTemp == 1)
                        skipValidation = true;
                }
            }

            catch (Exception) { }
            try
            {
                NameValueCollection qs = Request.QueryString;
                string gigyaUID = Uri.UnescapeDataString(qs["UID"]);
                bool isRequestValid = SigUtils.ValidateUserSignature(gigyaUID, Uri.UnescapeDataString(qs["timestamp"]), GlobalConfig.GSsecretkey, Uri.UnescapeDataString(qs["signature"]));
                if (isRequestValid || skipValidation)
                {
                    using (var context = new IPTV2Entities())
                    {
                        User user = null;
                        bool isSiteUID = Convert.ToBoolean(qs["isSiteUID"]);
                        if (isSiteUID) //Old user. Signin to site
                        {
                            var UserId = new Guid(gigyaUID);
                            user = context.Users.FirstOrDefault(u => u.UserId == UserId);
                            if (user != null)
                            {
                                if (user.StatusId == GlobalConfig.Visible) //Successful Login
                                    ReturnCode.StatusCode = (int)ErrorCodes.Success;
                                else
                                    ReturnCode.StatusMessage = "Account is not verified in our system.";
                            }
                            else
                            {
                                //ReturnCode.StatusMessage = "Social networking account does not exist in our system.";
                                //Create user                                
                                string FirstName = qs["first_name"];
                                string LastName = qs["last_name"];
                                string EMail = qs["login_email"];
                                string uid = qs["uid"];
                                string provider = qs["provider"];
                                string Password = Membership.GeneratePassword(10, 2);
                                string City = String.Empty;
                                string State = String.Empty;
                                string CountryCode = GlobalConfig.DefaultCountry;
                                var id = UserId;
                                var ip = qs["ip"];

                                try
                                {
                                    var location = MyUtility.GetLocationBasedOnIpAddress(ip);
                                    City = location.city;
                                    CountryCode = location.countryCode;
                                    State = String.Compare(CountryCode, GlobalConfig.DefaultCountry, true) == 0 ? location.region : location.regionName;
                                }
                                catch (Exception) { }

                                user = new User()
                                {
                                    UserId = id,
                                    FirstName = FirstName,
                                    LastName = LastName,
                                    City = City,
                                    State = State,
                                    CountryCode = CountryCode,
                                    EMail = EMail,
                                    Password = MyUtility.GetSHA1(Password),
                                    GigyaUID = id.ToString(),
                                    RegistrationDate = registDt,
                                    LastUpdated = registDt,
                                    RegistrationIp = ip ?? MyUtility.GetClientIpAddress(),
                                    DateVerified = registDt,
                                    StatusId = GlobalConfig.Visible,
                                    ActivationKey = Guid.NewGuid()
                                };

                                var CurrencyCode = GlobalConfig.DefaultCurrency;
                                var country = context.Countries.FirstOrDefault(c => String.Compare(c.Code, CountryCode, true) == 0);
                                if (country != null)
                                    CurrencyCode = country.CurrencyCode;

                                var wallet = user.UserWallets.FirstOrDefault(w => String.Compare(w.Currency, CurrencyCode, true) == 0);
                                if (wallet == null)
                                {
                                    wallet = ContextHelper.CreateWallet(0, CurrencyCode, registDt);
                                    user.UserWallets.Add(wallet);
                                }

                                var transaction = new RegistrationTransaction()
                                {
                                    RegisteredState = user.State,
                                    RegisteredCity = user.City,
                                    RegisteredCountryCode = user.CountryCode,
                                    Amount = 0,
                                    Currency = CurrencyCode,
                                    Reference = "New Registration (AIR PLUS)",
                                    Date = registDt,
                                    OfferingId = GlobalConfig.offeringId,
                                    UserId = user.UserId,
                                    StatusId = GlobalConfig.Visible
                                };

                                user.Transactions.Add(transaction);
                                context.Users.Add(user);

                                if (context.SaveChanges() > 0)
                                {
                                    ReturnCode.StatusCode = (int)ErrorCodes.Success;
                                    GSResponse res = null;

                                    GigyaUserData2 userData = new GigyaUserData2()
                                    {
                                        city = user.City,
                                        country = user.CountryCode,
                                        email = user.EMail,
                                        firstName = user.FirstName,
                                        lastName = user.LastName,
                                        state = user.State
                                    };

                                    TFCTV.Helpers.UserData privacyData = new UserData() { IsExternalSharingEnabled = "true,false", IsInternalSharingEnabled = "true,false", IsProfilePrivate = "false" };
                                    GigyaUserDataInfo2 userDataInfo = new GigyaUserDataInfo2()
                                    {
                                        UID = user.UserId.ToString(),
                                        profile = Newtonsoft.Json.JsonConvert.SerializeObject(userData, Formatting.None),
                                        data = Newtonsoft.Json.JsonConvert.SerializeObject(privacyData, Formatting.None)
                                    };

                                    GSObject userDataInfoObj = new GSObject(Newtonsoft.Json.JsonConvert.SerializeObject(userDataInfo));                                    //res = GigyaHelpers.createAndSendRequest("gcs.setUserData", userDataInfoObj);
                                    res = GigyaHelpers.createAndSendRequest("ids.setAccountInfo", userDataInfoObj);

                                    //Publish to Activity Feed
                                    List<ActionLink> actionlinks = new List<ActionLink>();
                                    actionlinks.Add(new ActionLink() { text = SNSTemplates.register_actionlink_text, href = String.Format("{0}{1}", GlobalConfig.baseUrl, SNSTemplates.register_actionlink_href) });
                                    //mediaItem
                                    List<MediaItem> mediaItems = new List<MediaItem>();
                                    mediaItems.Add(new MediaItem() { type = SNSTemplates.register_mediaitem_type, src = String.Format("{0}{1}", GlobalConfig.AssetsBaseUrl, SNSTemplates.register_mediaitem_src), href = String.Format("{0}{1}", GlobalConfig.baseUrl, SNSTemplates.register_mediaitem_href) });
                                    UserAction action = new UserAction()
                                    {
                                        actorUID = user.UserId.ToString(),
                                        userMessage = SNSTemplates.register_usermessage,
                                        title = SNSTemplates.register_title,
                                        subtitle = String.Format("{0}{1}", GlobalConfig.baseUrl, SNSTemplates.register_subtitle),
                                        linkBack = String.Format("{0}{1}", GlobalConfig.baseUrl, SNSTemplates.register_linkback),
                                        description = String.Format(SNSTemplates.register_description, FirstName),
                                        actionLinks = actionlinks,
                                        mediaItems = mediaItems
                                    };

                                    GigyaMethods.PublishUserAction(action, user.UserId, "external");
                                    action.userMessage = String.Empty;
                                    action.title = String.Empty;
                                    action.mediaItems = null;
                                    GigyaMethods.PublishUserAction(action, user.UserId, "internal");
                                }
                            }
                        }
                        else //New user. allow user to register
                        {
                            bool createUser = true;
                            if (!String.IsNullOrEmpty(qs["email"]))
                            {
                                string email = qs["email"];
                                user = context.Users.FirstOrDefault(u => String.Compare(u.EMail, email, true) == 0);
                                if (user != null) // link account
                                {
                                    Dictionary<string, object> collection = new Dictionary<string, object>();
                                    collection.Add("siteUID", user.UserId);
                                    collection.Add("uid", Uri.UnescapeDataString(qs["UID"]));
                                    collection.Add("cid", String.Format("{0} - New User", qs["provider"]));

                                    GSObject obj = new GSObject(Newtonsoft.Json.JsonConvert.SerializeObject(collection));
                                    GSResponse res = GigyaHelpers.createAndSendRequest("socialize.notifyRegistration", obj);
                                    if (res.GetErrorCode() == 0) //Successful link
                                    {
                                        createUser = false;
                                        var UserId = user.UserId.ToString();
                                        user.StatusId = GlobalConfig.Visible; //activate account
                                        user.DateVerified = DateTime.Now;
                                        if (context.SaveChanges() > 0)
                                            ReturnCode.StatusCode = (int)ErrorCodes.Success;
                                        else
                                            ReturnCode.StatusMessage = "Create user failed";
                                    }
                                    else
                                        ReturnCode.StatusMessage = res.GetErrorMessage();
                                }
                            }

                            if (createUser)
                            {
                                string FirstName = qs["first_name"];
                                string LastName = qs["last_name"];
                                string EMail = qs["login_email"];
                                string uid = qs["uid"];
                                string provider = qs["provider"];
                                string Password = Membership.GeneratePassword(10, 2);
                                string City = String.Empty;
                                string State = String.Empty;
                                string CountryCode = GlobalConfig.DefaultCountry;
                                var id = Guid.NewGuid();
                                var ip = qs["ip"];

                                try
                                {
                                    var location = MyUtility.GetLocationBasedOnIpAddress(ip);
                                    City = location.city;
                                    CountryCode = location.countryCode;
                                    State = String.Compare(CountryCode, GlobalConfig.DefaultCountry, true) == 0 ? location.region : location.regionName;
                                }
                                catch (Exception) { }


                                user = new User()
                                {
                                    UserId = id,
                                    FirstName = FirstName,
                                    LastName = LastName,
                                    City = City,
                                    State = State,
                                    CountryCode = CountryCode,
                                    EMail = EMail,
                                    Password = MyUtility.GetSHA1(Password),
                                    GigyaUID = id.ToString(),
                                    RegistrationDate = registDt,
                                    LastUpdated = registDt,
                                    RegistrationIp = ip ?? MyUtility.GetClientIpAddress(),
                                    ActivationKey = Guid.NewGuid()
                                };

                                var CurrencyCode = GlobalConfig.DefaultCurrency;
                                var country = context.Countries.FirstOrDefault(c => String.Compare(c.Code, CountryCode, true) == 0);
                                if (country != null)
                                    CurrencyCode = country.CurrencyCode;

                                var wallet = user.UserWallets.FirstOrDefault(w => String.Compare(w.Currency, CurrencyCode, true) == 0);
                                if (wallet == null)
                                {
                                    wallet = ContextHelper.CreateWallet(0, CurrencyCode, registDt);
                                    user.UserWallets.Add(wallet);
                                }

                                var transaction = new RegistrationTransaction()
                                {
                                    RegisteredState = user.State,
                                    RegisteredCity = user.City,
                                    RegisteredCountryCode = user.CountryCode,
                                    Amount = 0,
                                    Currency = CurrencyCode,
                                    Reference = "New Registration (AIR PLUS)",
                                    Date = registDt,
                                    OfferingId = GlobalConfig.offeringId,
                                    UserId = user.UserId,
                                    StatusId = GlobalConfig.Visible
                                };

                                user.Transactions.Add(transaction);
                                context.Users.Add(user);

                                if (context.SaveChanges() > 0)
                                {
                                    GSResponse res = null;
                                    if (!String.IsNullOrEmpty(uid) && !String.IsNullOrEmpty(provider))
                                    {
                                        Dictionary<string, object> collection = new Dictionary<string, object>();
                                        collection.Add("siteUID", user.UserId);
                                        collection.Add("uid", Uri.UnescapeDataString(uid));
                                        collection.Add("cid", String.Format("{0} - New User", provider));
                                        res = GigyaHelpers.createAndSendRequest("socialize.notifyRegistration", GigyaHelpers.buildParameter(collection));
                                        if (res.GetErrorCode() == 0) //Successful link
                                        {
                                            if (user != null)
                                            {
                                                var UserId = user.UserId.ToString();
                                                user.StatusId = GlobalConfig.Visible; //activate account
                                                user.DateVerified = DateTime.Now;
                                                if (context.SaveChanges() > 0)
                                                    ReturnCode.StatusCode = (int)ErrorCodes.Success;
                                            }
                                        }
                                    }
                                    else
                                        ReturnCode.StatusMessage = "Missing parameters uid & provider";
                                    //else
                                    //{
                                    //    var info = new GigyaUserInfo()
                                    //    {
                                    //        firstName = FirstName,
                                    //        lastName = LastName,
                                    //        email = EMail
                                    //    };

                                    //    var registrationInfo = new GigyaNotifyLoginInfo()
                                    //    {
                                    //        siteUID = user.UserId.ToString(),
                                    //        cid = "TFCTV - Registration",
                                    //        sessionExpiration = 0,
                                    //        newUser = true,
                                    //        userInfo = Newtonsoft.Json.JsonConvert.SerializeObject(info)
                                    //    };
                                    //    GSObject obj = new GSObject(Newtonsoft.Json.JsonConvert.SerializeObject(registrationInfo));
                                    //    res = GigyaHelpers.createAndSendRequest("socialize.notifyLogin", obj);
                                    //    ReturnCode.StatusCode = (int)ErrorCodes.Success;
                                    //}

                                    if (ReturnCode.StatusCode == (int)ErrorCodes.Success)
                                    {
                                        GigyaUserData2 userData = new GigyaUserData2()
                                        {
                                            city = user.City,
                                            country = user.CountryCode,
                                            email = user.EMail,
                                            firstName = user.FirstName,
                                            lastName = user.LastName,
                                            state = user.State
                                        };

                                        TFCTV.Helpers.UserData privacyData = new UserData() { IsExternalSharingEnabled = "true,false", IsInternalSharingEnabled = "true,false", IsProfilePrivate = "false" };

                                        GigyaUserDataInfo2 userDataInfo = new GigyaUserDataInfo2()
                                        {
                                            UID = user.UserId.ToString(),
                                            profile = Newtonsoft.Json.JsonConvert.SerializeObject(userData, Formatting.None),
                                            data = Newtonsoft.Json.JsonConvert.SerializeObject(privacyData, Formatting.None)
                                        };

                                        GSObject userDataInfoObj = new GSObject(Newtonsoft.Json.JsonConvert.SerializeObject(userDataInfo));                                    //res = GigyaHelpers.createAndSendRequest("gcs.setUserData", userDataInfoObj);
                                        res = GigyaHelpers.createAndSendRequest("ids.setAccountInfo", userDataInfoObj);

                                        //Publish to Activity Feed
                                        List<ActionLink> actionlinks = new List<ActionLink>();
                                        actionlinks.Add(new ActionLink() { text = SNSTemplates.register_actionlink_text, href = String.Format("{0}{1}", GlobalConfig.baseUrl, SNSTemplates.register_actionlink_href) });
                                        //mediaItem
                                        List<MediaItem> mediaItems = new List<MediaItem>();
                                        mediaItems.Add(new MediaItem() { type = SNSTemplates.register_mediaitem_type, src = String.Format("{0}{1}", GlobalConfig.AssetsBaseUrl, SNSTemplates.register_mediaitem_src), href = String.Format("{0}{1}", GlobalConfig.baseUrl, SNSTemplates.register_mediaitem_href) });
                                        UserAction action = new UserAction()
                                        {
                                            actorUID = user.UserId.ToString(),
                                            userMessage = SNSTemplates.register_usermessage,
                                            title = SNSTemplates.register_title,
                                            subtitle = String.Format("{0}{1}", GlobalConfig.baseUrl, SNSTemplates.register_subtitle),
                                            linkBack = String.Format("{0}{1}", GlobalConfig.baseUrl, SNSTemplates.register_linkback),
                                            description = String.Format(SNSTemplates.register_description, FirstName),
                                            actionLinks = actionlinks,
                                            mediaItems = mediaItems
                                        };

                                        GigyaMethods.PublishUserAction(action, user.UserId, "external");
                                        action.userMessage = String.Empty;
                                        action.title = String.Empty;
                                        action.mediaItems = null;
                                        GigyaMethods.PublishUserAction(action, user.UserId, "internal");
                                    }
                                }
                            }
                        }

                        if (ReturnCode.StatusCode == (int)ErrorCodes.Success)
                        {
                            ReturnCode.StatusMessage = "Success!";

                            //GenerateToken
                            SynapseUserInfo uInfo = new SynapseUserInfo() { firstName = user.FirstName, lastName = user.LastName, email = user.EMail };
                            Dictionary<string, object> collection = new Dictionary<string, object>();
                            collection.Add("client_id", GlobalConfig.GSapikey);
                            collection.Add("client_secret", GlobalConfig.GSsecretkey);
                            collection.Add("grant_type", "none");
                            collection.Add("x_siteUID", user.UserId);
                            collection.Add("x_sessionExpiration", 0);
                            collection.Add("x_userInfo", JsonConvert.SerializeObject(uInfo));
                            GSResponse res = GigyaHelpers.createAndSendRequest("socialize.getToken", GigyaHelpers.buildParameter(collection));
                            SynapseCookie cookie = new SynapseCookie()
                            {
                                cookieName = FormsAuthentication.FormsCookieName,
                                cookiePath = FormsAuthentication.FormsCookiePath,
                                cookieDomain = FormsAuthentication.CookieDomain
                            };

                            if (res.GetErrorCode() == 0)
                            {
                                HttpCookie authCookie = SetCookie(user.UserId.ToString());
                                cookie.cookieValue = authCookie.Value;
                                ContextHelper.SaveSessionInDatabase(context, user, authCookie.Value);
                                SynapseToken token = new SynapseToken()
                                {
                                    uid = user.UserId.ToString(),
                                    token = res.GetString("access_token", String.Empty),
                                    expire = res.GetInt("expires_in", 0),
                                };

                                ReturnCode.tk = token;
                                ReturnCode.gs = cookie;
                            }
                            else
                            {
                                ReturnCode.StatusCode = res.GetErrorCode();
                                ReturnCode.StatusMessage = res.GetErrorMessage();
                            }
                        }
                    }
                }
                else
                    ReturnCode.StatusMessage = "Request is not valid";
            }
            catch (Exception e) { MyUtility.LogException(e); ReturnCode.StatusMessage = String.Format("Exception: {0} | Inner Exception: {1}", e.Message, e.InnerException.Message); }
            return this.Json(ReturnCode, JsonRequestBehavior.AllowGet);
        }