/* Minification failed. Returning unminified contents.
(279,62-63): run-time error JS1100: Expected ',': =
(279,68-69): run-time error JS1002: Syntax error: ,
(279,77-78): run-time error JS1100: Expected ',': =
(279,83-84): run-time error JS1002: Syntax error: ,
(279,92-93): run-time error JS1100: Expected ',': =
(303,74-75): run-time error JS1195: Expected expression: >
(303,108-109): run-time error JS1004: Expected ';': )
(309,17-18): run-time error JS1002: Syntax error: }
(311,109-110): run-time error JS1002: Syntax error: }
(320,13-14): run-time error JS1002: Syntax error: }
(323,44-45): run-time error JS1004: Expected ';': {
(405,81-82): run-time error JS1195: Expected expression: >
(411,18-19): run-time error JS1195: Expected expression: )
(416,130-131): run-time error JS1195: Expected expression: >
(422,18-19): run-time error JS1195: Expected expression: )
(428,10-11): run-time error JS1195: Expected expression: ,
(429,9-25): run-time error JS1197: Too many errors. The file might not be a JavaScript file: validateCardInfo
(427,13-36): run-time error JS1018: 'return' statement outside of function: return deffered.promise
(392,17-40): run-time error JS1018: 'return' statement outside of function: return deffered.promise
(372,21-44): run-time error JS1018: 'return' statement outside of function: return deffered.promise
(375,21-44): run-time error JS1018: 'return' statement outside of function: return deffered.promise
(360,17-40): run-time error JS1018: 'return' statement outside of function: return deffered.promise
(353,17-40): run-time error JS1018: 'return' statement outside of function: return deffered.promise
 */
var app = angular.module('app');

app.factory('PagesLookupSvc', ['common', function (common) {

    var urlCore = serviceBase + '/api/Lookup';
    return {
        getLookup: function (type) {
            var promise = common.$http.get(urlCore + "/GetLookup", {
                params: { type: type }
            });
            return promise;
        },
        getLookupArray: function (type) {
            var promise = common.$http.get(urlCore + "/GetlookupArray", {
                params: { type: type }
            });
            return promise;
        },
        getLookupParentChild: function (type, displayProgram, displaySubProgram, displayOnPublic) {    //Fundraising Page Get Lookup - Added By VP
            var promise = common.$http.get(urlCore + "/GetLookupParentChild", {
                params: { type: type, parameter: { 'DisplayProgram': displayProgram, 'DisplaySubProgram': displaySubProgram, 'DisplayOnPublic': displayOnPublic } }
            });
            return promise;
        },
        getParentProgramOnly: function () {
            var promise = common.$http.get(urlCore + "/GetlookupArray", {
                params: { type: 'Program', parameter: { 'ParentOnly': 'ParentOnly' } }
            });
            return promise;
        },
        CheckEmailExists: function (email, contactId) {
            var promise = common.$http.get(urlCore + "/CheckEmailExists", {
                params: {
                    email: email,
                    contactId: contactId
                }
            });
            return promise;
        },
        getContactMergeSetting: function () {
            var promise = common.$http.get(urlCore + "/GetContactMergeSetting");
            return promise;
        },
        //getSubPrograms: function (clientId, programId) {
        //    var promise = common.$http.get(urlCore + "/GetSubPrograms", {
        //        params: { clientId: clientId, programId: programId }
        //    })
        //    return promise;
        //},
    }
}]);

;
var app = angular.module('app');
app.factory('PagesContactAddressSvc', ['common', function (common) {
    $resource = common.$resource;
    var urlCore = '/api/PublicPageAddress';
    return {
        GetAddressFromZipCode: function (client,val) {
            var promise = common.$http.get(urlCore + "/GetAddressFromZipCode", {
                params: {
                    clientId:client,
                    zipCode: val
                }
            });
            return promise;
        },
        VerifyAddress: function (client,val) {
            var promise = common.$http.get(urlCore + "/VerifyAddress", {
                params: {
                    clientId: client,
                    AddressLine1: val.AddressLine1,
                    AddressLine2: val.AddressLine2,
                    AddressLine3: val.AddressLine3,
                    AddressLine4: val.AddressLine4,
                    City: val.City,
                    StateRegionProvince: val.StateRegionProvince,
                    County: val.County,
                    Country: val.Country,
                    PostalCode: val.PostalCode
                }
            });
            return promise;
        }
    }
}]);

;
var app = angular.module('app');

app.factory('ContactProfileSvc', ['common', function (common) {
    var urlCore = serviceBase + 'api/Profile';
    return {
        getContactDetail: function () {
            var promise = common.$http.get(urlCore + "/GetContactDetail",
                {
                    params: {}
                });
            return promise;
        },
        getBasicContactDetails: function () {
            var promise = common.$http.get(urlCore + "/GetBasicContactDetails",
                {
                    params: {}
                });
            return promise;
        },
        saveContactDetail: function (contact) {
            var promise = common.$http({
                url: urlCore + "/SaveContactDetail",
                method: "POST",
                data: contact
            });
            return promise;
        },
        saveProfileImage: function (imageurl, contactId) {
            var promise = common.$http({
                url: urlCore + "/SaveProfileImage",
                method: "POST",
                params: { imageurl: imageurl, contactId: contactId }
            });
            return promise;
        },
        //For My payment section
        getPaymentHistory: function () {
            var promise = common.$http.get(urlCore + "/GetInvoiceList",
                {
                    params: {}
                });
            return promise;
        },


        GetCardsOnFile: function () {
            return common.$http({
                url: urlCore + '/GetCardsOnFile',
                method: "Get",
                params: {},
            });
        },

        GetDefaultCardOnFile: function () {
            return common.$http({
                url: urlCore + '/GetDefaultCardOnFile',
                method: "Get"
            });
        },

        GetContactCardsById: function (contactId) {
            return common.$http({
                url: urlCore + '/GetContactCardsById',
                method: "Get",
                params: { contactId: contactId },
            });
        },

        SaveCardsOnFile: function (Card) {
            var promise = common.$http({
                url: urlCore + "/SaveCardsOnFile",
                method: "POST",
                data: { Card: Card },
            });
            return promise;
        },
        SetDefaultCardsOnFile: function (CardOnFileId) {
            var promise = common.$http({
                url: urlCore + "/SetDefaultCardsOnFile",
                method: "POST",
                params: { CardOnFileId: CardOnFileId },
            });
            return promise;
        },
        DeleteCardsOnFile: function (CardOnFileId) {
            var promise = common.$http({
                url: urlCore + "/DeleteCardsOnFile",
                method: "Get",
                params: { CardOnFileId: CardOnFileId },
            });
            return promise;
        },

        getIndividualContactDetail: function (contactId) {
            var promise = common.$http.get(urlCore + "/GetIndividualContact",
                {
                    params: { contactId: contactId }
                });
            return promise;
        },
        getOrganizationContactDetail: function (contactId) {
            var promise = common.$http.get(urlCore + "/GetOrganizationContact",
                {
                    params: { contactId: contactId }
                });
            return promise;
        },
        getMatchingOrganizations: function () {
            var promise = common.$http({
                url: urlCore + "/GetMatchingOrganizations",
                method: "GET",
            });
            return promise;
        },
        GetHouseholdRelations: function (contactId) {
            var promise = common.$http.get(urlCore + "/GetHouseholdRelations", {
                params: { contactId: contactId }
            });
            return promise;
        },
        getContactAddresses: function () {
            var promise = common.$http({
                url: urlCore + "/GetContactAddresses",
                method: "GET"
            });
            return promise;
        }
    }
}]);

;
var app = angular.module('app');

app.factory('IndividualSvc', ['common', function (common) {

    var urlCore = serviceBase + 'api/Individual';

    return {
        GetContact: function (contactId) {
            var promise = common.$http.get(urlCore + "/GetContact", {
                params: { contactId: contactId }
            });
            return promise;
        },
        GetRelations: function () {
            var promise = common.$http.get(urlCore + "/GetRelations", {
                params: {}
            });
            return promise;
        }
    }

}]);;
var app = angular.module('app');
app.factory('PublicFileUploaderSvc', ['$http','$resource', function ($http, $resource) {
    var urlCore = '/api/PublicFileUpload/';
    var url = $resource(urlCore,
            {
                'save': {
                    method: 'Post',
                    url: urlCore + '/Post'
                },
                'delete': { method: 'Delete', url: urlCore + 'Delete/:source' }
            });
    return {
        Deletedocument: function (source) {
            return url.delete({ source: source }).$promise;
        },
        uploadEditedFile: function (filePath) {
            return $http({
                url: urlCore + '/UploadEditedFile',
                method: "POST",
                params: { filePath: filePath },
            });
        },
    }
}]);

;
window.onload = function () {
    window.crm.constants.cardAuthenticationProps = {
        handle: "Handle",
        setup: "Setup",
        cardApproved: "Approved",
        cardRejected: "Rejected",
        noCardAuthRequired: "NoCardAuthRequired"
    }
}
app.factory('cardService', ['$q', '$window', '$timeout', function ($q, $window, $timeout) {
    return {
        getToken: function (stripeObj, billingAddress, _name = null, _email = null, _phone = null) {
            var deffered = $q.defer();

            //to handle stripe payment button
            if (IsNotNullorEmpty(stripeObj.StripePaymentMethodID)) {
                deffered.resolve(stripeObj.StripePaymentMethodID)
                return deffered.promise;
            }

            var billing_details = {
                name: IsNullorEmpty(_name) ? null : _name,
                email: _email,
                phone: _phone,
                address: {}
            };

            //pass extra param as billing address if exist.
            if (IsNotNullorEmpty(billingAddress)) {
                billing_details.address.line1 = IsNotNullorEmpty(billingAddress.AddressLine1) ? billingAddress.AddressLine1 : '';
                billing_details.address.line2 = IsNotNullorEmpty(billingAddress.AddressLine2) ? billingAddress.AddressLine2 : '';
                billing_details.address.city = IsNotNullorEmpty(billingAddress.City) ? billingAddress.City : '';
                billing_details.address.state = IsNotNullorEmpty(billingAddress.StateRegionProvince) ? billingAddress.StateRegionProvince : '';
                billing_details.address.postal_code = IsNotNullorEmpty(billingAddress.PostalCode) ? billingAddress.PostalCode : '';
                if (IsNotNullorEmpty(billingAddress.Country)) {
                    var countryObj = window.crm.list.countries.find((a) => a.Name == billingAddress.Country)
                    if (typeof (countryObj) != 'undefined') {
                        billing_details.address.country = countryObj.Id;
                    } else {
                        billing_details.address.country = billingAddress.Country;
                    }
                }
            }
            stripeObj.stripe.createPaymentMethod('card', stripeObj.card, { billing_details: billing_details }).then((result) => {
                if (result.error) {
                    // Inform the user if there was an error
                    //var errorElement = document.getElementById('card-errors');
                    deffered.reject(result.error.message);
                } else {
                    // Send the token to your server
                    deffered.resolve(result.paymentMethod.id);
                }
            });
            return deffered.promise;
        },
        authenticateCard: function (props) {
            //create as promise 
            var deffered = $q.defer();

            //get the default params
            var _config = {
                serverResponse: null,
                action: "Handle",
                nameOnCard: null,
                secretkey: null,
                paymentMethodData: {
                    payment_method_data: {
                        billing_details: {
                            name: null
                        }
                    }
                }
            }

            //configure parameters from props 
            angular.extend(_config, props);

            // Consider standard server resopose as per below and called CASE #1
            // For Type: serverResponse.Type
            // For Stripe "Required Action": serverResponse.Key
            // For Stripe secret key: serverResponse.Description

            // check if server response exist or not 
            if (IsNullorEmpty(_config.serverResponse)) {
                deffered.reject({ type: "Error", description: "No server response found" });
                return deffered.promise;
            }

            // Handle different serverside errors and retrun as error
            var _errorsKey = ["Failed", "CardNumberIsIncorrect", "CCPaymentFailure", "CCTokenizationFailed", "RecurringDonationFail"];
            if (_errorsKey.indexOf(_config.serverResponse.Key) != -1) {
                deffered.reject({ type: "Error", description: _config.serverResponse.Description });
                return deffered.promise;
            }

            //we have two style of error handling object
            //so we are handling here to make it standardize by overriding _config as based on the error handle object

            //check weather authenticate action require or not
            //Handle CASE #1 for success message
            if ((_config.serverResponse.Type !== "Error" && _config.serverResponse.Key !== "RequiresAction")) {
                //Handle CASE #2 for success message
                if (_config.serverResponse.StatusCode === 200 || _config.serverResponse.Type === "Success") {
                    deffered.resolve({ type: "Success", data: null, description: "No Authentication Required" });
                    return deffered.promise;
                } else if (_config.serverResponse.StatusCode !== 999) {
                    deffered.reject({ type: "Error", description: _config.serverResponse.ErrorText });
                    return deffered.promise;
                }
            }

            //Handle CASE #2 and Match with CASE #1
            //in this case, require action have status code 999 and ErrorText have stripe token. 
            //Modify the configure object as per standard error handling object like CASE #1
            //check if status code is 999 so that standardize the config
            if (_config.serverResponse.StatusCode === 999 && IsNotNullorEmpty(_config.serverResponse.ErrorText)) {
                _config.serverResponse.Type = "Error";
                _config.serverResponse.Key = "RequiresAction";
                _config.serverResponse.Description = _config.serverResponse.ErrorText;
            }

            //Validate stripe secret key
            if (IsNullorEmpty(_config.serverResponse.Description)) {
                deffered.reject({ type: "Error", description: "Server secret key not found from server." });
                return deffered.promise;
            }

            //assign serverkey to stripe secret key
            _config.secretkey = _config.serverResponse.Description;

            //check if stripe object already exist globally or not.
            //if not exit, create it globlally
            if (!$window.stripeObject)
                $window.stripeObject = $window.Stripe($window.crm.constants.publishableKey);

            //Proceed stripe action based on the action required
            if (_config.action === "Handle") {
                stripeObject.handleCardAction(_config.secretkey).then((result) => {
                    if (result.error) {
                        deffered.reject({ type: "Error", description: result.error.message });
                    } else {
                        deffered.resolve({ type: "Success", data: result, description: "Stripe authentication verified." });
                    }
                });
            }
            else if (_config.action === 'Setup') {
                //set name on card if exit
                _config.paymentMethodData.payment_method_data.name = _config.nameOnCard;
                stripeObject.handleCardSetup(_config.secretkey, _config.stripeElement, _config.paymentMethodData).then((result) => {
                    if (result.error) {
                        deffered.reject({ type: "Error", description: result.error.message });
                    } else {
                        deffered.resolve({ type: "Success", data: result, description: "Stripe authentication verified." });
                    }
                });
            }
            else {
                deffered.reject({ type: "Error", description: "No stripe element found" });
            }
            return deffered.promise;
        },
        validateCardInfo(res) {
            var deffered = $q.defer();
            //server response object
            var response = {
                serverResponse: res
            }

            if (res.action !== undefined && res.action !== null && res.action !== "")
                response.action = res.action;

            //check server response valid or not 
            if (typeof (res.data.Message) !== 'undefined') {
                if (res.data.Message.Type == "Success") {
                    deffered.resolve({ status: "NoCardAuthRequired", description: res.data.Message.Description });
                    return deffered.promise;
                } else {
                    if (typeof (res.data.Message.Key) !== 'undefined' && res.data.Message.Key == 'RequiresAction') {

                        response.serverResponse = res.data.Message;
                    } else {
                        deffered.resolve({ status: "Rejected", description: res.data.Message.Description });
                        return deffered.promise;
                    }
                }
            } else {
                response.serverResponse = res.data;
            }
            this.authenticateCard(response).then((stripeResponse) => {
                if (stripeResponse.data) {
                    //proccess in process to save after payment intent
                    switch (res.action) {
                        case "Setup":
                            deffered.resolve({ status: "Approved", paymentIntent: stripeResponse.data.setupIntent });
                            break;
                        case "Handle":
                            deffered.resolve({ status: "Approved", paymentIntent: stripeResponse.data.paymentIntent });
                            break;
                        default:
                            deffered.resolve({ status: "Approved", paymentIntent: stripeResponse.data.paymentIntent });
                            break;
                    }
                } else {
                    //not required authentication process
                    deffered.resolve({ status: "NoCardAuthRequired", description: "No authentication required" });
                }
            }, (err) => {
                //error while processing stripe card 
                deffered.resolve({ status: "Rejected", description: err.description });
            });
            return deffered.promise;
        }
    }
}]);

app.factory('publiccardService', ['$q', '$window', '$timeout', function ($q, $window, $timeout) {
    return {
        getToken: function (stripeObj, billingAddress, _name = null, _email = null, _phone = null) {
            var deffered = $q.defer();

            //to handle stripe payment button
            if (IsNotNullorEmpty(stripeObj.StripePaymentMethodID)) {
                deffered.resolve(stripeObj.StripePaymentMethodID)
                return deffered.promise;
            }

            var billing_details = {
                name: IsNullorEmpty(_name) ? null : _name,
                email: _email,
                phone: _phone,
                address: {}
            };

            if (IsNotNullorEmpty(billingAddress)) {
                billing_details.address.line1 = IsNotNullorEmpty(billingAddress.AddressLine1) ? billingAddress.AddressLine1 : '';
                billing_details.address.line2 = IsNotNullorEmpty(billingAddress.AddressLine2) ? billingAddress.AddressLine2 : '';
                billing_details.address.city = IsNotNullorEmpty(billingAddress.City) ? billingAddress.City : '';
                billing_details.address.state = IsNotNullorEmpty(billingAddress.StateRegionProvince) ? billingAddress.StateRegionProvince : '';
                billing_details.address.postal_code = IsNotNullorEmpty(billingAddress.PostalCode) ? billingAddress.PostalCode : '';
                if (IsNotNullorEmpty(billingAddress.Country)) {
                    var countryObj = window.crm.list.countries.find((a) => a.Name == billingAddress.Country)
                    if (typeof (countryObj) != 'undefined') {
                        billing_details.address.country = countryObj.Id;
                    } else {
                        billing_details.address.country = billingAddress.Country;
                    }
                }
            }
            stripeObj.stripe.createPaymentMethod('card', stripeObj.cardNumber, { billing_details: billing_details }).then((result) => {
                if (result.error) {
                    // Inform the user if there was an error
                    //var errorElement = document.getElementById('card-errors');
                    deffered.reject(result.error.message);
                } else {
                    // Send the token to your server
                    deffered.resolve(result.paymentMethod.id);
                }
            });
            return deffered.promise;
        },
        authenticateCard: function (props) {
            //create as promise 
            var deffered = $q.defer();

            //get the default params
            var _config = {
                serverResponse: null,
                action: "Handle",
                nameOnCard: null,
                secretkey: null,
                paymentMethodData: {
                    payment_method_data: {
                        billing_details: {
                            name: null
                        }
                    }
                }
            }

            //configure parameters from props 
            angular.extend(_config, props);

            // Consider standard server resopose as per below and called CASE #1
            // For Type: serverResponse.Type
            // For Stripe "Required Action": serverResponse.Key
            // For Stripe secret key: serverResponse.Description

            // check if server response exist or not 
            if (IsNullorEmpty(_config.serverResponse)) {
                deffered.reject({ type: "Error", description: "No server response found" });
                return deffered.promise;
            }

            // Handle different serverside errors and retrun as error
            var _errorsKey = ["Failed", "CardNumberIsIncorrect", "CCPaymentFailure", "CCTokenizationFailed", "RecurringDonationFail"];
            if (_errorsKey.indexOf(_config.serverResponse.Key) != -1) {
                deffered.reject({ type: "Error", description: _config.serverResponse.Description });
                return deffered.promise;
            }

            //we have two style of error handling object
            //so we are handling here to make it standardize by overriding _config as based on the error handle object

            //check weather authenticate action require or not
            //Handle CASE #1 for success message
            if ((_config.serverResponse.Type !== "Error" && _config.serverResponse.Key !== "RequiresAction")) {
                //Handle CASE #2 for success message
                if (_config.serverResponse.StatusCode === 200 || _config.serverResponse.Type === "Success") {
                    deffered.resolve({ type: "Success", data: null, description: "No Authentication Required" });
                    return deffered.promise;
                } else if (_config.serverResponse.StatusCode !== 999) {
                    deffered.reject({ type: "Error", description: _config.serverResponse.ErrorText });
                    return deffered.promise;
                }
            }

            //Handle CASE #2 and Match with CASE #1
            //in this case, require action have status code 999 and ErrorText have stripe token. 
            //Modify the configure object as per standard error handling object like CASE #1
            //check if status code is 999 so that standardize the config
            if (_config.serverResponse.StatusCode === 999 && IsNotNullorEmpty(_config.serverResponse.ErrorText)) {
                _config.serverResponse.Type = "Error";
                _config.serverResponse.Key = "RequiresAction";
                _config.serverResponse.Description = _config.serverResponse.ErrorText;
            }

            //Validate stripe secret key
            if (IsNullorEmpty(_config.serverResponse.Description)) {
                deffered.reject({ type: "Error", description: "Server secret key not found from server." });
                return deffered.promise;
            }

            //assign serverkey to stripe secret key
            _config.secretkey = _config.serverResponse.Description;

            //check if stripe object already exist globally or not.
            //if not exit, create it globlally
            if (!$window.stripeObject)
                $window.stripeObject = $window.Stripe($window.crm.constants.publishableKey);

            //Proceed stripe action based on the action required
            if (_config.action === "Handle") {
                stripeObject.handleCardAction(_config.secretkey).then((result) => {
                    if (result.error) {
                        deffered.reject({ type: "Error", description: result.error.message });
                    } else {
                        deffered.resolve({ type: "Success", data: result, description: "Stripe authentication verified." });
                    }
                });
            }
            else if (_config.action === 'Setup') {
                //set name on card if exit
                _config.paymentMethodData.payment_method_data.name = _config.nameOnCard;
                stripeObject.handleCardSetup(_config.secretkey, _config.stripeElement, _config.paymentMethodData).then((result) => {
                    if (result.error) {
                        deffered.reject({ type: "Error", description: result.error.message });
                    } else {
                        deffered.resolve({ type: "Success", data: result, description: "Stripe authentication verified." });
                    }
                });
            }
            else {
                deffered.reject({ type: "Error", description: "No stripe element found" });
            }
            return deffered.promise;
        },
        validateCardInfo(res) {
            var deffered = $q.defer();
            //server response object
            var response = {
                serverResponse: res
            }

            if (res.action !== undefined && res.action !== null && res.action !== "")
                response.action = res.action;

            //check server response valid or not 
            if (typeof (res.data.Message) !== 'undefined') {
                if (res.data.Message.Type == "Success") {
                    deffered.resolve({ status: "NoCardAuthRequired", description: res.data.Message.Description });
                    return deffered.promise;
                } else {
                    if (typeof (res.data.Message.Key) !== 'undefined' && res.data.Message.Key == 'RequiresAction') {

                        response.serverResponse = res.data.Message;
                    } else {
                        deffered.resolve({ status: "Rejected", description: res.data.Message.Description });
                        return deffered.promise;
                    }
                }
            } else {
                response.serverResponse = res.data;
            }
            this.authenticateCard(response).then((stripeResponse) => {
                if (stripeResponse.data) {
                    //proccess in process to save after payment intent
                    switch (res.action) {
                        case "Setup":
                            deffered.resolve({ status: "Approved", paymentIntent: stripeResponse.data.setupIntent });
                            break;
                        case "Handle":
                            deffered.resolve({ status: "Approved", paymentIntent: stripeResponse.data.paymentIntent });
                            break;
                        default:
                            deffered.resolve({ status: "Approved", paymentIntent: stripeResponse.data.paymentIntent });
                            break;
                    }
                } else {
                    //not required authentication process
                    deffered.resolve({ status: "NoCardAuthRequired", description: "No authentication required" });
                }
            }, (err) => {
                //error while processing stripe card 
                deffered.resolve({ status: "Rejected", description: err.description });
            });
            return deffered.promise;
        }
    }
}]);;
var app = angular.module('app');

app.factory('WorkInformationsSvc', ['common', function (common) {

    var urlCore = serviceBase + 'api/WorkInformation';

    return {
        GetOrganizationbyName: function (name) {
            var promise = common.$http.get(urlCore + "/GetOrganizationbyName", {
                params: {
                    name: name
                }
            });
            return promise;
        },
        GetOrganizationEmployees: function (organizationContactId) {
            var promise = common.$http.get(urlCore + "/GetOrganizationEmployees", {
                params: {
                    organizationContactId: organizationContactId
                }
            });
            return promise;
        },
        GetFirstWorkInformation: function (contactId, organizationId) {
            var promise = common.$http.get(urlCore + "/GetFirstWorkInformation", {
                params: {
                    contactId: contactId,
                    organizationId: organizationId
                }
            });
            return promise;
        },
        GetOrganizationAddresses: function (contactId, organizationId) {
            var promise = common.$http.get(urlCore + "/GetOrganizationAddresses", {
                params: {
                    contactId: contactId,
                    organizationId: organizationId
                }
            });
            return promise;
        },
        WorkInformationList: function () {
            var promise = common.$http.get(urlCore + "/WorkInformationList", {
                params: {
                }
            });
            return promise;
        }
    }
}]);;
var app = angular.module('app');

app.factory('eStorePageSvc', ['common', function (common) {
    var urlCore = serviceBase + 'api/eStore';

    return {
        GetCategories: function (searchCriteria) {
            return common.$http({
                url: urlCore + '/GetCategories',
                method: "POST",
                data: searchCriteria,
            });
        },
        GetProductList: function (searchCriteria) {
            return common.$http({
                url: urlCore + '/GetProductList',
                method: "POST",
                data: searchCriteria,
            });
        },
        GetProductDetail: function (productId) {
            return common.$http({
                url: urlCore + '/GetProductDetail',
                method: "GET",
                params: { productId: productId },
            });
        },
        GetContactOrders: function (searchCriteria) {
            return common.$http({
                url: urlCore + '/GetContactOrders',
                method: "POST",
                data: searchCriteria
            });
        },
        RequestForCancellation: function (orderFullfilment) {
            return common.$http({
                url: urlCore + '/RequestForCancellation',
                method: "POST",
                data: orderFullfilment
            });
        },
        calculateSalesTax: function (batchOrder) {
            return common.$http({
                url: urlCore + '/CalculateSalesTax',
                method: "POST",
                data: batchOrder
            });
        },
        calculateSalesTaxOnCart: function (guestCart) {
            return common.$http({
                url: urlCore + '/CalculateSalesTaxOnCart',
                method: "POST",
                data: guestCart
            });
        },
    }
}]);;
var app = angular.module('app');

app.run(["$rootScope", "gettextCatalog", "LocaleService",
    function ($rootScope, gettextCatalog, LocaleService) {
        gettextCatalog.currentLanguage = window.crm.constants.culture;
        LocaleService.useLocale(window.crm.constants.culture, 'Pages/PublicPages');
    }]);

var serviceBase = window.crm.constants.APIBasePath;//'http://localhost/NPE.API/';
app.constant('ngAuthSettings', {
    apiServiceBaseUri: serviceBase,
    clientId: 'npePagesAPP'
});

app.config(["$httpProvider",
    function ($httpProvider) {
        $httpProvider.interceptors.push('authInterceptorService');
    }]);

app.run(["$rootScope", "authService",
    function ($rootScope, authService) {
        authService.fillAuthData();
        $rootScope.authentication = authService.authentication;
    }]);


;
'use strict';
app.factory('authInterceptorService', ['$q', '$injector', 'localStorageService', function ($q, $injector, localStorageService) {

    var authInterceptorServiceFactory = {};

    var _request = function (config) {
        config.headers = config.headers || {};
        
        var authData = localStorageService.get('authorizationData');
        if (authData) {
            config.headers.Authorization = 'Bearer ' + authData.token;
        }

        if (window.crm.constants.APIKey) {
            if (config.headers['Content-Type'] == 'application/x-www-form-urlencoded') {
                config.data = config.data + '&APIKey=' + window.crm.constants.APIKey;
            }
            else {
                config.headers.APIKey = window.crm.constants.APIKey;
            }
        }

        return config;
    }

    var _responseError = function (rejection) {
        if (rejection.status === 401) {
            var authService = $injector.get('authService');
            var authData = localStorageService.get('authorizationData');

            if (authData) {
                if (authData.useRefreshTokens) {
                    //$location.path('/refresh');
                    return $q.reject(rejection);
                }
            }
            authService.logOut();
            //$location.path('/login');
            window.location.href = window.crm.constants.baseurl + '/Account#/login';
        }
        return $q.reject(rejection);
    }

    authInterceptorServiceFactory.request = _request;
    authInterceptorServiceFactory.responseError = _responseError;

    return authInterceptorServiceFactory;
}]);;
'use strict';
app.factory('authService', ['$http', '$q', 'localStorageService', 'ngAuthSettings', 'common', 'CheckoutSvc', 'PageCartSvc', 'GuestCartSvc',
    function ($http, $q, localStorageService, ngAuthSettings, common, CheckoutSvc, PageCartSvc, GuestCartSvc) {
        var serviceBase = ngAuthSettings.apiServiceBaseUri;
        var authServiceFactory = {};
        var _authentication = {
            isAuth: false,
            userName: "",
            userId: "",
            name: "",
            isExternal: false,
            useRefreshTokens: false
        };
        var _externalAuthData = {
            provider: "",
            userName: "",
            externalAccessToken: ""
        };
        var _saveRegistration = function (registration) {
            _ClearSessionData();
            return $http.post(serviceBase + 'api/account/register', registration, { headers: { 'APIKey': window.crm.constants.APIKey } }).then(function (response) {
                if (response.data.Type != 'Error') {
                    localStorageService.set('authorizationData', {
                        token: response.data.access_token, userName: response.data.userName,
                        userId: response.data.userId, name: response.data.name, refreshToken: "", useRefreshTokens: false, isExternal: false
                    });
                    _authentication.isAuth = true;
                    _authentication.userName = response.data.userName;
                    _authentication.name = response.data.name;
                    _authentication.isExternal = false,
                    _authentication.useRefreshTokens = false;
                }
                return response;
            });
        };
        var _recoverPassword = function (data) {
            return $http.post(serviceBase + 'api/account/recoverpassword', data, { headers: { 'APIKey': window.crm.constants.APIKey } }).then(function (response) {
                return response;
            });
        };
        var _recoverUsername = function (data) {
            return $http.post(serviceBase + 'api/account/recoverusername', data, { headers: { 'APIKey': window.crm.constants.APIKey } }).then(function (response) {
                return response;
            });
        };
        var _changePassword = function (data) {
            return $http.post(serviceBase + 'api/account/ChangePassword', data, { headers: { 'APIKey': window.crm.constants.APIKey } }).then(function (response) {
                return response;
            });
        };
        var _getUserInfo = function () {
            return $http.get(serviceBase + 'api/account/getUserInfo', { headers: { 'APIKey': window.crm.constants.APIKey } }).then(function (response) {
                return response;
            });
        };
        var _changeUserNameEmail = function (data) {
            return $http.post(serviceBase + 'api/account/ChangeUsernameEmail', data, { headers: { 'APIKey': window.crm.constants.APIKey } }).then(function (response) {
                return response;
            });
        };

        var _login = function (loginData) {
            var data = "grant_type=password&username=" + loginData.userName + "&password=" + encodeURIComponent(loginData.password);
            //if (loginData.useRefreshTokens) {
            //data = data + "&client_id=" + ngAuthSettings.clientId;
            //}

            data = data + "&client_id=" + ngAuthSettings.clientId;
            var deferred = $q.defer();

            $http.post(serviceBase + 'token', data, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }).success(function (response) {

                if (loginData.useRefreshTokens) {
                    localStorageService.set('authorizationData', {
                        token: response.access_token, userName: loginData.userName,
                        userId: response.userId, name: response.name, refreshToken: response.refresh_token, useRefreshTokens: true, isExternal: false
                    });
                }
                else {
                    localStorageService.set('authorizationData', {
                        token: response.access_token, userName: loginData.userName,
                        userId: response.userId, name: response.name, refreshToken: "", useRefreshTokens: false, isExternal: false
                    });
                }
                _authentication.isAuth = true;
                _authentication.userId = loginData.userId;
                _authentication.userName = loginData.userName;
                _authentication.name = loginData.name;
                _authentication.isExternal = false,
                _authentication.useRefreshTokens = loginData.useRefreshTokens;
                deferred.resolve(response);

            }).error(function (err, status) {
                _ClearSessionData();
                deferred.reject(err);
            });
            return deferred.promise;
        };

        var _logOut = function () {

            _ClearSessionData();
            //this will clear the cart id from local storage
            PageCartSvc.ClearCartId();
        };

        var _ClearSessionData = function () {

            localStorageService.remove('authorizationData');

            _authentication.isAuth = false;
            _authentication.userName = "";
            _authentication.name = "";
            _authentication.isExternal = false,
            _authentication.useRefreshTokens = true;
        };

        var _fillAuthData = function () {

            var authData = localStorageService.get('authorizationData');
            if (authData) {
                _authentication.isAuth = true;
                _authentication.userName = authData.userName;
                _authentication.name = authData.name;
                _authentication.isExternal = authData.isExternal,
                _authentication.useRefreshTokens = authData.useRefreshTokens;
            }
        };
        var _refreshToken = function () {
            var deferred = $q.defer();
            var authData = localStorageService.get('authorizationData');
            if (authData) {
                if (authData.useRefreshTokens) {
                    var data = "grant_type=refresh_token&refresh_token=" + authData.refreshToken + "&client_id=" + ngAuthSettings.clientId;
                    localStorageService.remove('authorizationData');
                    $http.post(serviceBase + 'token', data, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }).success(function (response) {
                        localStorageService.set('authorizationData', {
                            token: response.access_token, userName: response.userName,
                            userId: response.userId, name: response.name, refreshToken: response.refresh_token, useRefreshTokens: true, isExternal: false
                        });
                        deferred.resolve(response);
                    }).error(function (err, status) {
                        _ClearSessionData();
                        deferred.reject(err);
                    });
                }
            }
            return deferred.promise;
        };
        var _obtainAccessToken = function (externalData) {
            var deferred = $q.defer();
            $http.get(serviceBase + 'api/account/ObtainLocalAccessToken', { params: { provider: externalData.provider, externalAccessToken: externalData.externalAccessToken } }).success(function (response) {
                localStorageService.set('authorizationData', {
                    token: response.access_token, userName: response.userName,
                    userId: response.userId, name: response.name, refreshToken: "", useRefreshTokens: false, isExternal: true
                });
                _authentication.isAuth = true;
                _authentication.userName = response.userName;
                _authentication.name = response.name;
                _authentication.isExternal = true,
                _authentication.useRefreshTokens = true;
                deferred.resolve(response);
            }).error(function (err, status) {
                _ClearSessionData();
                err.error_description = err.Message;
                deferred.reject(err);
            });
            return deferred.promise;
        };

        var _registerExternal = function (registerExternalData) {
            var deferred = $q.defer();
            $http.post(serviceBase + 'api/account/registerexternal', registerExternalData).success(function (response) {
                localStorageService.set('authorizationData', {
                    token: response.access_token, userName: response.userName,
                    userId: response.userId, name: response.name, refreshToken: "", useRefreshTokens: false, isExternal: true
                });
                _authentication.isAuth = true;
                _authentication.userName = response.userName;
                _authentication.name = response.name;
                _authentication.isExternal = true,
                _authentication.useRefreshTokens = true;
                deferred.resolve(response);
            }).error(function (err, status) {
                _ClearSessionData();
                deferred.reject(err);
            });
            return deferred.promise;
        };

        authServiceFactory.getUserInfo = _getUserInfo;
        authServiceFactory.changeUserNameEmail = _changeUserNameEmail;
        authServiceFactory.changePassword = _changePassword;
        authServiceFactory.recoverPassword = _recoverPassword;
        authServiceFactory.recoverusername = _recoverUsername;
        authServiceFactory.saveRegistration = _saveRegistration;
        authServiceFactory.login = _login;
        authServiceFactory.logOut = _logOut;
        authServiceFactory.fillAuthData = _fillAuthData;
        authServiceFactory.authentication = _authentication;
        authServiceFactory.refreshToken = _refreshToken;

        authServiceFactory.obtainAccessToken = _obtainAccessToken;
        authServiceFactory.externalAuthData = _externalAuthData;
        authServiceFactory.registerExternal = _registerExternal;

        return authServiceFactory;
    }]);;
'use strict';
app.controller('indexController', ['$scope', '$window', '$location', '$modal', 'authService', 'GuestCartSvc', 'CheckoutSvc', 'PageCartSvc', 'common', 'ContactProfileSvc',
    function ($scope, $window, $location, $modal, authService, GuestCartSvc, CheckoutSvc, PageCartSvc, common, ContactProfileSvc) {

        $scope.cartsubSection = false;
        $scope.PhotoUrl = "";

        $scope.PhotoUrl = "";

        $scope.DisableCart = window.crm.constants.DisableCart === "True" ? true : false;
        $scope.DisableProfile = window.crm.constants.DisableProfile === "True" ? true : false;

        if ($scope.DisableProfile === true && authService.authentication.isAuth) {
            authService.logOut();
            RedirectToHome();
        }

        $scope.GetBasicContactDetails = function () {
            ContactProfileSvc.getBasicContactDetails().then(function (contactDetails) {
                $scope.ContactDetails = contactDetails.data;

                if ($scope.ContactDetails.PhotoUrl !== undefined && $scope.ContactDetails.PhotoUrl !== null && $scope.ContactDetails.PhotoUrl !== "") {
                    $scope.PhotoUrl = $scope.ContactDetails.PhotoUrl + '&height=130&width=130';
                }

            }, function (red) {
            });

        };

        if ($scope.DisableProfile === false && authService.authentication.isAuth) {
            $scope.GetBasicContactDetails();
        }



        $scope.logOut = function () {
            authService.logOut();
            //RedirectToLoginSignup();
            RedirectToHome();
            //window.location.reload(true);
        };
        $scope.ToProfile = function () {
            window.location.href = window.crm.constants.baseurl + '/profile/#/info';
        };
        $scope.ToTransactions = function () {
            window.location.href = window.crm.constants.baseurl + '/transaction/#/paymenthistory';
        };
        $scope.ToMyFunds = function () {
            window.location.href = window.crm.constants.baseurl + '/Funds/#/list';
        };
        $scope.ToCheckoutPage = function (isCheckoutButton) {
            if (isCheckoutButton === false && $scope.CartItemCount > 0)
                $scope.cartsubSection = !$scope.cartsubSection;
            else
                window.location.href = window.crm.constants.baseurl + '/Checkout';
        };
        if (window.crm.constants.isAdmin !== 'True') {
            GetCartCount();
        }
        $scope.ShowLoginPopup = function () {
            $scope.modalLoginInstance = $modal.open({
                controller: "loginController",
                templateUrl: '/Content/Pages/Template2/Templates/login_topnavigation.html?v=' + window.crm.constants.version,
                keyboard: true,
                backdrop: 'static',
                sizeclass: 'modal-lg',
                scope: $scope,
                resolve: {
                    NeedToReload: function () {
                        return true;
                    }
                }
            });
            $scope.modalClose = function () {
                $scope.modalLoginInstance.close();
            };
        };

        $scope.OpenLoginPopup = function () {
            $scope.modalloginsignupInstance = $modal.open({
                controller: "LoginSignupOrGuestCheckoutPopup",
                templateUrl: '/App_Client/views/Pages/PublicPages/Account/Template3/LoginSignupOrGuestCheckoutPopup.html?v=' + window.crm.constants.version,
                keyboard: true,
                backdrop: 'static',
                sizeclass: 'modal-md',
                resolve: {
                    FunctionType: function () {
                        return "Login";
                    },
                    DataObject: function () {
                        $scope.ObjectToBeProcessed = { ItemObject: {}, OriginalObject: {}, IsRedirectionRequired: false };
                        return $scope.ObjectToBeProcessed;
                    }
                }
            });
            $scope.modalloginsignupInstance.result.then(function (value) {
                common.usSpinnerService.stop('spnPublicPagesDonationpage');
            }, function () {
            });
        };

        function GetCartCount() {
            if (authService.authentication.isAuth) {
                CheckoutSvc.getCartItemsByUserId().then(function (res) {
                    $scope.CartItemCount = res.data.length || 0;
                    $scope.CartItems = res.data;
                    $scope.TotatCartAmount = 0;
                    angular.forEach($scope.CartItems, function (obj) {
                        obj.DataObject = angular.fromJson(obj.DataObject);
                        $scope.TotatCartAmount = $scope.TotatCartAmount + obj.Amount;
                    });
                    if ($scope.CartItemCount > 0) {
                        PageCartSvc.SetCartId($scope.CartItems[0].CartId);
                    }
                }, function (err) {
                    if (IsNotNullorEmpty(err.data))
                        common.aaNotify.error(err.data);
                });
            }
            else {
                GetGuestCart();
            }
        }

        function GetGuestCart() {
            var cartId = PageCartSvc.GetCurrentCartId();
            if (cartId !== undefined && cartId !== null && cartId !== "") {
                GuestCartSvc.getCartItemByCartId(cartId).then(function (res) {
                    $scope.CartItemCount = res.data.CartItems.length || 0;
                    $scope.CartItems = res.data.CartItems;
                    $scope.TotatCartAmount = 0;
                    angular.forEach($scope.CartItems, function (obj) {
                        obj.DataObject = angular.fromJson(obj.DataObject);
                        $scope.TotatCartAmount = $scope.TotatCartAmount + obj.Amount;
                    });
                }, function (err) {
                    if (IsNotNullorEmpty(err.data))
                        common.aaNotify.error(err.data);
                });
            }
        };

        common.$rootScope.$on('RefreshCartCount', function (e, args) {
            if (window.crm.constants.isAdmin !== 'True') {
                GetCartCount();
            }
        });
    }]);;
var app = angular.module('app');

app.controller('loginController', ['$scope', 'common', '$modalInstance', '$location', 'authService', 'ngAuthSettings', 'localStorageService', 'CheckoutSvc', 'PageCartSvc', 'NeedToReload',
    function ($scope, common, $modalInstance, $location, authService, ngAuthSettings, localStorageService, CheckoutSvc, PageCartSvc, NeedToReload) {
        $scope.loginData = {
            userName: "",
            password: "",
            useRefreshTokens: false
        };

        $scope.message = "";

        var authData = localStorageService.get('authorizationData');
        if (authData != null && typeof authData != 'undefined' && window.crm.constants.isAdmin != 'True') {
            RedirectToProfile();
        }

        $scope.loginfromtopnaviation = function () {
            common.usSpinnerService.spin('spnpageslogin');
            authService.login($scope.loginData).then(function (response) {

                //once logged in, clear the guest contact details.
                PageCartSvc.ClearGuestContact();

                //This will merge the guest cart to existing cart or will update the contact id of the guest cart
                //It will also set the current cart Id in the local storage
                if (CartId != undefined && CartId != null && CartId != "") {
                    var cartId = CartId;
                    CheckoutSvc.mergeCart(cartId, response.contactId).then(function (res) {
                        if (NeedToReload === true) {
                            window.location.reload();
                        }
                        else {
                            common.$rootScope.$broadcast('RefreshCartCount');
                            $scope.ResponseData = { Value: "Close", ContactId: response.contactId };
                            $modalInstance.close($scope.ResponseData);
                        }

                    }, function (error) {
                    });
                }
                else {
                    if (NeedToReload === true) {
                        window.location.reload();
                    }
                    else {
                        common.$rootScope.$broadcast('RefreshCartCount');
                        $scope.ResponseData = { Value: "Close", ContactId: response.contactId };
                        $modalInstance.close($scope.ResponseData);
                    }
                }
                common.usSpinnerService.stop('spnpageslogin');
            }, function (err) {
                if (IsNotNullorEmpty(err.error_description))
                    common.aaNotify.error(err.error_description);
                $scope.message = err.error_description;
                common.usSpinnerService.stop('spnpageslogin');
            });
        };

        $scope.ToSignup = function () {
            RedirectToSignup();
        };
        $scope.FromTopforgotpassword = function () {
            RedirectToForgotPassword();
        };
        $scope.FromTopforgotUsername = function () {
            RedirectToForgotUsername();
        };

        $scope.gotoSignup = function () {
            common.$location.path('/signup');
        }
        $scope.ToForgotPassword = function () {
            common.$location.path('/forgotpassword');
        };
        $scope.ToForgotUsername = function () {
            common.$location.path('/forgotusername');
        };

        $scope.authExternalProvider = function (provider) {
            var redirectUri = location.protocol + '//' + location.host + '/app_client/views/pages/publicpages/authcomplete.html';
            var externalProviderUrl = ngAuthSettings.apiServiceBaseUri + "api/Account/ExternalLogin?provider=" + provider
                + "&response_type=token&client_id=" + ngAuthSettings.clientId
                + "&APIKey=" + window.crm.constants.APIKey
                + "&redirect_uri=" + redirectUri;
            window.$windowScope = $scope;
            var oauthWindow = window.open(externalProviderUrl, "Authenticate Account", "location=0,status=0,width=600,height=750");
        };

        $scope.authCompletedCB = function (fragment) {
            $scope.$apply(function () {
                if (fragment.haslocalaccount == 'False') {
                    authService.logOut();
                    authService.externalAuthData = {
                        provider: fragment.provider,
                        userName: fragment.external_user_name,
                        externalAccessToken: fragment.external_access_token
                    };
                    common.$location.path('/login');
                }
                else {
                    //Obtain access token and redirect to orders
                    var contactId = fragment.contactId;
                    var externalData = { provider: fragment.provider, externalAccessToken: fragment.external_access_token };
                    authService.obtainAccessToken(externalData).then(function (response) {

                        //once logged in, clear the guest contact details.
                        PageCartSvc.ClearGuestContact();

                        //This will merge the guest cart to existing cart or will update the contact id of the guest cart
                        //It will also set the current cart Id in the local storage
                        if (CartId != undefined && CartId != null && CartId != "") {
                            var cartId = CartId;
                            CheckoutSvc.mergeCart(cartId, contactId).then(function (res) {
                                window.location.reload();
                            },
                                function (error) {
                                });
                        }
                        else {
                            window.location.reload();
                        }
                    }, function (err) {
                        common.aaNotify.error(err.error_description);
                        $scope.message = err.error_description;
                    });
                }
            });
        }

        $scope.CloseLogin = function () {
            $modalInstance.dismiss('cancel');
        }

    }]);

app.controller('loginPageController', ['$scope', 'common', '$location', 'authService', 'ngAuthSettings', 'localStorageService', 'CheckoutSvc', 'PageCartSvc',
    function ($scope, common, $location, authService, ngAuthSettings, localStorageService, CheckoutSvc, PageCartSvc) {
        $scope.loginData = {
            userName: "",
            password: "",
            useRefreshTokens: false
        };

        $scope.message = "";

        var authData = localStorageService.get('authorizationData');
        if (authData != null && typeof authData != 'undefined' && window.crm.constants.isAdmin != 'True') {
            RedirectToProfile();
        }

        $scope.login = function () {
            common.usSpinnerService.spin('spnpageslogin');
            authService.login($scope.loginData).then(function (response) {

                //once logged in, clear the guest contact details.
                PageCartSvc.ClearGuestContact();

                //This will merge the guest cart to existing cart or will update the contact id of the guest cart
                //It will also set the current cart Id in the local storage
                if (CartId != undefined && CartId != null && CartId != "") {
                    var cartId = CartId;
                    CheckoutSvc.mergeCart(cartId, response.contactId).then(function (res) {
                        common.usSpinnerService.stop('spnpageslogin');
                        RedirectToHome();

                    }, function (error) {
                    });
                }
                else {
                    common.usSpinnerService.stop('spnpageslogin');
                    RedirectToHome();
                }
            }, function (err) {
                if (IsNotNullorEmpty(err.error_description))
                    common.aaNotify.error(err.error_description);
                $scope.message = err.error_description;
                common.usSpinnerService.stop('spnpageslogin');
            });
        };

        $scope.ToSignup = function () {
            RedirectToSignup();
        };
        $scope.FromTopforgotpassword = function () {
            RedirectToForgotPassword();
        };
        $scope.FromTopforgotUsername = function () {
            RedirectToForgotUsername();
        };

        $scope.gotoSignup = function () {
            common.$location.path('/signup');
        }
        $scope.ToForgotPassword = function () {
            common.$location.path('/forgotpassword');
        };
        $scope.ToForgotUsername = function () {
            common.$location.path('/forgotusername');
        };

        $scope.authExternalProvider = function (provider) {
            var redirectUri = location.protocol + '//' + location.host + '/app_client/views/pages/publicpages/authcomplete.html';
            var externalProviderUrl = ngAuthSettings.apiServiceBaseUri + "api/Account/ExternalLogin?provider=" + provider
                + "&response_type=token&client_id=" + ngAuthSettings.clientId
                + "&APIKey=" + window.crm.constants.APIKey
                + "&redirect_uri=" + redirectUri;
            window.$windowScope = $scope;
            var oauthWindow = window.open(externalProviderUrl, "Authenticate Account", "location=0,status=0,width=600,height=750");
        };

        $scope.authCompletedCB = function (fragment) {
            $scope.$apply(function () {
                if (fragment.haslocalaccount == 'False') {
                    authService.logOut();
                    authService.externalAuthData = {
                        provider: fragment.provider,
                        userName: fragment.external_user_name,
                        externalAccessToken: fragment.external_access_token
                    };
                    common.$location.path('/login');
                }
                else {
                    //Obtain access token and redirect to orders
                    var contactId = fragment.contactId;
                    var externalData = { provider: fragment.provider, externalAccessToken: fragment.external_access_token };
                    authService.obtainAccessToken(externalData).then(function (response) {

                        //once logged in, clear the guest contact details.
                        PageCartSvc.ClearGuestContact();

                        //This will merge the guest cart to existing cart or will update the contact id of the guest cart
                        //It will also set the current cart Id in the local storage
                        if (CartId != undefined && CartId != null && CartId != "") {
                            var cartId = CartId;
                            CheckoutSvc.mergeCart(cartId, contactId).then(function (res) {
                                window.location.reload();
                            },
                                function (error) {
                                });
                        }
                        else {
                            window.location.reload();
                        }
                    }, function (err) {
                        common.aaNotify.error(err.error_description);
                        $scope.message = err.error_description;
                    });
                }
            });
        }

        $scope.CloseLogin = function () {
            $modalInstance.dismiss('cancel');
        }

    }]);;
'use strict';
app.controller('forgotpasswordController', ['$scope', 'authService', 'ngAuthSettings', 'common', function ($scope, authService, ngAuthSettings, common) {

    $scope.forgotdata = {
        UserName: "",
        URL: window.crm.constants.pageUrl
    };
    $scope.message = "";

    if (window.crm.constants.isAdmin == 'True') {
        RedirectToHome();
    };
    if (authService.authentication.isAuth) {
        RedirectToHome();
    }
    $scope.recover = function () {
        common.usSpinnerService.spin('spnpagesrecoverpassword');
        authService.recoverPassword($scope.forgotdata).then(function (res) {
            common.usSpinnerService.stop('spnpagesrecoverpassword');
            $scope.ShowMessage(res.data);

            $scope.ForgotPasswordForm.$aaFormExtensions.$clearErrors();
            $scope.forgotdata = {
                UserName: "",
                URL: window.crm.constants.pageUrl
            };
            $scope.frmforgotpassword.$aaFormExtensions.$reset();
            $scope.frmforgotpassword.$aaFormExtensions.$clearErrors();
            $scope.message = "";
        },
         function (err) {
             if (IsNotNullorEmpty(err.error_description))
                 common.aaNotify.error(err.error_description);
             $scope.message = err.error_description;
             common.usSpinnerService.stop('spnpagesrecoverpassword');
         });
    };

    $scope.cancel = function () {
        // common.$location.path('/login');
        RedirectToLoginSignup();
    };

    $scope.ShowMessage = function (Message) {
        if (Message != null) {
            if (Message.Type == 'Error' || Message.Type == '1') {
                common.aaNotify.error(Message.Description);
                return false;
            }
            else {
                common.aaNotify.success(Message.Description);
                return true;
            }
        }
        else {
            return true;
        }
    };

}]);;
'use strict';
app.controller('forgotusernameController', ['$scope', 'authService', 'ngAuthSettings', 'common', function ($scope, authService, ngAuthSettings, common) {

    $scope.forgotdata = {
        Email: "",
        URL: window.crm.constants.pageUrl
    };
    $scope.message = "";

    if (window.crm.constants.isAdmin == 'True') {
        RedirectToHome();
    };
    if (authService.authentication.isAuth) {
        RedirectToHome();
    }

    $scope.recover = function () {
        common.usSpinnerService.spin('spnpagesrecoverusername');
        authService.recoverusername($scope.forgotdata).then(function (res) {
            common.usSpinnerService.stop('spnpagesrecoverusername');
            $scope.ShowMessage(res.data);
            //$scope.forgotdata = {
            //    Email: "",
            //    URL: window.crm.constants.pageUrl
            //};
            $scope.message = "";
        },
         function (err) {
             if (IsNotNullorEmpty(err.error_description))
                 common.aaNotify.error(err.error_description);
             $scope.message = err.error_description;
             common.usSpinnerService.stop('spnpagesrecoverusername');
         });
    };
    $scope.cancel = function () {
        //  common.$location.path('/login');
        RedirectToLoginSignup();
    };

    $scope.ShowMessage = function (Message) {
        if (Message != null) {
            if (Message.Type == 'Error' || Message.Type == '1') {
                common.aaNotify.error(Message.Description);
                return false;
            }
            else {
                common.aaNotify.success(Message.Description);
                $scope.forgotdata = {
                    Email: "",
                    URL: window.crm.constants.pageUrl
                };
                $scope.ForgotusernameForm.$aaFormExtensions.$reset();
                $scope.ForgotusernameForm.$aaFormExtensions.$clearErrors();
                return true;
            }
        }
        else {
            return true;
        }
    };

}]);;
app.controller('AvioryImageEditorCtrl', ['$scope', '$location', '$routeParams', function ($scope, $location, $routeParams) {
    var featherEditor = null;
    $scope.UpdateImageUrl = "";
    
    $scope.InitImageEditor = function () {
        $scope.SaveEditedImage($scope.ImageUrl);
    }
    $scope.SaveEditedImage = function (updateImageUrl) {
        if (typeof $scope.CloseImageEditorPopup != 'undefined') {
            $scope.CloseImageEditorPopup(updateImageUrl);
        }
    }
    $scope.ClosePopup = function () {
        if ($scope.UpdateImageUrl != undefined && $scope.UpdateImageUrl != '') {
            $scope.SaveEditedImage($scope.UpdateImageUrl);
        }
        else {
            $scope.CancelImageEditorPopup();
        }
    }
    $scope.InitImageEditor();
}]);
;
var app = angular.module('app');

app.directive('publicpagescontactaddress', ['$compile', '$http', '$templateCache', '$parse', 'ContactProfileSvc',
    function ($compile, $http, $templateCache, $parse, ContactProfileSvc) {
        var compiler = function (tElement, tAttrs) {
            return function (originalScope, element, attrs, modelCtrl) {
                var tplURL = "/App_Client/views/Pages/PublicPages/Account/" + attrs.templatename + "/directives/PagesContactAddress.html?v=" + window.crm.constants.version;
                templateLoader = $http.get(tplURL, { cache: $templateCache }).success(function (html) {
                    tElement.html(html);
                });
                templateLoader.then(function (templateText) {
                    element.html($compile(tElement.html())(originalScope));
                });
            };
        }
        return {
            restrict: 'E',
            replace: true,
            require: 'ngModel',
            compile: compiler,
            link: function (originalScope, element, attrs, modelCtrl) {
            },
            scope: {
                Address: '=ngModel',
                ContactId: '=contactid',
                AddressType: '@addresstype',
                HeaderText: '@headertext',
                ContactGroupType: '@contactgrouptype',
                sameasmailing: '@sameasmailing',
                isMailingAddressFlag: '@ismailingaddressflag',
                isForAttendeeForm: '@isforattendeeform',
                isrequired: '=isrequired',
                templatename: '@templatename',
                sameasmailingchange: '&sameasmailingchange',
                isaddressdisabled: '@isaddressdisabled',
                dupPrefOrganizationInfoValidation: '=duppreforganizationinfovalidation',
                setpostalcodeincc: '&setpostalcodeincc',
                IndexId: '@indexid',
            },

            controller: ["$scope", "$modal", "$filter", "common", "PagesContactAddressSvc",
                function ($scope, $modal, $filter, common, PagesContactAddressSvc) {
                    $scope.CountryList = window.crm.list.countries;
                    $scope.StateList = window.crm.list.states;
                    $scope.LocalStorage = {};
                    $scope.identity = angular.identity;
                    $scope.isAddressRquired = $scope.isrequired === 'true' || $scope.isrequired === true ? true : false;
                    $scope.InitAddress = function () {

                        $scope.isAddressRquired = $scope.isrequired === 'true' || $scope.isrequired === true ? true : false;
                        $scope.isForAttendeeForm = $scope.isForAttendeeForm === 'true' || $scope.isForAttendeeForm === true ? true : false;

                        $scope.CitiesList = [];

                        if ($scope.Address === undefined || $scope.Address === null || $scope.Address.AddressLine1 === undefined
                            || $scope.Address.AddressLine1 === null || $scope.Address.AddressLine1 === "") {
                            if (!IsNotNullorEmpty($scope.Address)) {
                                $scope.Address = {};
                            }

                            $scope.Address.Country = window.crm.constants.defaultCountry;

                            if ($scope.Address.Country === 'USA' && IsNotNullorEmpty($scope.Address.PostalCode)) {
                                PagesContactAddressSvc.GetAddressFromZipCode(window.crm.constants.client, $scope.Address.PostalCode).then(function (res) {
                                    if (IsNotNullorEmpty(res.data) && IsNotNullorEmpty(res.data.Cities)) {
                                        $scope.CitiesList = res.data.Cities;
                                    }
                                });
                            }
                            $scope.Address.SelectedCity = $scope.Address.City;
                            $scope.LocalStorage.LocalFromDate = convertUTCDateToLocalDate($scope.Address.FromDate);
                            $scope.LocalStorage.LocalToDate = convertUTCDateToLocalDate($scope.Address.ToDate);
                        }
                        else {
                            if ($scope.Address.Country === 'USA' && IsNotNullorEmpty($scope.Address.PostalCode)) {
                                PagesContactAddressSvc.GetAddressFromZipCode(window.crm.constants.client, $scope.Address.PostalCode).then(function (res) {
                                    if (IsNotNullorEmpty(res.data) && IsNotNullorEmpty(res.data.Cities)) {
                                        $scope.CitiesList = res.data.Cities;
                                    }
                                });
                            }
                            $scope.Address.SelectedCity = $scope.Address.City;
                            $scope.LocalStorage.LocalFromDate = convertUTCDateToLocalDate($scope.Address.FromDate);
                            $scope.LocalStorage.LocalToDate = convertUTCDateToLocalDate($scope.Address.ToDate);

                        }
                        $scope.Address.AddressType = $scope.AddressType;

                        if ($scope.Address.Varified) {
                            $scope.LocalStorage.VerifiedBy = '<b>Verified by ' + $scope.Address.AVSProvider + '</b>'
                            $scope.LocalStorage.VerifiedDetails = '<div style=width:200px> <span> Verified By : </span> <span><b> ' + $scope.Address.AVSProvider + '</b></span></b></div>' +
                                '<div style=width:200px> <span> DeliveryPointBarcode : </span> <span><b> ' + $scope.Address.DeliveryPointBarcode + '</b></span></b></div>' +
                                '<div style=width:200px> <span> CarrierRoute : </span> <span><b> ' + $scope.Address.CarrierRoute + '</b></span></b></div>' +
                                '<div style=width:200px> <span> Latitude : </span> <span><b> ' + $scope.Address.Latitude + '</b></span></b></div>' +
                                '<div style=width:200px> <span> Longitude : </span> <span><b> ' + $scope.Address.Longitude + '</b></span></b></div>'
                        }
                    }

                    $scope.$watch('LocalStorage.LocalFromDate', function (item) {
                        if (IsNotNullorEmpty(item) && $scope.Address.AddressType === 'Seasonal' || $scope.Address.AddressType === 'Temporary')
                            $scope.Address.FromDate = convertUTCDateToLocalDate(item);
                        else
                            $scope.Address.FromDate = '';
                    });

                    $scope.$watch('LocalStorage.LocalToDate', function (item) {
                        if (IsNotNullorEmpty(item) && $scope.Address.AddressType === 'Seasonal' || $scope.Address.AddressType === 'Temporary')
                            $scope.Address.ToDate = convertUTCDateToLocalDate(item);
                        else
                            $scope.Address.ToDate = '';
                    });

                    $scope.$watch('Address.SelectedCity', function (city) {
                        if (IsNotNullorEmpty($scope.Address))
                            $scope.Address.City = city;
                    });

                    $scope.$watch('Address.StateRegionProvince', function (StateRegionProvince) {
                        if (IsNotNullorEmpty($scope.Address))
                            $scope.Address.StateRegionProvince = StateRegionProvince;
                    });

                    $scope.$watch('Address.AddressId', function () {
                        if ($scope.Address.AddressId > 0 && $scope.Address.AddressCategory === "Home") {
                            $scope.GetSharedAddressCount();
                            $scope.InitAddress();
                        }
                    });

                    $scope.SetAddress = function () {
                        $scope.setpostalcodeincc($scope.Address.PostalCode);

                        if (!IsNotNullorEmpty($scope.Address.PostalCode))
                            $scope.Address.PostalCode = '';
                        if ($scope.Address.Country === 'USA') {
                            return PagesContactAddressSvc.GetAddressFromZipCode(window.crm.constants.client, $scope.Address.PostalCode).then(function (res) {
                                if (res.data !== 'null') {
                                    if (IsNotNullorEmpty(res.data.Cities))
                                        $scope.CitiesList = res.data.Cities;
                                    $scope.Address.StateRegionProvince = res.data.StateAbbrivation;
                                    $scope.Address.County = res.data.County;

                                }
                                else {
                                    $scope.Address.StateRegionProvince = '';
                                    $scope.Address.County = '';
                                    $scope.Address.City = '';
                                    $scope.CitiesList = [];
                                    $scope.Address.SelectedCity = '';
                                }
                                $scope.Address.AddressLine3 = '';
                                $scope.Address.AddressLine4 = '';
                            });
                        }
                    }

                    $scope.OnCountryChange = function () {
                        if ($scope.Address.Country !== 'USA') {
                            $scope.Address.StateRegionProvince = '';
                            $scope.Address.County = '';
                            $scope.Address.City = '';
                            $scope.CitiesList = [];
                            $scope.Address.SelectedCity = '';
                            $scope.Address.Varified = false;
                            $scope.Address.CarrierRoute = '';
                            $scope.Address.DeliveryPointBarcode = '';
                            $scope.Address.AVSProvider = '';
                            $scope.Address.AddressCensusStatistics = '';
                            $scope.Address.AddressJurisdictions = '';
                            $scope.Address.Latitude = '';
                            $scope.Address.Longitude = '';
                            $scope.Address.Plus4Code = '';
                        }
                    }

                    $scope.SetAsMailingAddress = function () {
                        if ($scope.sameasmailingchange !== undefined) {
                            $scope.sameasmailingchange();
                        }
                    }

                    $scope.$watch('isrequired', function (item) {
                        $scope.isAddressRquired = $scope.isrequired === 'true' || $scope.isrequired === true ? true : false;
                    });

                    $scope.ValidateAddress = function () {
                        if (IsNotNullorEmpty($scope.Address)) {
                            if (IsNotNullorEmpty($scope.Address.Country) && $scope.Address.Country === 'USA') {
                                if (IsNotNullorEmpty($scope.Address.AddressLine2) || IsNotNullorEmpty($scope.Address.PostalCode) || IsNotNullorEmpty($scope.Address.City) || IsNotNullorEmpty($scope.Address.County)) {
                                    return true;
                                }
                            }
                            else if (IsNotNullorEmpty($scope.Address.AddressLine2) || IsNotNullorEmpty($scope.Address.AddressLine3) || IsNotNullorEmpty($scope.Address.AddressLine4) || IsNotNullorEmpty($scope.Address.PostalCode) || IsNotNullorEmpty($scope.Address.City) || IsNotNullorEmpty($scope.Address.County)) {
                                return true;
                            }
                        }
                        return $scope.isAddressRquired;
                    }

                    $scope.GetSharedAddressCount = function () {
                        if (IsNotNullorEmpty($scope.Address.AddressId) && $scope.ContactId > 0 && $scope.Address.AddressCategory && $scope.Address.AddressCategory === 'Home') {
                            ContactProfileSvc.GetHouseholdRelations($scope.ContactId).then(function (res) {
                                $scope.HouseholdList = res.data;
                            });
                        }
                        else
                            $scope.SharedAddressCount = 0;
                    }

                    $scope.IsFieldRequired = function (FieldName) {
                        switch (FieldName) {
                            case "AddressLine1":
                                if ($scope.dupPrefOrganizationInfoValidation !== undefined && $scope.dupPrefOrganizationInfoValidation !== null)
                                    return $scope.ContactGroupType === "individual"
                                        ? $scope.isAddressRquired === true && $scope.dupPrefOrganizationInfoValidation.AddressLine1 === true ? true : false
                                        : $scope.isAddressRquired === true && $scope.dupPrefOrganizationInfoValidation.OrganizationAddressLine1 === true ? true : false;
                                else
                                    return $scope.isAddressRquired;
                            case "AddressLine2":
                                if ($scope.dupPrefOrganizationInfoValidation !== undefined && $scope.dupPrefOrganizationInfoValidation !== null)
                                    return $scope.ContactGroupType === "individual"
                                        ? $scope.isAddressRquired === true && $scope.dupPrefOrganizationInfoValidation.AddressLine2 === true ? true : false
                                        : $scope.isAddressRquired === true && $scope.dupPrefOrganizationInfoValidation.OrganizationAddressLine2 === true ? true : false;
                                else
                                    return false;
                            case "AddressLine3":
                                if ($scope.dupPrefOrganizationInfoValidation !== undefined && $scope.dupPrefOrganizationInfoValidation !== null)
                                    return $scope.ContactGroupType === "individual"
                                        ? $scope.isAddressRquired === true && $scope.dupPrefOrganizationInfoValidation.AddressLine3 === true ? true : false
                                        : $scope.isAddressRquired === true && $scope.dupPrefOrganizationInfoValidation.OrganizationAddressLine3 === true ? true : false;
                                else
                                    return false;
                            case "AddressLine4":
                                if ($scope.dupPrefOrganizationInfoValidation !== undefined && $scope.dupPrefOrganizationInfoValidation !== null)
                                    return $scope.ContactGroupType === "individual"
                                        ? $scope.isAddressRquired === true && $scope.dupPrefOrganizationInfoValidation.AddressLine4 === true ? true : false
                                        : $scope.isAddressRquired === true && $scope.dupPrefOrganizationInfoValidation.OrganizationAddressLine4 === true ? true : false;
                                else

                                    return false;
                            case "City":
                                if ($scope.dupPrefOrganizationInfoValidation !== undefined && $scope.dupPrefOrganizationInfoValidation !== null)
                                    return $scope.ContactGroupType === "individual"
                                        ? $scope.isAddressRquired === true && $scope.dupPrefOrganizationInfoValidation.City === true ? true : false
                                        : $scope.isAddressRquired === true && $scope.dupPrefOrganizationInfoValidation.OrganizationCity === true ? true : false;
                                else
                                    return $scope.isAddressRquired;
                            case "State":
                                if ($scope.dupPrefOrganizationInfoValidation !== undefined && $scope.dupPrefOrganizationInfoValidation !== null)
                                    return $scope.ContactGroupType === "individual"
                                        ? $scope.isAddressRquired === true && $scope.dupPrefOrganizationInfoValidation.State === true ? true : false
                                        : $scope.isAddressRquired === true && $scope.dupPrefOrganizationInfoValidation.OrganizationState === true ? true : false;
                                else
                                    return $scope.isAddressRquired;
                            case "Zip":
                                if ($scope.dupPrefOrganizationInfoValidation !== undefined && $scope.dupPrefOrganizationInfoValidation !== null)
                                    return $scope.ContactGroupType === "individual"
                                        ? $scope.isAddressRquired === true && $scope.dupPrefOrganizationInfoValidation.Zip === true ? true : false
                                        : $scope.isAddressRquired === true && $scope.dupPrefOrganizationInfoValidation.OrganizationZip === true ? true : false;
                                else
                                    return $scope.isAddressRquired;
                            default:
                                return false;
                        }
                    };

                    $scope.ValidationMessage = function (fieldLabel) {
                        fieldLabel = $filter('translate')(fieldLabel);
                        if ($scope.templatename === "Template3" && $scope.isForAttendeeForm === true)
                            return fieldLabel + " for Attendee " + String($scope.IndexId) + " is required.";
                        else
                            return fieldLabel + " is required.";
                    };

                    $scope.InitAddress();
                }]
        };
    }]);

//app.directive('pagescustomPopover', function () {
//    return {
//        restrict: 'A',
//        template: '<span>{{label}}</span>',
//        link: function (scope, el, attrs) {
//            scope.label = attrs.popoverLabel;
//            $(el).popover({
//                trigger: 'click',
//                html: true,
//                content: attrs.popoverHtml,
//                placement: attrs.popoverPlacement
//            });
//        }
//    };
//});;
var app = angular.module('app');

app.directive('publicpagessingleaddress', ['$compile', '$http', '$templateCache', '$parse',
  function ($compile, $http, $templateCache, $parse) {
      var compiler = function (tElement, tAttrs) {
          return function (originalScope, element, attrs, modelCtrl) {
              var tplURL = "/App_Client/views/Pages/PublicPages/Fundraising/" + attrs.templatename + "/directives/Address.html?v=" + window.crm.constants.version;
              templateLoader = $http.get(tplURL, { cache: $templateCache }).success(function (html) {
                  tElement.html(html);
              });
              templateLoader.then(function (templateText) {
                  element.html($compile(tElement.html())(originalScope));
              });
          };
      }
      return {
          restrict: 'E',
          replace: true,
          require: 'ngModel',
          compile: compiler,
          link: function (originalScope, element, attrs, modelCtrl) {
          },
          scope: {
              Address: '=ngModel',
              AddressType: '@addresstype',
              HeaderText: '@headertext',
              templatename: '@templatename',
              isrequired: '=isrequired'
          },

          controller: ["$scope","$modal","PagesContactAddressSvc","PagesLookupSvc", function ($scope, $modal, PagesContactAddressSvc, PagesLookupSvc) {
              $scope.CountryList = window.crm.list.countries;
              $scope.StateList = window.crm.list.states;
              $scope.LocalStorage = {};
              $scope.identity = angular.identity;
              $scope.isAddressRquired = $scope.isrequired == 'true';
              $scope.InitAddress = function () {

                  PagesLookupSvc.getContactMergeSetting().then(function (res) {
                      $scope.ContactMergeSetting = res.data;
                  }, function (err) {
                  });

                  $scope.CitiesList = [];

                  if (!IsNotNullorEmpty($scope.Address) || !IsNotNullorEmpty($scope.Address.AddressId) || $scope.Address.AddressId <= 0) {
                      if (!IsNotNullorEmpty($scope.Address))
                          $scope.Address = {};
                      if ($scope.Address.AddressId != -999) { // for anyother directive use(no contact address)
                          $scope.Address.SelectedCity = {};
                          $scope.Address.SelectedCity = '';
                          $scope.Address.Country = window.crm.constants.defaultCountry;
                          $scope.Address.StateRegionProvince = '';
                          $scope.Address.AddressType = $scope.Address.AddressType;
                          $scope.Address.AddressLine1 = '';
                          $scope.Address.AddressLine2 = '';
                          $scope.Address.AddressLine3 = '';
                          $scope.Address.AddressLine4 = '';
                          $scope.Address.PostalCode = '';
                          $scope.Address.County = '';
                          $scope.Address.City = '';
                      }
                      else {
                          if ($scope.Address.Country == 'USA' && IsNotNullorEmpty($scope.Address.PostalCode)) {
                              PagesContactAddressSvc.GetAddressFromZipCode(window.crm.constants.client, $scope.Address.PostalCode).then(function (res) {
                                  if (IsNotNullorEmpty(res.data) && IsNotNullorEmpty(res.data.Cities)) {
                                      $scope.CitiesList = res.data.Cities;
                                  }
                              });
                          }
                          $scope.Address.SelectedCity = $scope.Address.City;
                          $scope.LocalStorage.LocalFromDate = convertUTCDateToLocalDate($scope.Address.FromDate);
                          $scope.LocalStorage.LocalToDate = convertUTCDateToLocalDate($scope.Address.ToDate);
                      }
                  }
                  else {
                      if ($scope.Address.Country == 'USA' && IsNotNullorEmpty($scope.Address.PostalCode)) {
                          PagesContactAddressSvc.GetAddressFromZipCode(window.crm.constants.client, $scope.Address.PostalCode).then(function (res) {
                              if (IsNotNullorEmpty(res.data) && IsNotNullorEmpty(res.data.Cities)) {
                                  $scope.CitiesList = res.data.Cities;
                              }
                          });
                      }
                      $scope.Address.SelectedCity = $scope.Address.City;
                      $scope.LocalStorage.LocalFromDate = convertUTCDateToLocalDate($scope.Address.FromDate);
                      $scope.LocalStorage.LocalToDate = convertUTCDateToLocalDate($scope.Address.ToDate);
                  }
                  $scope.Address.AddressType = $scope.AddressType;

                  if ($scope.Address.Varified) {
                      $scope.LocalStorage.VerifiedBy = '<b>Verified by ' + $scope.Address.AVSProvider + '</b>'
                      $scope.LocalStorage.VerifiedDetails = '<div style=width:200px> <span> Verified By : </span> <span><b> ' + $scope.Address.AVSProvider + '</b></span></b></div>' +
                          '<div style=width:200px> <span> DeliveryPointBarcode : </span> <span><b> ' + $scope.Address.DeliveryPointBarcode + '</b></span></b></div>' +
                          '<div style=width:200px> <span> CarrierRoute : </span> <span><b> ' + $scope.Address.CarrierRoute + '</b></span></b></div>' +
                          '<div style=width:200px> <span> Latitude : </span> <span><b> ' + $scope.Address.Latitude + '</b></span></b></div>' +
                          '<div style=width:200px> <span> Longitude : </span> <span><b> ' + $scope.Address.Longitude + '</b></span></b></div>'
                  }
              }

              $scope.$watch('Address.SelectedCity', function (city) {
                  if (IsNotNullorEmpty($scope.Address))
                      $scope.Address.City = city;
              });

              $scope.$watch('Address.StateRegionProvince', function (StateRegionProvince) {
                  if (IsNotNullorEmpty($scope.Address))
                      $scope.Address.StateRegionProvince = StateRegionProvince;
              });

              $scope.SetAddress = function () {
                  if (!IsNotNullorEmpty($scope.Address.PostalCode)) $scope.Address.PostalCode = '';
                  if ($scope.Address.Country == 'USA') {
                      return PagesContactAddressSvc.GetAddressFromZipCode(window.crm.constants.client, $scope.Address.PostalCode).then(function (res) {
                          if (res.data != 'null') {
                              if (IsNotNullorEmpty(res.data.Cities))
                                  $scope.CitiesList = res.data.Cities;
                              $scope.Address.StateRegionProvince = res.data.StateAbbrivation;
                              $scope.Address.County = res.data.County;

                          }
                          else {
                              $scope.Address.StateRegionProvince = '';
                              $scope.Address.County = '';
                              $scope.Address.City = '';
                              $scope.CitiesList = [];
                              $scope.Address.SelectedCity = '';
                          }
                          $scope.Address.AddressLine3 = '';
                          $scope.Address.AddressLine4 = '';
                      });
                  }
              }

              $scope.OnCountryChange = function () {
                  if ($scope.Address.Country != 'USA') {
                      $scope.Address.StateRegionProvince = '';
                      $scope.Address.County = '';
                      $scope.Address.City = '';
                      $scope.CitiesList = [];
                      $scope.Address.SelectedCity = '';
                      $scope.Address.Varified = false;
                      $scope.Address.CarrierRoute = '';
                      $scope.Address.DeliveryPointBarcode = '';
                      $scope.Address.AVSProvider = '';
                      $scope.Address.AddressCensusStatistics = '';
                      $scope.Address.AddressJurisdictions = '';
                      $scope.Address.Latitude = '';
                      $scope.Address.Longitude = '';
                      $scope.Address.Plus4Code = '';
                  }
              }

              $scope.ValidateAddress = function () {
                  if (IsNotNullorEmpty($scope.Address)) {
                      if (IsNotNullorEmpty($scope.Address.Country) && $scope.Address.Country == 'USA') {
                          if (IsNotNullorEmpty($scope.Address.AddressLine2) || IsNotNullorEmpty($scope.Address.PostalCode) || IsNotNullorEmpty($scope.Address.City) || IsNotNullorEmpty($scope.Address.County)) {
                              return true;
                          }
                      }
                      else if (IsNotNullorEmpty($scope.Address.AddressLine2) || IsNotNullorEmpty($scope.Address.AddressLine3) || IsNotNullorEmpty($scope.Address.AddressLine4) || IsNotNullorEmpty($scope.Address.PostalCode) || IsNotNullorEmpty($scope.Address.City) || IsNotNullorEmpty($scope.Address.County)) {
                          return true;
                      }
                      //if($scope.ContactMergeSetting.AddressLine1)
                      //    return true;
                  }
                  return $scope.isAddressRquired;
              }

              $scope.InitAddress();
          }]
      };
  }]);
;
var routerApp = angular.module('app');
routerApp.directive('publiccontactviewphoto', ['$compile',
  function ($compile) {
      return {
          restrict: 'E',
          replace: true,
          require: 'ngModel',
          template: '<img ng-src="{{contact.PhotoUrl}}&height=130&width=130"/>',
          link: function (originalScope, element, attrs) {
          },
          scope: {
              contact: '=ngModel'
          },
          controller: ["$scope", "common",function ($scope, common) {
              $scope.client = window.crm.constants.client;
              $scope.initDirective = function () {
                  if (!IsNotNullorEmpty($scope.contact.PhotoUrl)) {
                      if ($scope.contact.ContactGroupType == 'I') {
                          if ($scope.contact.Gender == 'Male')
                              $scope.contact.PhotoUrl = '/Content/images/male-no-image-new.jpg';
                          else if ($scope.contact.Gender == 'Female')
                              $scope.contact.PhotoUrl = '/Content/images/female-no-image-new.jpg';
                          else
                              $scope.contact.PhotoUrl = '/Content/images/no-image-new.jpg';
                      }
                      else {
                          $scope.contact.PhotoUrl = '/Content/images/organisation-no-image-new.jpg';
                      }
                      $scope.contact.PhotoUrl = $scope.contact.PhotoUrl + "?t=1"
                  }
              };

              $scope.$watch(function () {
                  return [$scope.contact.PhotoUrl];
              }, function (newValue, oldValue) {
                  $scope.initDirective();
              }, true);

              $scope.initDirective();
          }]
      }
  }]);;
app.directive('publicCard', ['$compile', '$http', '$templateCache', '$parse',
    function ($compile, $http, $templateCache, $parse) {
        var compiler = function (tElement, tAttrs) {
            return function (originalScope, element, attrs, modelCtrl) {
                var tplURL = "/App_Client/views/Pages/PublicPages/Checkout/" + attrs.templatename + "/PublicCard.html?v=" + window.crm.constants.version;
                templateLoader = $http.get(tplURL, { cache: $templateCache }).success(function (html) {
                    tElement.html(html);
                });
                templateLoader.then(function (templateText) {
                    element.html($compile(tElement.html())(originalScope));

                    //assign unique id to stripe element
                    $(element[0]).find('#npe-cardnumber').first().attr({ "id": "npe-cardnumber-" + originalScope.uniqueCardId });
                    //set new id to label in "for" attribute
                    $(element[0]).find('.npe-cardnumber-label').first().attr({ "for": "npe-cardnumber-" + originalScope.uniqueCardId });
                    //execute stripe element once new unique id set
                    originalScope.cardInfo.cardNumber.mount('#npe-cardnumber-' + originalScope.uniqueCardId);

                    //assign unique id to stripe element
                    $(element[0]).find('#npe-cardexpiry').first().attr({ "id": "npe-cardexpiry-" + originalScope.uniqueCardId });
                    //set new id to label in "for" attribute
                    $(element[0]).find('.npe-cardcvv-label').first().attr({ "for": "npe-cardcvv-" + originalScope.uniqueCardId });
                    //execute stripe element once new unique id set
                    originalScope.cardInfo.cardExpiry.mount('#npe-cardexpiry-' + originalScope.uniqueCardId);

                    //assign unique id to stripe element
                    $(element[0]).find('#npe-cardcvv').first().attr({ "id": "npe-cardcvv-" + originalScope.uniqueCardId });
                    //set new id to label in "for" attribute
                    $(element[0]).find('.npe-cardcvv-label').first().attr({ "for": "npe-cardcvv-" + originalScope.uniqueCardId });
                    //execute stripe element once new unique id set
                    originalScope.cardInfo.cardCvc.mount('#npe-cardcvv-' + originalScope.uniqueCardId);

                });
            };
        };
        return {
            restrict: 'E',
            replace: true,
            compile: compiler,
            scope: {
                cardInfo: '=cardModel',
                style: '@cardStyle'
            },
            controller: ['$scope', '$element', '$attrs', '$rootScope',
                function ($scope, $element, $attrs, $rootScope) {
                    //below code is usefull when the same directive load in same page more then one
                    //the code is create unique variable to incresae number which is used to create dynamic unique id 
                    if (window.uniqueCardId) {
                        window.uniqueCardId++;
                    } else {
                        window.uniqueCardId = 1;
                    }
                    //assign it to scope to use and idetify for this directive 
                    $scope.uniqueCardId = window.uniqueCardId;
                    //hide lable based on attribute value "lable-hide"
                    $scope.labelHide = false;
                    if (typeof ($attrs.labelHide) !== 'undefined') {
                        $scope.labelHide = true;
                    }
                    //Card validation msg display flag
                    $scope.cardValidationMsg = '';
                    //execute direvice funtionality if publishable key fin
                    if (IsNotNullorEmpty(window.crm.constants.publishableKey)) {
                        //stripe objects
                        var stripe = Stripe(window.crm.constants.publishableKey);
                        var elements = stripe.elements();

                        // Floating labels
                        var inputs = document.querySelectorAll('.npe-cardnumber');
                        Array.prototype.forEach.call(inputs, function (input) {
                            input.addEventListener('focus', function () {
                                input.classList.add('focused');
                            });
                            input.addEventListener('blur', function () {
                                input.classList.remove('focused');
                            });
                            input.addEventListener('keyup', function () {
                                if (input.value.length === 0) {
                                    input.classList.add('empty');
                                } else {
                                    input.classList.remove('empty');
                                }
                            });
                        });
                        //default UI object
                        var cardStyle = {
                            base: {
                                color: '#31325F',
                                lineHeight: '40px',
                                padding: '20px',
                                fontWeight: 400,
                                fontFamily: '"Open Sans", Arial, sans-serif',
                                fontSize: '16px',
                                '::placeholder': {
                                    color: '#ccc',
                                },
                            },
                            invalid: {
                                color: '#e5424d',
                                ':focus': {
                                    color: '#303238',
                                },
                            }
                        }


                        var elementClasses = {
                            focus: 'focused',
                            empty: 'empty',
                            invalid: 'invalid',
                        };

                        //create card number element
                        var cardNumber = elements.create('cardNumber', {
                            style: cardStyle,
                            classes: elementClasses,
                        });

                        //create card expiry element
                        var cardExpiry = elements.create('cardExpiry', {
                            style: cardStyle,
                            classes: elementClasses,
                        });

                        //create card cvv element
                        var cardCvc = elements.create('cardCvc', {
                            style: cardStyle,
                            classes: elementClasses,
                        });

                        //get validation from stripe 
                        var errorTextBox = $($element[0]).find('label.field-info').first();
                        cardNumber.on('change', function (e) {
                            // show error if card details are not proper 
                            errorTextBox.text('');
                            if (e.error)
                                errorTextBox.text(e.error.message);
                        });
                        //assign stripe and card to the parant scope object and generate unique token useing 'cardService.getToken'
                        $scope.cardInfo = {
                            stripe: stripe,
                            cardNumber: cardNumber,
                            cardExpiry: cardExpiry,
                            cardCvc: cardCvc
                        }

                        $rootScope.$on("SetPostalCode", function (SetPostalCode, value) {
                            cardNumber.update({ value: { postalCode: value.postalCode } });
                        });


                    } else {
                        console.warn("Publisable Key not found.");
                    }
                }],
            link: function (scope, element) {
            }
        };
    }]);;
var app = angular.module('app');

app.directive('pagesPaymentOptions', ['$compile', '$http', '$templateCache', '$parse',
    function ($compile, $http, $templateCache, $parse) {
        var compiler = function (tElement, tAttrs) {
            return function (originalScope, element, attrs, modelCtrl) {
                var tplURL = "";

                if (attrs.pagename === "Popup")
                    tplURL = "/App_Client/views/Pages/PublicPages/Checkout/" + attrs.templatename + "/PaymentOptionForPopup.html?v=" + window.crm.constants.version;
                else
                    tplURL = "/App_Client/views/Pages/PublicPages/Checkout/" + attrs.templatename + "/PaymentOptions.html?v=" + window.crm.constants.version;

                templateLoader = $http.get(tplURL, { cache: $templateCache }).success(function (html) {
                    tElement.html(html);
                });
                templateLoader.then(function (templateText) {
                    element.html($compile(tElement.html())(originalScope));
                });
            };
        };
        return {
            restrict: 'E',
            replace: true,
            compile: compiler,
            link: function (originalScope, element, attrs, modelCtrl) {
            },
            scope: {
                TemplateName: '@templatename',
                PageName: '@pagename',
                ContactId: '@contactid',
                ContactDetails: '=contactdetails',
                TotalAmount: '=totalamount',
                IsInvalidForm: '=isinvalidform',
                //FormErrors: '=formErrors',
                FormName: '@formname',
                SpinnerName: '@spinnername',
                ForeignCurrency: '@foreigncurrency',
                IsOrganizationCheckout: '=isorganizationcheckout',
                IsPayLaterDisabled: '=disablepayleter',
                BailingAddress: '@bailingaddress',
                procceedtocheckout: '&procceedtocheckout',
                controllerfunction: '&controllerfunction',
                iscontrollerfunction: '@iscontrollerfunction',
                CheckoutButtonText: '@checkoutbuttontext',
                HidePayLater: '@hidepaylater',
                TransactionType: '@transactiontype' // 'D' for Donation, 'E' for event, 'M' for membership , 'C' for cart.
            },
            controller: ["$scope", "$modal", "common", "authService", "ContactProfileSvc", "ngAuthSettings", "publiccardService", "IndividualSvc",
                function ($scope, $modal, common, authService, ContactProfileSvc, ngAuthSettings, publiccardService, IndividualSvc) {
                    $scope.UseCardsOnFiles = [];
                    $scope.IsLoggedInUser = false;
                    $scope.FinalCheckoutAmount = 0;

                    $scope.isStripeButton = true;
                    $scope.CheckoutType = "Checkout";

                    $scope.ButtonText = $scope.CheckoutButtonText !== undefined && $scope.CheckoutButtonText !== null && $scope.CheckoutButtonText !== "" ? $scope.CheckoutButtonText : "Checkout";
                    $scope.ShowPayLater = $scope.HidePayLater === true || $scope.HidePayLater === 'true' ? true : false;
                    $scope.IsForCartCheckout = $scope.IsCartCheckout === true || $scope.IsCartCheckout === 'true' ? true : false;

                    $scope.DisableCart = window.crm.constants.DisableCart === "True" ? true : false;
                    $scope.DisableProfile = window.crm.constants.DisableProfile === "True" ? true : false;
                    $scope.PayLaterOn = window.crm.list.clientPageModuleSetting.PayLaterOn;
                    $scope.PayLaterLabel = window.crm.list.clientPageModuleSetting.PayLaterLabel;

                    $scope.PaymentOptions = {
                        TempPaymentOptionSelect: "NewCard",
                        CreditCard:
                        {
                            FirstName: "", LastName: ""
                        },
                        BillingAddress: {},
                        PaymentType: "payCheckout"
                    };

                    $scope.Configuration = {};

                    $scope.InitPaymentOptions = function () {
                        if ($scope.DisableProfile === false) {
                            if (authService.authentication.isAuth) {
                                $scope.IsLoggedInUser = authService.authentication.isAuth;
                                $scope.GetCardonfile();
                            }
                            else {
                                if ($scope.ContactDetails !== undefined && $scope.ContactDetails !== null) {
                                    $scope.IsOrganizationCheckout = $scope.ContactDetails.CheckoutAs === "O";
                                    if ($scope.ContactDetails.CheckoutAs === "I") {
                                        $scope.PaymentOptions.CreditCard.FirstName = $scope.ContactDetails.FirstName;
                                        $scope.PaymentOptions.CreditCard.LastName = $scope.ContactDetails.LastName;
                                    }
                                    else {
                                        $scope.PaymentOptions.CreditCard.FirstName = $scope.ContactDetails.Name;
                                    }
                                }
                            }
                        }
                        else if ($scope.DisableProfile === true) {
                            if ($scope.ContactDetails !== undefined && $scope.ContactDetails !== null) {
                                $scope.IsOrganizationCheckout = $scope.ContactDetails.CheckoutAs === "O";
                                if ($scope.ContactDetails.CheckoutAs === "I") {
                                    $scope.PaymentOptions.CreditCard.FirstName = $scope.ContactDetails.FirstName;
                                    $scope.PaymentOptions.CreditCard.LastName = $scope.ContactDetails.LastName;
                                }
                                else {
                                    $scope.PaymentOptions.CreditCard.FirstName = $scope.ContactDetails.Name;
                                }
                            }
                        }
                    };

                    $scope.GetCardonfile = function () {
                        //Get cards on file
                        ContactProfileSvc.getBasicContactDetails().then(function (contactDetails) {
                            $scope.PaymentOptions.CreditCard.FirstName = contactDetails.data.FirstName;
                            $scope.PaymentOptions.CreditCard.LastName = contactDetails.data.LastName;
                            ContactProfileSvc.GetCardsOnFile().then(function (response) {
                                $scope.UseCardsOnFiles = response.data;
                                $scope.SetCardSelection();
                            }, function (red) {
                            });
                        }, function (red) {
                        });
                    };

                    $scope.GetCardonfileByContact = function (contactId) {
                        //Get cards on file
                        common.usSpinnerService.spin($scope.SpinnerName);
                        IndividualSvc.GetContact(contactId).then(function (contactDetails) {
                            $scope.PaymentOptions.CreditCard.FirstName = contactDetails.data.FirstName;
                            $scope.PaymentOptions.CreditCard.LastName = contactDetails.data.LastName;
                            //Get cards on file
                            $scope.UseCardsOnFiles = [];
                            ContactProfileSvc.GetContactCardsById(contactId).then(function (response) {
                                $scope.UseCardsOnFiles = response.data;
                                common.usSpinnerService.stop($scope.SpinnerName);
                                $scope.SetCardSelection();
                            }, function (red) {
                            });
                        }, function (red) {
                        });
                    };

                    $scope.SetCardSelection = function () {
                        if ($scope.UseCardsOnFiles.length > 0) {
                            var getdefaultselected = _.find($scope.UseCardsOnFiles, function (card) { return card.Default === true; });
                            if (IsNotNullorEmpty(getdefaultselected)) {
                                $scope.PaymentOptions.CardOnFileId = getdefaultselected.CardOnFileId;
                                $scope.PaymentOptions.TempPaymentOptionSelect = $scope.PaymentOptions.CardOnFileId;
                            }
                            else {
                                $scope.PaymentOptions.CardOnFileId = 0;
                                $scope.PaymentOptions.TempPaymentOptionSelect = "NewCard";
                            }
                        }
                        else {
                            $scope.PaymentOptions.CardOnFileId = 0;
                            $scope.PaymentOptions.TempPaymentOptionSelect = "NewCard";
                        }
                    }

                    $scope.CheckUncheckPaylaterOption = function (value) {
                        $scope.PaymentOptions.PayLeter = value;
                        if (value === true) {
                            $scope.PaymentOptions.TempPaymentOptionSelect = "PayLater";
                        }
                        else if (value === false) {
                            $scope.PaymentOptions.TempPaymentOptionSelect = "NewCard";
                        }
                    };

                    $scope.PaymentOptionSelect = function (existingCard, newCard, payLater) {
                        if (payLater !== null) {
                            $scope.PaymentOptions.CardOnFileId = 0;
                            $scope.PaymentOptions.PayLater = true;
                        }
                        else if (newCard !== null) {
                            $scope.PaymentOptions.CardOnFileId = 0;
                            $scope.PaymentOptions.PayLater = false;
                        }
                        else {
                            $scope.PaymentOptions.PayLater = false;
                            $scope.PaymentOptions.CardOnFileId = existingCard.CardOnFileId;
                        }
                    };

                    $scope.$on('getCCToken', function (event) {
                        $scope.PayNow();
                    });

                    $scope.$on('checkoutByPayLeter', function (event) {
                        $scope.PayLater();
                    });

                    $scope.$on('setCardContact', function (event, args) {
                        if (args !== undefined && args !== null) {
                            if ($scope.IsOrganizationCheckout === true || args.CheckoutAs === "O") {
                                $scope.IsOrganizationCheckout = true;
                                $scope.PaymentOptions.CreditCard.FirstName = args.Name;
                            }
                            else {
                                $scope.PaymentOptions.CreditCard.FirstName = args.FirstName;
                                $scope.PaymentOptions.CreditCard.LastName = args.LastName;
                            }
                        }
                    });

                    $scope.CallControllerFunction = function (checkoutType) {
                        if ($scope.IsInvalidForm === true) {
                            common.aaNotify.error("Please fill required details.");
                            return;
                        }
                        else {
                            if ($scope.iscontrollerfunction !== undefined && $scope.iscontrollerfunction !== null
                                && ($scope.iscontrollerfunction === false || $scope.iscontrollerfunction === 'false')) {
                                switch (checkoutType) {
                                    case "Checkout":
                                        $scope.PayNow();
                                        break;
                                    case "PayLater":
                                        $scope.PayLater();
                                        break;
                                    default:
                                }
                            }
                            else {
                                $scope.controllerfunction({ CheckoutType: checkoutType });
                            }
                        }
                    };

                    $scope.PayNow = function () {
                        if ($scope.IsInvalidForm === true) {
                            common.aaNotify.error("Please fill required details.");
                            return;
                        }
                        if ($scope.PaymentOptions.TempPaymentOptionSelect === "NewCard" || $scope.PaymentOptions.TempPaymentOptionSelect === "PayButton") {
                            var name = "";
                            if ($scope.IsOrganizationCheckout === false) {
                                name = $scope.PaymentOptions.CreditCard.FirstName + " " + $scope.PaymentOptions.CreditCard.LastName;
                            }
                            else {
                                name = $scope.PaymentOptions.CreditCard.FirstName;
                            }

                            publiccardService.getToken($scope.PaymentOptions.CreditCard.cardInfo, $scope.PaymentOptions.BillingAddress, name).then(function (result) {
                                $scope.procceedtocheckout({
                                    PaymentOption: {
                                        Key: "CardToken",
                                        Value: result,
                                        Tokenize: $scope.PaymentOptions.Tokenize !== undefined && $scope.PaymentOptions.Tokenize !== null && $scope.PaymentOptions.Tokenize !== "" ? $scope.PaymentOptions.Tokenize : false
                                    }
                                });
                            }, function (error) {
                                common.usSpinnerService.stop('spnPublicPagesDonationpage');
                                common.aaNotify.error(error);
                            });
                        }
                        else if ($scope.PaymentOptions.CardOnFileId > 0) {
                            $scope.procceedtocheckout({ PaymentOption: { Key: "CardOnFileId", Value: $scope.PaymentOptions.CardOnFileId } });
                        }

                    };

                    $scope.PayLater = function () {
                        $scope.procceedtocheckout({ PaymentOption: { Key: "PayLater", Value: "PayLater" } });
                    };

                    $scope.$watch('IsPayLaterDisabled', function (oldValue, newValue) {
                        if (oldValue !== newValue) {
                            if ($scope.IsPayLaterDisabled === true) {
                                $scope.CheckUncheckPaylaterOption(false);
                            }
                        }
                    });

                    $scope.$watch('ContactId', function (newValue) {
                        switch ($scope.TransactionType) {
                            case "M"://Membership
                                if (newValue > 0)
                                    $scope.GetCardonfileByContact(newValue);
                                else {
                                    $scope.UseCardsOnFiles = [];
                                    $scope.PaymentOptions.TempPaymentOptionSelect = "NewCard";
                                }
                                break;
                            case "D"://Donation
                            case "E"://Donation
                            case "P"://Pledge
                            case "ES"://eStore
                                if (newValue > 0 && authService.authentication.isAuth)
                                    $scope.GetCardonfileByContact(newValue);
                                break;
                            default:
                        }
                    });

                    $scope.stripePaymentMethodReceived = function (arg) {

                        $scope.PaymentOptions.TempPaymentOptionSelect = "PayButton";
                        $scope.PaymentOptions.CardOnFileId = 0;
                        $scope.PaymentOptions.CreditCard.cardInfo.StripePaymentMethodID = arg.PaymentInfo.paymentMethod.id;
                        $scope.PaymentOptions.CreditCard.FirstName = arg.Name.FirstName;
                        $scope.PaymentOptions.CreditCard.LastName = arg.Name.LastName;

                        //$scope.Checkout.CheckoutDetails.PayLater = false; //Safety assignment to make sure paylater is not true


                        common.usSpinnerService.spin('spnGuestCart');
                        let counter = 1;
                        let waitForUpdateName = setInterval(() => {
                            if ($("#CCFirstName").val() === arg.Name.FirstName) {
                                common.usSpinnerService.stop('spnGuestCart');
                                $scope.CallControllerFunction('Checkout');
                                clearInterval(waitForUpdateName);
                            } else {
                                if (counter > 24) {
                                    $scope.CallControllerFunction('Checkout');
                                    common.usSpinnerService.stop('spnGuestCart');
                                    clearInterval(waitForUpdateName);
                                }
                            }
                            counter++;
                        }, 500);
                    }

                    $scope.$watch('TotalAmount', function (oldValue, newValue) {
                        $scope.UpdateFinalAmount();
                    });

                    $scope.UpdateFinalAmount = function () {
                        $scope.FinalCheckoutAmount = $scope.TotalAmount;
                    };

                    $scope.stripeButtonInit = function (arg) {
                        $scope.isStripeButton = arg.isStripeButton;
                    };
                    $scope.Configuration.CardStyle = {
                        base: {

                            color: '#333333',
                            lineHeight: '40px',
                            fontWeight: 400,
                            fontSize: '16px',
                        },
                        invalid: {
                            color: '#e5424d'
                        },
                        placeholder: {
                            fontStyle: 'italic'
                        }
                    };

                    $scope.InitPaymentOptions();
                }]
        };
    }]);
;
var app = angular.module('app');

app.directive('pagesGuestProfile', ['$compile', '$http', '$templateCache', '$parse', function ($compile, $http, $templateCache, $parse) {
    var compiler = function (tElement, tAttrs) {
        return function (originalScope, element, attrs, modelCtrl) {
            var tplURL = "/App_Client/views/Pages/PublicPages/Account/" + attrs.templatename + "/directives/GuestProfile.html?v=" + window.crm.constants.version;
            templateLoader = $http.get(tplURL, { cache: $templateCache }).success(function (html) {
                tElement.html(html);
            });
            templateLoader.then(function (templateText) {
                element.html($compile(tElement.html())(originalScope));
            });
        };
    };
    return {
        restrict: 'E',
        replace: true,
        require: 'ngModel',
        compile: compiler,
        link: function (originalScope, element, attrs, modelCtrl) {
        },
        scope: {
            Contact: '=ngModel',
            IsOrganizationCheckout: '=isorganizationcheckout',
            HideIndividualContactDetails: '=hideindividualcontactdetails',
            HideOrganizationContactDetails: '=hideorganizationcontactdetails',
            changecontactfunction: '&changecontactfunction',
            SpinnerName: '@spinnername',
            TemplateName: '@templatename',
            ShowLoginOption: '@showloginoption',
            Page: '@page',
            Place: '@place'
        },
        controller: ["$scope", "$modal", "common", "authService", "ContactProfileSvc", "ngAuthSettings", "cardService", 'PagesLookupSvc', 'WorkInformationsSvc', 'PageCartSvc',
            function ($scope, $modal, common, authService, ContactProfileSvc, ngAuthSettings, cardService, PagesLookupSvc, WorkInformationsSvc, PageCartSvc) {
                //$scope.IsOrganizationCheckout = false;
                $scope.ContactMergeSetting = {};
                $scope.IsAddressRequired = false;
                $scope.KeepAddressFieldDisalbed = false;
                $scope.DisableProfile = window.crm.constants.DisableProfile === "True" ? true : false;
                $scope.ShowLoginButton = $scope.ShowLoginOption === 'True' || $scope.ShowLoginOption === 'true' || $scope.ShowLoginOption === true ? true : false
                $scope.GuestRegistrant = {};
                $scope.DisableContactFields = false;
                $scope.IndexId = Math.floor((Math.random() * 600) + 1);

                $scope.InitGuestProfile = function () {

                    $scope.Contact.KeepDetailsSaved = $scope.DisableProfile === true;

                    if ($scope.Contact.IsOrgSelected === undefined || $scope.Contact.IsOrgSelected === null) {
                        $scope.Contact.IsOrgSelected = false;
                    }

                    if (!authService.authentication.isAuth && $scope.DisableProfile === true
                        && $scope.HideIndividualContactDetails === false && $scope.HideOrganizationContactDetails === false) {
                        $scope.GuestRegistrant = PageCartSvc.GetCurrentGuestContact();
                        if ($scope.GuestRegistrant !== undefined && $scope.GuestRegistrant !== null) {
                            angular.copy($scope.GuestRegistrant, $scope.Contact);
                            $scope.DisableContactFields = true;
                            $scope.IsOrganizationCheckout = $scope.GuestRegistrant.CheckoutAs === "O";
                        }
                    }
                    $scope.GetAddressSettings();
                };

                $scope.GetAddressSettings = function () {
                    common.usSpinnerService.spin($scope.SpinnerName);
                    PagesLookupSvc.getContactMergeSetting().then(function (res) {
                        $scope.ContactMergeSetting = res.data;
                        $scope.CheckIsAddressRequired();
                        common.usSpinnerService.stop($scope.SpinnerName);
                    }, function (err) {
                    });
                };

                $scope.CheckIsAddressRequired = function () {
                    if ($scope.IsOrganizationCheckout === false) {
                        //Individual Checkout
                        if ($scope.ContactMergeSetting.IndividualEmailAndAddressCondition === true && ($scope.ContactMergeSetting.AddressLine1 === true || $scope.ContactMergeSetting.AddressLine2 === true ||
                            $scope.ContactMergeSetting.AddressLine3 === true || $scope.ContactMergeSetting.AddressLine4 === true || $scope.ContactMergeSetting.City === true || $scope.ContactMergeSetting.State === true ||
                            $scope.ContactMergeSetting.Zip === true)) {

                            $scope.IsAddressRequired = true;

                            if ($scope.HideIndividualContactDetails === true || $scope.HideIndividualContactDetails === 'true')
                                $scope.KeepAddressFieldDisalbed = true;
                            else
                                $scope.KeepAddressFieldDisalbed = false;
                        }
                        else {
                            $scope.IsAddressRequired = false;
                        }
                    }
                    else {
                        //Organization Checkout
                        if ($scope.ContactMergeSetting.OrganizationAddressLine1 === true ||
                            $scope.ContactMergeSetting.OrganizationAddressLine2 === true ||
                            $scope.ContactMergeSetting.OrganizationAddressLine3 === true ||
                            $scope.ContactMergeSetting.OrganizationAddressLine4 === true ||
                            $scope.ContactMergeSetting.OrganizationCity === true ||
                            $scope.ContactMergeSetting.OrganizationState === true ||
                            $scope.ContactMergeSetting.OrganizationZip === true) {

                            $scope.IsAddressRequired = true;

                            if ($scope.HideOrganizationContactDetails === true || $scope.HideOrganizationContactDetails === 'true')
                                $scope.KeepAddressFieldDisalbed = true;
                            else
                                $scope.KeepAddressFieldDisalbed = false;
                        }
                        else {
                            $scope.IsAddressRequired = false;
                        }
                    }
                };

                $scope.ChangeGroupType = function () {
                    $scope.Contact.SelectedOrgText = null;
                    $scope.Contact.IsOrgSelected = false;
                    $scope.Contact.FirstName = "";
                    $scope.Contact.LastName = "";
                    $scope.Contact.Email = "";
                    $scope.CheckIsAddressRequired();
                };

                $scope.$watch('Contact.Organization', function (value) {
                    if (value === undefined || value === null || value === "") {
                        $scope.Contact.IsOrgSelected = false;
                        $scope.Contact.SelectedOrgText = {};
                        $scope.OrganizationNameList = [];
                    }
                });

                $scope.ToggleClass = function () {
                    if ($scope.Place !== "popup")
                        return "chk-btn large";
                    else
                        return "chk-btn small";
                };

                $scope.GetOrganizationbyName = function (name) {
                    $scope.Contact.IsOrgSelected = false;
                    $scope.Contact.SelectedOrgText = {};
                    $scope.Contact.ContactId = 0;
                    $scope.OrganizationNameList = [];
                    return WorkInformationsSvc.GetOrganizationbyName(name).then(function (res) {
                        $scope.OrganizationNameList = KeyValueToArray(res.data);
                        return $scope.OrganizationNameList;
                    });
                };

                $scope.OnOrganizationSelect = function ($item, $model, $label) {
                    $scope.Contact.SelectedOrgText = $item;
                    $scope.Contact.IsOrgSelected = true;
                };

                $scope.$watch('Contact.SelectedOrgText', function (oldValue, newValue) {
                    if ($scope.IsOrganizationCheckout === true) {
                        if ($scope.Contact.IsOrgSelected === true && $scope.Contact.SelectedOrgText !== undefined && $scope.Contact.SelectedOrgText !== null && $scope.Contact.SelectedOrgText.id > 0) {
                            $scope.Contact.Name = $scope.Contact.SelectedOrgText.name;
                            $scope.Contact.ContactId = $scope.Contact.SelectedOrgText.id;
                        }
                        else {
                            $scope.Contact.Name = $scope.Contact.Organization;
                        }
                    }
                    else {
                        $scope.Contact.Organization = $scope.Contact.Name = "";
                        $scope.Contact.ContactId = 0;
                        $scope.Contact.IsOrgSelected = false;
                    }
                });

                $scope.OpenLoginPopup = function (ActionType) {
                    $scope.modalloginsignupInstance = $modal.open({
                        controller: "LoginSignupOrGuestCheckoutPopup",
                        templateUrl: '/App_Client/views/Pages/PublicPages/Account/' + $scope.TemplateName + '/LoginSignupOrGuestCheckoutPopup.html?v=' + window.crm.constants.version,
                        keyboard: true,
                        backdrop: 'static',
                        sizeclass: $scope.TemplateName === "Template3" ? 'modal-md' : 'modal-lg',
                        resolve: {
                            FunctionType: function () {
                                return $scope.Page === "Cart" ? "Cart" + ActionType : ActionType;
                            },
                            DataObject: function () {
                                $scope.ObjectToBeProcessed = { ItemObject: {}, OriginalObject: {}, IsRedirectionRequired: false };
                                return $scope.ObjectToBeProcessed;
                            }
                        }
                    });
                    $scope.modalloginsignupInstance.result.then(function (responseData) {
                        if (responseData.ContactId > 0) {
                            $scope.Contact.ContactId = responseData.ContactId;
                        }
                    }, function () {
                    });
                };

                $scope.$on('DisabledContactFields', function (event) {
                    $scope.DisableContactFields = true;
                });

                $scope.ChangeContact = function () {
                    if ($scope.HideIndividualContactDetails === false && $scope.HideOrganizationContactDetails === false) {
                        $scope.Contact = {
                            MailingAddress: { SetAsMailing: true, Country: window.crm.constants.defaultCountry },
                            ShippingAddress: { Country: window.crm.constants.defaultCountry, AddressType: "Billing" },
                            ContactId: 0,
                            IsOrgSelected: false,
                            KeepDetailsSaved: true
                        }
                        $scope.IsOrganizationCheckout = $scope.DisableContactFields = false;
                        PageCartSvc.ClearGuestContact();
                        $scope.GetAddressSettings();
                    }
                    else {
                        $scope.DisableContactFields = false;
                    }
                    $scope.changecontactfunction();
                }

                $scope.$watch('Contact', function (value) {
                    common.$rootScope.$broadcast('setCardContact', value);
                }, true);

                $scope.InitGuestProfile();
            }]
    };
}]);
;
app.directive('paymentButton', ["usSpinnerService", function (usSpinnerService) {
    return {
        restrict: 'E',
        replace: true,
        scope: {
            amount: '=',
            currency: '=',
            country: '@',
            onPaySuccess: '&',
            onButtonInit: '&'
        },
        link: function (scope, element) {
            //below code is usefull when the same directive load in same page more then one
            //the code is create unique variable to incresae number which is used to create dynamic unique id 
            if (window.uniquePaymentButtonId) {
                window.uniquePaymentButtonId++;
            } else {
                window.uniquePaymentButtonId = 1;
            }

            //assign it to scope to use and idetify for this directive 
            scope.strPaymentButtonId = "npe-payment-button-" + window.uniquePaymentButtonId;
            $(element[0]).find("stripe-payment-button").attr({ "id": scope.strPaymentButtonId });

            //get stripe publishable key
            let publishableKey = window.crm.constants.publishableKey || null;

            //if publishable key exist, watch on amount and currency to generate button
            if (IsNotNullorEmpty(publishableKey)) {
                scope.$watch('amount', (a) => {
                    if (typeof (a) !== "undefined" && a !== null && !isNaN(a)) {
                        proceesForButton();
                    } else {
                        scope.onButtonInit({ arg: { isStripeButton: false } });
                    }
                });
                scope.$watch('currency', (a) => {
                    if (typeof (scope.amout) !== "undefined" && typeof (a) !== "undefined") {
                        proceesForButton();
                    }
                });
            } else {
                scope.onButtonInit({ arg: { isStripeButton: false } });
                console.warn("Publishable Key not found.");
            }

            function proceesForButton() {
                usSpinnerService.spin('spnPaymentButton');

                //Declare variables
                scope.prButton;
                let stripe = Stripe(publishableKey);
                
                let elements = stripe.elements();

                let currency = scope.currency || 'usd';
                let amount = parseFloat(scope.amount);
                amount = Math.round(amount.toFixed(2) * 100);
                var paymentRequestObject = {
                    country: scope.country || "US", // pass from out side
                    currency: currency.toLowerCase(), //pass from out side
                    total: {
                        label: window.crm.constants.OrgName || "Fundly CRM", //Pass from out side
                        amount, //Pass from outside
                    },
                    requestPayerName: true,
                    requestPayerEmail: true,
                }
                //create payment request button
                

                let paymentRequest = stripe.paymentRequest(paymentRequestObject);
                if (typeof (scope.prButton) === 'object') {
                    scope.prButton.unmount();
                    scope.prButton.destroy();
                }

                //create payment request to check weather payment button available or not. 
               
                paymentRequest.canMakePayment().then((result) => {
                    let button = document.getElementById('payment-request-button');
                    if (result) {
                        button.addEventListener('click', paymentRequest.show);
                       // scope.prButton.mount('#' + scope.strPaymentButtonId);
                        usSpinnerService.stop('spnPaymentButton');
                        scope.onButtonInit({ arg: { isStripeButton: true } });
                    } else {
                        usSpinnerService.stop('spnPaymentButton');
                        scope.onButtonInit({ arg: { isStripeButton: false } });
                    }
                });

                paymentRequest.on('paymentmethod', function (ev) {

                    //Report to the browser that the confirmation was successful, prompting
                    //it to close the browser payment method collection interface.
                    ev.complete('success');

                    let Name = ev.payerName;
                    let SplitedName = Name.split(" ");
                    let FinalNameObj = { FullName: Name };
                    switch (SplitedName.length) {
                        case 2:
                            FinalNameObj.FirstName = SplitedName[0];
                            FinalNameObj.LastName = SplitedName[1];
                            break;
                        case 3:
                            FinalNameObj.FirstName = SplitedName[0];
                            FinalNameObj.LastName = SplitedName[2];
                            break;
                        default: break;
                    }
                    //callback to parent controller with arguments
                    var callbackArg = {
                        Name: FinalNameObj,
                        PaymentInfo: ev
                    }
                    scope.onPaySuccess({ arg: callbackArg });
                });
            }
        },
        templateUrl: "/App_Client/common/directives/PublicPages/paymentbutton.directive.html?v=" + window.crm.constants.version
    }
}]);;
var app = angular.module('app');

app.controller('LoginSignupPopupCtrl', ['$scope', 'common', '$modalInstance', 'localStorageService', 'authService', 'CheckoutSvc', 'PageCartSvc', 'ngAuthSettings', 'ContactMergeSetting', 'FunctionType', 'WorkInformationsSvc',
    function ($scope, common, $modalInstance, localStorageService, authService, CheckoutSvc, PageCartSvc, ngAuthSettings, ContactMergeSetting, FunctionType, WorkInformationsSvc) {
        $scope.registration = {};
        $scope.ContactMergeSetting = ContactMergeSetting;
        $scope.FunctionType = FunctionType;
        $scope.GuestContactDetails = { FirstName: "", LastName: "", Email: "", CheckoutAs: "", GuestOrganization: {} };
        $scope.ShowMainScreen = true;
        $scope.CheckoutAs = "I";
        $scope.IsSignup = false;
        $scope.OrganizationNameList = [];
        $scope.IsOrgSelected = false;
        $scope.GuestOrganization = { Name: "", Email: "" };

        function initpopup() {
            $scope.ContactMergeSetting = ContactMergeSetting;
            $scope.FunctionType = FunctionType;
            $scope.ShowMainScreen = $scope.FunctionType == 'IsGuestContact' ? false : true;
            CheckAddressRequired();
        }

        $scope.Close = function () {
            $modalInstance.close("Close");
        };

        $scope.ContinueAsGuest = function () {
            $modalInstance.close("ContinueAsGuest");
        };

        //#region Login
        $scope.loginData = {
            userName: "",
            password: "",
            useRefreshTokens: false
        };
        $scope.message = '';

        var authData = localStorageService.get('authorizationData');

        $scope.login = function () {
            common.usSpinnerService.spin('spnpageslogin');
            authService.login($scope.loginData).then(function (response) {
                authService.fillAuthData();

                switch (FunctionType) {
                    case "IsAddToWaitList":
                        $modalInstance.close();
                        if (IsAddToWaitList)
                            $scope.openaddtowaitlist();
                        else {
                            common.$rootScope.$broadcast('RefreshCartCount');
                            $scope.SaveRegistration();
                        }
                        break;
                    case "IsMembership":
                        $modalInstance.close();
                        $scope.RedirectToMembershipPage();
                        break;
                    case "IsGuestCheckout":

                        //once logged in, clear the guest contact details.
                        PageCartSvc.ClearGuestContact();

                        $modalInstance.close();
                        //This will merge the guest cart to existing cart or will update the contact id of the guest cart
                        //It will also set the current cart Id in the local storage
                        if (CartId != undefined && CartId != null && CartId != "") {
                            var cartId = CartId;
                            CheckoutSvc.mergeCart(cartId, response.contactId).then(function (res) {
                                //This will save the cart id in the local storage
                                common.usSpinnerService.stop('spnLoginSignupDiv');
                                PageCartSvc.SetCartId(res.data.CartId);
                                window.location.reload();
                            }, function (error) {
                            });
                        }
                        else {
                            $modalInstance.close();
                            common.usSpinnerService.stop('spnLoginSignupDiv');
                            window.location.reload();
                        }
                        break;
                    case "IsGuestContact":
                        $modalInstance.close("ContinueAsGuestContact");
                        break;
                    default:
                        $modalInstance.close("LoggedIn");
                        break;
                }
                common.usSpinnerService.stop('spnpageslogin');
            }, function (err) {
                $scope.message = err.error_description;
                common.usSpinnerService.stop('spnpageslogin');
            });
        };

        $scope.authExternalProvider = function (provider) {
            var redirectUri = location.protocol + '//' + location.host + '/app_client/views/pages/publicpages/authcomplete.html';
            var externalProviderUrl = ngAuthSettings.apiServiceBaseUri + "api/Account/ExternalLogin?provider=" + provider
                + "&response_type=token&client_id=" + ngAuthSettings.clientId
                + "&APIKey=" + window.crm.constants.APIKey
                + "&redirect_uri=" + redirectUri;
            window.$windowScope = $scope;
            var oauthWindow = window.open(externalProviderUrl, "Authenticate Account", "location=0,status=0,width=600,height=750");
        };

        $scope.authCompletedCB = function (fragment) {
            $scope.$apply(function () {
                if (fragment.haslocalaccount == 'False') {
                    authService.logOut();
                    authService.externalAuthData = {
                        provider: fragment.provider,
                        userName: fragment.external_user_name,
                        externalAccessToken: fragment.external_access_token
                    };
                    common.$location.path('/login');
                }
                else {
                    //Obtain access token and redirect to orders
                    var contactId = fragment.contactId;
                    var externalData = { provider: fragment.provider, externalAccessToken: fragment.external_access_token };
                    authService.obtainAccessToken(externalData).then(function (response) {
                        switch (FunctionType) {
                            case "IsAddToWaitList":
                                $modalInstance.close();
                                if (IsAddToWaitList)
                                    $scope.openaddtowaitlist();
                                else {
                                    common.$rootScope.$broadcast('RefreshCartCount');
                                    $scope.SaveRegistration();
                                }
                                break;
                            case "IsMembership":
                                $modalInstance.close();
                                $scope.RedirectToMembershipPage();
                                break;
                            case "IsGuestCheckout":

                                //once logged in, clear the guest contact details.
                                PageCartSvc.ClearGuestContact();

                                $modalInstance.close();
                                //This will merge the guest cart to existing cart or will update the contact id of the guest cart
                                //It will also set the current cart Id in the local storage
                                if (CartId != undefined && CartId != null && CartId != "") {
                                    var cartId = CartId;
                                    CheckoutSvc.mergeCart(cartId, response.contactId).then(function (res) {
                                        //This will save the cart id in the local storage
                                        common.usSpinnerService.stop('spnLoginSignupDiv');
                                        PageCartSvc.SetCartId(res.data.CartId);
                                        window.location.reload();
                                    }, function (error) {
                                    });
                                }
                                else {
                                    $modalInstance.close();
                                    common.usSpinnerService.stop('spnLoginSignupDiv');
                                    window.location.reload();
                                }
                                break;
                            case "IsGuestContact":
                                $modalInstance.close("ContinueAsGuestContact");
                                break;
                            default:
                                $modalInstance.close("LoggedIn");
                                break;
                        }
                    }, function (err) {
                        $scope.message = err.error_description;
                    });
                }
            });
        }
        //#endregion

        //#region Signup
        $scope.savedSuccessfully = false;

        $scope.ContinueAsUser = function (userType) {
            $scope.CheckoutAs = userType;
            $scope.ShowMainScreen = true;
        }

        $scope.ContinueAsGuestContact = function () {
            $scope.GuestContactDetails.CheckoutAs = $scope.CheckoutAs;
            if ($scope.CheckoutAs == "O") {
                if (IsNotNullorEmpty($scope.SelectedOrgText) && IsNotNullorEmpty($scope.SelectedOrgText.name)) {

                    $scope.GuestContactDetails.GuestOrganization = {};
                    $scope.GuestContactDetails.GuestOrganization.name = $scope.SelectedOrgText.name;
                    $scope.GuestContactDetails.GuestOrganization.id = $scope.SelectedOrgText.id;
                }
                else {
                    $scope.GuestContactDetails.GuestOrganization = {};
                    $scope.GuestContactDetails.GuestOrganization.Name = $scope.GuestOrganization.Name;
                    $scope.GuestContactDetails.GuestOrganization.Email = $scope.GuestOrganization.Email;
                }
            }
            PageCartSvc.SetGuestContact($scope.GuestContactDetails);
            $modalInstance.close("ContinueAsGuestContact");
        }

        function CheckAddressRequired() {
            if ($scope.ContactMergeSetting.AddressLine1 == true || $scope.ContactMergeSetting.AddressLine2 == true
                || $scope.ContactMergeSetting.City == true || $scope.ContactMergeSetting.State == true ||
                $scope.ContactMergeSetting.Zip == true) {
                $scope.AddressRequired = 'true';
            }
            else
                $scope.AddressRequired = 'false';
        }

        $scope.signUpMessage = '';
        $scope.signUp = function () {
            var errors = [];
            common.usSpinnerService.spin('spnpagesregistration');
            authService.saveRegistration($scope.registration).then(function (response) {
                common.usSpinnerService.stop('spnpagesregistration');
                if (response.data.Type == 'Error' && typeof response.data.Description != 'undefined') {
                    $scope.savedSuccessfully = false;
                    errors.push(response.data.Description);
                    //$scope.message = "Failed to register user due to:" + response.data.Description;
                    $scope.signUpMessage = "Failed to register user due to:" + response.data.Description;
                }
                else {
                    $scope.savedSuccessfully = true;

                    switch (FunctionType) {
                        case "IsAddToWaitList":
                            $modalInstance.close();
                            if (IsAddToWaitList)
                                $scope.openaddtowaitlist();
                            else {
                                common.$rootScope.$broadcast('RefreshCartCount');
                                $scope.SaveRegistration();
                            }
                            break;
                        case "IsMembership":
                            $modalInstance.close();
                            $scope.RedirectToMembershipPage();
                            break;
                        case "IsGuestCheckout":

                            //once logged in, clear the guest contact details.
                            PageCartSvc.ClearGuestContact();

                            $modalInstance.close();
                            //This will merge the guest cart to existing cart or will update the contact id of the guest cart
                            //It will also set the current cart Id in the local storage
                            if (CartId != undefined && CartId != null && CartId != "") {
                                var cartId = CartId;
                                CheckoutSvc.mergeCart(cartId, response.contactId).then(function (res) {
                                    //This will save the cart id in the local storage
                                    common.usSpinnerService.stop('spnLoginSignupDiv');
                                    PageCartSvc.SetCartId(res.data.CartId);
                                    window.location.reload();
                                }, function (error) {
                                });
                            }
                            else {
                                $modalInstance.close();
                                common.usSpinnerService.stop('spnLoginSignupDiv');
                                window.location.reload();
                            }
                            break;
                        case "IsGuestContact":
                            $modalInstance.close("ContinueAsGuestContact");
                            break;
                        default:
                            $modalInstance.close("LoggedIn");
                            break;
                    }
                    $scope.signUpMessage = response.data.Description;
                }
            }, function (response) {
                $scope.savedSuccessfully = false;
                for (var key in response.data.ModelState) {
                    for (var i = 0; i < response.data.ModelState[key].length; i++) {
                        errors.push(response.data.ModelState[key][i]);
                    }
                }
                if (response.data.Type == 'Error' && typeof response.data.Description != 'undefined') {
                    errors.push(response.data.Description);
                }
                //$scope.message = "Failed to register user due to:" + errors.join(' ');
                $scope.signUpMessage = "Failed to register user due to:" + errors.join(' ');
                common.usSpinnerService.stop('spnpagesregistration');
            });
        };
        //#endregion

        $scope.FromTopforgotpassword = function () {
            RedirectToForgotPassword();
        };

        $scope.FromTopforgotUsername = function () {
            RedirectToForgotUsername();
        };

        $scope.GetOrganizationbyName = function (name) {
            $scope.OrganizationNameList = [];
            return WorkInformationsSvc.GetOrganizationbyName(name).then(function (res) {
                $scope.OrganizationNameList = KeyValueToArray(res.data);
                return $scope.OrganizationNameList;
            });
        }

        $scope.OnOrganizationSelect = function ($item, $model, $label) {
            $scope.SelectedOrgText = $item;
            $scope.IsOrgSelected = true;
        }

        $scope.GoToSignup = function () {
            $scope.message = '';
            $scope.IsSignup = !$scope.IsSignup;
        }

        initpopup();

    }]);;
var app = angular.module('app');

app.controller('LoginSignupOrGuestCheckoutPopup', ['$scope', '$modal', 'common', '$modalInstance', 'localStorageService', 'authService', 'CheckoutSvc', 'PageCartSvc', 'ngAuthSettings', 'FunctionType', 'PagesLookupSvc', 'DataObject', 'GuestCartSvc', 'publiccardService', 'eStorePageSvc', 'ContactProfileSvc',
    function ($scope, $modal, common, $modalInstance, localStorageService, authService, CheckoutSvc, PageCartSvc, ngAuthSettings, FunctionType, PagesLookupSvc, DataObject, GuestCartSvc, publiccardService, eStorePageSvc, ContactProfileSvc) {

        $scope.PayLaterOn = window.crm.list.clientPageModuleSetting.PayLaterOn;
        $scope.PayLaterLabel = window.crm.list.clientPageModuleSetting.PayLaterLabel;
        $scope.DisableCart = window.crm.constants.DisableCart === "True" ? true : false;
        $scope.DisableProfile = window.crm.constants.DisableProfile === "True" ? true : false;
        $scope.TemplateName = getResolveValue(common, 'TemplateName');
        $scope.CurrentTab = "";
        $scope.TempContactId = 0;

        $scope.ProductCost = 0;
        $scope.ShippingCost = 0;
        $scope.SalesTax = 0;
        $scope.RegistrationCost = 0;
        $scope.OtherItemTotal = 0;
        $scope.EstoreItemTotal = 0;

        $scope.IsShippingAddressRequired = false;

        $scope.IsRedirectionRequired = DataObject.IsRedirectionRequired !== undefined && DataObject.IsRedirectionRequired !== null ? DataObject.IsRedirectionRequired : false;
        $scope.NextStepToPerform = DataObject.NextStepToPerform;

        $scope.registration = {
            MailingAddress: { SetAsMailing: true }
        };
        $scope.FunctionType = FunctionType;
        $scope.ShowMainScreen = true;
        $scope.CheckoutAs = "I";
        $scope.CurrentStep = "Login";
        $scope.OrganizationNameList = [];
        $scope.IsOrgSelected = false;
        $scope.GuestOrganization = { Name: "", Email: "" };
        $scope.IsMemberRegistrationTypeExists = false;
        $scope.ErrorMessage = "";
        $scope.TransactionType = "";

        $scope.ContactShippingAddresses = [];

        if (DataObject.ContactShippingAddresses !== undefined
            && DataObject.ContactShippingAddresses !== null
            && DataObject.ContactShippingAddresses.length > 0) {
            $scope.ContactShippingAddresses = angular.copy(DataObject.ContactShippingAddresses);
        }

        $scope.DataObject = DataObject.ItemObject;
        $scope.OriginalObject = DataObject.OriginalObject;

        $scope.ShippingAddress = {
            AddressLine1: "",
            AddressLine2: "",
            SelectedCity: "",
            StateRegionProvince: "",
            PostalCode: "",
            Country: window.crm.constants.defaultCountry
        };

        $scope.IsAddressSelectedFromList = false;

        $scope.HideIndividualContactDetails = false;
        $scope.HideOaganizationContactDetails = false;

        $scope.IndexId = Math.floor((Math.random() * 600) + 1);

        $scope.CouponObject = {
            CouponCode: "",
            ContactDetails: {
                IndividualInfo: {}, OrganizationInfo: {}
            },
            Discount: 0,
            CouponId: 0,
            ItemId: 0
        };

        $scope.Checkout = {
            CheckoutDetails:
                {
                    SameAsMailing: 'true',
                    Billing: {},
                    CardInformation: { CardOnFileId: 0, Tokenize: false },
                    PayLater: false,
                    IsPayeLaterDisabled: false,
                    Organization: {}
                },
            ContactDetails: {
                MailingAddress: { SetAsMailing: true },
                ShippingAddress: {},
                ContactId: 0
            },
            UserDetails: {},
            CartId: "",
            IsOrganizationCheckout: false,
            CheckoutAs: "",
            IncludeCharges: false,
            DoubleTheDonationDetails: {},
            IsImmediateCheckout: true
        };

        $scope.InitLoginSignupPopup = function () {
            $scope.TemplateName = getResolveValue(common, 'TemplateName');
            $scope.FunctionType = FunctionType;
            if (authService.authentication.isAuth) {
                if ($scope.FunctionType === "EstoreCheckout") {

                    $scope.OrdersWithShipping = _.filter($scope.DataObject.Orders, function (x) { return x.IsShippingRequired === true; });

                    if ($scope.OrdersWithShipping !== undefined && $scope.OrdersWithShipping !== null && $scope.OrdersWithShipping.length > 0) {
                        //get contact details and check for the billing address
                        $scope.ShowMainScreen = false;
                        $scope.CurrentTab = "ContactDetails";
                        $scope.GetContactInfo();
                    }
                    else {
                        $scope.ShowMainScreen = false;
                        $scope.CalculateSalesTax();
                    }
                }
                else if ($scope.FunctionType === "EventCheckout") {
                    if ($scope.DataObject.EstoreBatch !== undefined && $scope.DataObject.EstoreBatch !== null && $scope.DataObject.EstoreBatch.Orders !== undefined
                        && $scope.DataObject.EstoreBatch.Orders !== null && $scope.DataObject.EstoreBatch.Orders.length > 0) {
                        var ItemWithShippingRequired = _.find($scope.DataObject.EstoreBatch.Orders, function (c) { return c.ShippingCost > 0 });
                        $scope.IsShippingAddressRequired = ItemWithShippingRequired !== undefined && ItemWithShippingRequired !== null && IsNotNullorEmpty(ItemWithShippingRequired);
                    }

                    if ($scope.IsShippingAddressRequired === true) {
                        $scope.ShowMainScreen = false;
                        $scope.CurrentTab = "ContactDetails";
                        $scope.GetContactInfo();
                    }
                    else {
                        $scope.ShowMainScreen = false;
                        $scope.CurrentStep = "Checkout";
                    }
                }
                else {
                    $scope.ShowMainScreen = false;
                    $scope.CurrentStep = "Checkout";
                }
            }
            else {
                if ($scope.DisableProfile === true) {
                    $scope.GuestRegistrant = PageCartSvc.GetCurrentGuestContact();
                    if ($scope.GuestRegistrant !== undefined && $scope.GuestRegistrant !== null) {

                        $scope.ShowMainScreen = false;
                        switch ($scope.FunctionType) {
                            case "EventCheckout":
                                angular.copy($scope.GuestRegistrant, $scope.Checkout.ContactDetails);
                                if ($scope.DataObject.EstoreBatch !== undefined && $scope.DataObject.EstoreBatch !== null && $scope.DataObject.EstoreBatch.Orders !== undefined
                                    && $scope.DataObject.EstoreBatch.Orders !== null && $scope.DataObject.EstoreBatch.Orders.length > 0) {
                                    var ItemWithShippingRequired = _.find($scope.DataObject.EstoreBatch.Orders, function (c) { return c.IsShippingRequired === true });
                                    $scope.IsShippingAddressRequired = ItemWithShippingRequired !== undefined && ItemWithShippingRequired !== null && IsNotNullorEmpty(ItemWithShippingRequired);
                                }
                                if ($scope.IsShippingAddressRequired === true) {
                                    $scope.ShowMainScreen = false;
                                    $scope.CurrentTab = "ContactDetails";
                                }
                                else {
                                    $scope.ShowMainScreen = false;
                                    $scope.CurrentStep = "Checkout";
                                }
                                break;
                            case "JoinMembership":
                                $scope.CurrentTab = "Guest";
                                break;
                            case "MembershipCheckout":
                                $scope.CurrentStep = "Checkout";
                                break;
                            default:
                                $scope.CurrentTab = "Guest";
                                break;
                        }
                    }
                    else {
                        $scope.ShowMainScreen = false;
                        $scope.CurrentTab = "Guest";
                    }
                }
            }

            $scope.TakeDefaultActionOnInit();
        };

        $scope.TakeDefaultActionOnInit = function () {
            if ($scope.DataObject !== undefined && $scope.DataObject !== null) {
                $scope.DataObject.IsImmediateCheckout = true;
            }
            switch ($scope.FunctionType) {
                case "DonationCheckout":
                    $scope.TransactionType = "D";
                    if ($scope.PayLaterOn === true) {
                        if ($scope.DataObject !== undefined && $scope.DataObject !== null
                            && $scope.DataObject.RecurringProfile !== undefined && $scope.DataObject.RecurringProfile !== null
                            && $scope.DataObject.RecurringProfile.Frequency !== undefined && $scope.DataObject.RecurringProfile.Frequency !== null && $scope.DataObject.RecurringProfile.Frequency !== ""
                            && $scope.DataObject.RecurringProfile.Amount > 0) {
                            $scope.Checkout.CheckoutDetails.IsPayeLaterDisabled = true;
                        }
                    }

                    break;
                case "EventCheckout":
                    $scope.TransactionType = "E";
                    //check whether is there any registration type having the Member only
                    if (authService.authentication.isAuth !== true) {
                        $scope.IsMemberRegistrationTypeExists = _.filter($scope.OriginalObject.RegistrationAttendees, function (x) { return x.Availability === "MemberOnly" }).length > 0;
                    }
                    $scope.CouponObject.ItemId = $scope.DataObject.EventId;
                    $scope.CouponObject.ApplicableCategory = "Event";

                    if ($scope.DataObject.EstoreBatch !== undefined && $scope.DataObject.EstoreBatch !== null && $scope.DataObject.EstoreBatch.Orders !== undefined
                        && $scope.DataObject.EstoreBatch.Orders !== null && $scope.DataObject.EstoreBatch.Orders.length > 0) {
                        var ItemWithShippingRequired = _.find($scope.DataObject.EstoreBatch.Orders, function (c) { return c.ShippingCost > 0 });
                        $scope.IsShippingAddressRequired = ItemWithShippingRequired !== undefined && ItemWithShippingRequired !== null && IsNotNullorEmpty(ItemWithShippingRequired);
                    }

                    $scope.CalculateEventCost();

                    break;
                case "MembershipCheckout":
                    $scope.TransactionType = "M";
                    if ($scope.DataObject !== undefined && $scope.DataObject !== null) {
                        $scope.CouponObject.ItemId = $scope.DataObject.Membership.MembershipLevel.MembershipLevelId;
                        $scope.CouponObject.ApplicableCategory = "NewMembership";
                        $scope.Checkout.CheckoutDetails.IsPayeLaterDisabled = $scope.DataObject.Membership.SetAutoRenewal === true;
                    }
                    if ($scope.OriginalObject !== undefined && $scope.OriginalObject !== null) {
                        $scope.HideIndividualContactDetails = $scope.OriginalObject.HideIndividualContact;
                        $scope.HideOaganizationContactDetails = $scope.OriginalObject.HideOrganizationContact;
                        $scope.Checkout.ContactDetails = $scope.OriginalObject.ContactDetails;
                        $scope.ShowMainScreen = false;
                        $scope.CurrentStep = "Checkout";
                    }
                    break;
                case "EstoreCheckout":
                    $scope.TransactionType = "ES";
                    $scope.CalculateProductCost();
                    break;
                case "ExistingLogin":
                case "CartExistingLogin":
                    $scope.SetCurrentTab("Login");
                    break;
                case "GroupMembershipLogin":
                    break;
                case "NewSignup":
                case "CartNewSignup":
                    switch ($scope.TemplateName) {
                        case "Template3":
                            $scope.SetCurrentTab("Signup");
                            $scope.CheckAddressRequired();
                            break;
                        case "Template2":
                            $scope.CurrentStep = "Signup";
                            break;
                        default:
                            break;
                    }
                    break;
                default:
                    break;
            }
        };

        $scope.NewSignup = function () {
            $scope.SetCurrentTab("Signup");
            $scope.CheckAddressRequired();
        };

        $scope.Close = function () {
            $modalInstance.close("Close");
        };

        $scope.CloseAndRefresh = function (action) {
            $modalInstance.close(action);
        };

        $scope.ContinueAsGuest = function () {
            $modalInstance.close("ContinueAsGuest");
        };

        //#region Login
        $scope.loginData = {
            userName: "",
            password: "",
            useRefreshTokens: false
        };
        $scope.message = '';

        var authData = localStorageService.get('authorizationData');

        $scope.login = function () {
            common.usSpinnerService.spin('spnpageslogin');
            authService.login($scope.loginData).then(function (response) {
                $scope.TempContactId = response.contactId;
                authService.fillAuthData();
                $scope.AfterLogin("Login");
            }, function (err) {
                $scope.message = err.error_description;
                common.usSpinnerService.stop('spnpageslogin');
            });
        };

        $scope.authExternalProvider = function (provider) {
            var redirectUri = location.protocol + '//' + location.host + '/app_client/views/pages/publicpages/authcomplete.html';
            var externalProviderUrl = ngAuthSettings.apiServiceBaseUri + "api/Account/ExternalLogin?provider=" + provider
                + "&response_type=token&client_id=" + ngAuthSettings.clientId
                + "&APIKey=" + window.crm.constants.APIKey
                + "&redirect_uri=" + redirectUri;
            window.$windowScope = $scope;
            var oauthWindow = window.open(externalProviderUrl, "Authenticate Account", "location=0,status=0,width=600,height=750");
        };

        $scope.authCompletedCB = function (fragment) {
            $scope.$apply(function () {
                if (fragment.haslocalaccount == 'False') {
                    authService.logOut();
                    authService.externalAuthData = {
                        provider: fragment.provider,
                        userName: fragment.external_user_name,
                        externalAccessToken: fragment.external_access_token
                    };
                    common.$location.path('/login');
                }
                else {
                    //Obtain access token and redirect to orders
                    var contactId = fragment.contactId;
                    var externalData = { provider: fragment.provider, externalAccessToken: fragment.external_access_token };
                    authService.obtainAccessToken(externalData).then(function (response) {
                        $scope.TempContactId = response.contactId;
                        $scope.AfterLogin("Login");
                    }, function (err) {
                        $scope.message = err.error_description;
                    });
                }
            });
        }
        //#endregion

        //#region Signup
        $scope.savedSuccessfully = false;

        $scope.ContinueAsUser = function (userType) {
            $scope.CheckoutAs = userType;
            $scope.ShowMainScreen = true;
        }

        $scope.CheckAddressRequired = function () {
            common.usSpinnerService.spin("spnpageslogin");
            PagesLookupSvc.getContactMergeSetting().then(function (res) {
                $scope.ContactMergeSetting = res.data;
                common.usSpinnerService.stop("spnpageslogin");
                $scope.SetFlag();
            }, function (err) {
            });
        }

        $scope.SetFlag = function () {
            if ($scope.ContactMergeSetting.IndividualEmailAndAddressCondition === true && ($scope.ContactMergeSetting.AddressLine1 === true || $scope.ContactMergeSetting.AddressLine2 === true ||
                $scope.ContactMergeSetting.AddressLine3 === true || $scope.ContactMergeSetting.AddressLine4 === true || $scope.ContactMergeSetting.City === true || $scope.ContactMergeSetting.State === true ||
                $scope.ContactMergeSetting.Zip === true)) {
                $scope.IsAddressRequired = true;
            }
            else {
                $scope.IsAddressRequired = false;
            }
        };

        $scope.signUpMessage = '';

        $scope.signUp = function () {
            var errors = [];
            common.usSpinnerService.spin('spnpagesregistration');
            authService.saveRegistration($scope.registration).then(function (response) {
                $scope.TempContactId = response.data.contactId;
                common.usSpinnerService.stop('spnpagesregistration');
                if (response.data.Type === 'Error' && typeof response.data.Description !== 'undefined') {
                    $scope.savedSuccessfully = false;
                    errors.push(response.data.Description);
                    //$scope.message = "Failed to register user due to:" + response.data.Description;
                    $scope.signUpMessage = "Failed to register user due to:" + response.data.Description;
                    common.aaNotify.error($scope.signUpMessage);
                    $("#signupDiv").scrollTop(0);
                }
                else {
                    $scope.AfterLogin("Signup");
                }
            }, function (response) {
                $scope.savedSuccessfully = false;
                for (var key in response.data.ModelState) {
                    for (var i = 0; i < response.data.ModelState[key].length; i++) {
                        errors.push(response.data.ModelState[key][i]);
                    }
                }
                if (response.data.Type == 'Error' && typeof response.data.Description != 'undefined') {
                    errors.push(response.data.Description);
                }
                //$scope.message = "Failed to register user due to:" + errors.join(' ');
                $scope.signUpMessage = "Failed to register user due to:" + errors.join(' ');
                common.usSpinnerService.stop('spnpagesregistration');
            });
        };
        //#endregion

        //Event Logic starts.
        $scope.AfterLogin = function (actionPerformed) {
            $scope.ShowMainScreen = false;
            $scope.CurrentTab = "";

            //once logged in, clear the guest contact details.
            PageCartSvc.ClearGuestContact();
            //This will merge the guest cart to existing cart or will update the contact id of the guest cart
            //It will also set the current cart Id in the local storage
            if ($scope.DisableCart === false && CartId !== undefined && CartId !== null && CartId !== "") {
                var cartId = CartId;
                CheckoutSvc.mergeCart(cartId, $scope.TempContactId).then(function (res) {
                    //This will save the cart id in the local storage
                    PageCartSvc.SetCartId(res.data.CartId);
                    switch ($scope.FunctionType) {
                        case "DonationCheckout":
                            common.usSpinnerService.stop('spnpageslogin');
                            $scope.CurrentStep = "Checkout";
                            break;
                        case "EstoreCheckout":
                            $scope.OrdersWithShipping = _.filter($scope.DataObject.Orders, function (x) { return x.IsShippingRequired === true; });

                            if ($scope.OrdersWithShipping !== undefined && $scope.OrdersWithShipping !== null && $scope.OrdersWithShipping.length > 0) {
                                //get contact details and check for the billing address
                                $scope.ShowMainScreen = false;
                                $scope.CurrentTab = "ContactDetails";
                                $scope.GetContactInfo();
                            }
                            else {
                                common.usSpinnerService.stop('spnpageslogin');
                                $scope.ShowMainScreen = false;
                                $scope.CurrentStep = "Checkout";
                            }
                            break;
                        case "EventCheckout":
                            //check event free tickets with member benefits
                            if ($scope.IsShippingAddressRequired === true) {
                                $scope.ShowMainScreen = false;
                                $scope.CurrentTab = "ContactDetails";
                                $scope.GetContactInfo();
                            }
                            else
                                $scope.ValidateEventAgain();
                            break;
                        case "JoinMembership":
                            $modalInstance.close("ContinueAsContact");
                            break;
                        case "MembershipCheckout":
                            common.usSpinnerService.stop('spnpageslogin');
                            $scope.CurrentStep = "Checkout";
                            break;
                        case "GroupMembershipLogin":
                            $modalInstance.close("ContinueAsMember");
                            break;
                        case "NewSignup":
                        case "ExistingLogin":
                            $scope.savedSuccessfully = true;
                            if (actionPerformed === "Signup") {
                                common.aaNotify.success("User has been registered successfully.");
                                $scope.message = "User has been registered successfully.";
                            }
                            common.$rootScope.$broadcast('RefreshCartCount');
                            $scope.ResponseData = { Value: "Close", ContactId: $scope.TempContactId };
                            $modalInstance.close($scope.ResponseData);
                            break;
                        default:
                            $scope.savedSuccessfully = true;
                            if (actionPerformed === "Signup") {
                                common.aaNotify.success("User has been registered successfully.");
                                $scope.message = "User has been registered successfully.";
                            }
                            window.location.reload(true);
                            //RedirectToHome();
                            break;
                    }
                }, function (error) {
                });
            }
            else {
                switch ($scope.FunctionType) {
                    case "DonationCheckout":
                        common.usSpinnerService.stop('spnpageslogin');
                        $scope.CurrentStep = "Checkout";
                        break;
                    case "EstoreCheckout":
                        $scope.OrdersWithShipping = _.filter($scope.DataObject.Orders, function (x) { return x.IsShippingRequired === true; });

                        if ($scope.OrdersWithShipping !== undefined && $scope.OrdersWithShipping !== null && $scope.OrdersWithShipping.length > 0) {
                            //get contact details and check for the billing address
                            $scope.ShowMainScreen = false;
                            $scope.CurrentTab = "ContactDetails";
                            $scope.GetContactInfo();
                        }
                        else {
                            common.usSpinnerService.stop('spnpageslogin');
                            $scope.ShowMainScreen = false;
                            $scope.CurrentStep = "Checkout";
                        }
                        break;
                    case "EventCheckout":
                        //check event free tickets with member benefits
                        if ($scope.IsShippingAddressRequired === true) {
                            $scope.ShowMainScreen = false;
                            $scope.CurrentTab = "ContactDetails";
                            $scope.GetContactInfo();
                        }
                        else
                            $scope.ValidateEventAgain();
                        break;
                    case "JoinMembership":
                        $modalInstance.close("ContinueAsContact");
                        break;
                    case "MembershipCheckout":
                        common.usSpinnerService.stop('spnpageslogin');
                        $scope.CurrentStep = "Checkout";
                        break;
                    case "GroupMembershipLogin":
                        $modalInstance.close("ContinueAsMember");
                        break;
                    case "NewSignup":
                    case "ExistingLogin":
                        $scope.savedSuccessfully = true;
                        if (actionPerformed === "Signup") {
                            common.aaNotify.success("User has been registered successfully.");
                            $scope.message = "User has been registered successfully.";
                        }
                        common.$rootScope.$broadcast('RefreshCartCount');
                        $scope.ResponseData = { Value: "Close", ContactId: $scope.TempContactId };
                        $modalInstance.close($scope.ResponseData);
                        break;
                    default:
                        $scope.savedSuccessfully = true;
                        if (actionPerformed === "Signup") {
                            common.aaNotify.success("User has been registered successfully.");
                            $scope.message = "User has been registered successfully.";
                        }
                        window.location.reload(true);
                        //RedirectToHome();
                        break;
                }
            }
        };

        $scope.ValidateEventAgain = function () {
            //validate event again after login to check whether is there any free ticket or not with the registration for member benefits
            common.usSpinnerService.spin('spnpageslogin');
            $scope.OriginalObject.CalculateSalesTax = true;

            if ($scope.IsAddressSelectedFromList === false && $scope.ShippingAddress !== undefined && $scope.ShippingAddress !== null) {
                $scope.OriginalObject.EstoreBatch.ShippingAddress = angular.copy($scope.ShippingAddress);
            }

            $scope.Checkout.ContactDetails.ShippingAddress = angular.copy($scope.OriginalObject.EstoreBatch.ShippingAddress);

            GuestCartSvc.validateRegistration($scope.OriginalObject).then(function (resValidation) {
                if (resValidation.data) {
                    if (resValidation.data.Message) {
                        if (resValidation.data.Message !== null && (resValidation.data.Message.Type === 'Error' || resValidation.data.Message.Type === '1')) {
                            if (resValidation.data.Message.Key === "NotavalidMembershipToRegisterEvent") {
                                common.usSpinnerService.stop('spnpageslogin');
                                $scope.CurrentStep = "Message";
                                $scope.ErrorMessage = resValidation.data.Message.Description;
                                common.usSpinnerService.stop('spnpageslogin');
                                return;
                            }
                        }
                    }
                    $scope.DataObject = resValidation.data;

                    //Need to replace attendees here. After login/signup event would be validated again so contact would get clear. So copying attendees from original object.
                    $scope.DataObject.Attendees = [];
                    angular.copy($scope.OriginalObject.Attendees, $scope.DataObject.Attendees);

                    $scope.CalculateEventCost();
                    if (resValidation.data.TotalFreeSeatsAsMembershipBenefit > 0) {
                        $scope.CheckEventFreeTickets(resValidation);
                    }
                    else {
                        //if no free tickets then move to next step.
                        if ($scope.IsRedirectionRequired === true) {
                            common.$rootScope.cartItemsForForm = resValidation.data;
                            $modalInstance.close();
                            common.$location.path('/RegisterAttendees/' + $scope.DataObject.EventId);
                        }
                        else if ($scope.NextStepToPerform === "Cart") {
                            $scope.ReturnObject =
                                {
                                    Action: "Cart",
                                    DataObject: resValidation.data
                                };
                            $modalInstance.close($scope.ReturnObject);
                        }
                        else {
                            common.usSpinnerService.stop('spnpageslogin');
                            $scope.ShowMainScreen = false;
                            $scope.SetCurrentTab("");
                            $scope.CurrentStep = "Checkout";
                        }
                    }
                }
            });
        };

        $scope.CheckEventFreeTickets = function (resValidation) {
            var templateUrl = "/App_Client/views/Pages/PublicPages/Event/" + $scope.TemplateName + "/_eventFulfillmentPopup.html?v=" + window.crm.constants.version;
            var modaleventFulfillmentPopupInstance1 = $modal.open({
                controller: "EventFulfillmentCTLR",
                templateUrl: templateUrl,
                keyboard: true,
                backdrop: 'static',
                scope: $scope,
                resolve: {
                    registrationCartItem: function () {
                        return resValidation.data;
                    },
                    IsAddtoCart: function () {
                        return false;
                    }
                }
            });
            modaleventFulfillmentPopupInstance1.result.then(function (result) {
                if (result.Operation === "Procceed" && result.NoOfTickets > 0) {
                    GuestCartSvc.proceedTemporaryFulfillment(resValidation.data, result.NoOfTickets).then(function (res) {
                        $scope.DataObject = res.data;
                        $scope.CurrentStep = "Checkout";
                        common.usSpinnerService.stop('spnpageslogin');
                    });
                }
                else {
                    //if no benefit avail
                    $scope.CurrentStep = "Checkout";
                    common.usSpinnerService.stop('spnpageslogin');
                }
            }, function () {
            });
        };
        //Event Logic ends

        $scope.FromTopforgotpassword = function () {
            RedirectToForgotPassword();
        };

        $scope.FromTopforgotUsername = function () {
            RedirectToForgotUsername();
        };

        $scope.GoToSignup = function () {
            $scope.message = '';
            $scope.CurrentStep = "Signup";
        };

        $scope.ProcessCheckout = function () {
            common.usSpinnerService.spin('spnpageslogin');
            if ($scope.TotalAmount() > 0) {
                common.$rootScope.$broadcast('getCCToken');
            }
            else {
                $scope.ProcceedToCheckout({ PaymentOption: { Key: "Free", Value: "Free" } });
            }

        };

        $scope.ProcceedToCheckout = function (PaymentOption) {

            //clear the cart before adding item to the cart so that it always consider a new cart.
            //PageCartSvc.ClearCartId();

            switch ($scope.FunctionType) {
                case "DonationCheckout":
                    $scope.DonationCheckout(PaymentOption);
                    break;
                case "EventCheckout":
                    $scope.EventCheckout(PaymentOption);
                    break;
                case "MembershipCheckout":
                    $scope.MembershipCheckout(PaymentOption);
                    break;
                case "EstoreCheckout":
                    $scope.EstoreCheckout(PaymentOption);
                    break;
                default:
                    break;
            }
        };

        $scope.DonationCheckout = function (PaymentOption) {
            common.usSpinnerService.spin('spnpageslogin');
            if (PaymentOption !== undefined && PaymentOption !== null) {
                if (PaymentOption.Key === "CardToken") {
                    $scope.Checkout.CheckoutDetails.CardInformation.CardToken = PaymentOption.Value;
                    $scope.Checkout.CheckoutDetails.CardInformation.Tokenize = PaymentOption.Tokenize;
                }
                else if (PaymentOption.Key === "CardOnFileId") {
                    $scope.Checkout.CheckoutDetails.CardInformation.CardOnFileId = PaymentOption.Value;
                }
                else if (PaymentOption.Key === "PayLater") {
                    $scope.Checkout.CheckoutDetails.PayLater = true;
                }

                //If there is double donation details then it will be stored in original object.
                if ($scope.OriginalObject !== undefined && $scope.OriginalObject !== null) {
                    //assignment should be done in case of donation only.
                    angular.copy($scope.OriginalObject, $scope.Checkout.DoubleTheDonationDetails);
                }

                //first add the donation to the cart and then process cart.
                GuestCartSvc.addDonationToCart($scope.DataObject).then(function (res) {
                    $scope.DataObject.gift = res.data;
                    $scope.Checkout.CartId = res.data.CartId;
                    //Process cart
                    $scope.ProcessCart();
                }, function (err) {
                    //common.aaNotify.error(err);
                    common.usSpinnerService.stop('spnpageslogin');
                });
            }
        };

        $scope.ApplyCouponCode = function () {
            common.usSpinnerService.spin('spnpageslogin');
            if (IsNotNullorEmpty($scope.CouponObject.CouponCode) && $scope.Checkout.ContactDetails !== null) {
                if ($scope.DisableProfile === false && authService.authentication.isAuth === true) {
                    $scope.CouponObject.ContactDetails.IndividualInfo = {};
                }
                else {
                    if ($scope.Checkout.IsOrganizationCheckout === true) {
                        //need to handle discount for organization.
                        if ($scope.Checkout.ContactDetails.IsOrgSelected === true && $scope.Checkout.ContactDetails.SelectedOrgText !== undefined
                            && $scope.Checkout.ContactDetails.SelectedOrgText !== null && $scope.Checkout.ContactDetails.SelectedOrgText.id > 0) {
                            $scope.CouponObject.ContactDetails.OrganizationInfo.Id = $scope.Checkout.ContactDetails.ContactId;
                        }
                        else {
                            $scope.CouponObject.ContactDetails.OrganizationInfo.ContactName = $scope.Checkout.ContactDetails.Name;
                            $scope.CouponObject.ContactDetails.OrganizationInfo.Email = $scope.Checkout.ContactDetails.Email;
                            if ($scope.Checkout.ContactDetails.MailingAddress !== undefined && $scope.Checkout.ContactDetails.MailingAddress !== null) {
                                $scope.CouponObject.ContactDetails.OrganizationInfo.AddressLine1 = $scope.Checkout.ContactDetails.MailingAddress.AddressLine1;
                                $scope.CouponObject.ContactDetails.OrganizationInfo.AddressLine2 = $scope.Checkout.ContactDetails.MailingAddress.AddressLine2;
                                $scope.CouponObject.ContactDetails.OrganizationInfo.AddressLine3 = $scope.Checkout.ContactDetails.MailingAddress.AddressLine3;
                                $scope.CouponObject.ContactDetails.OrganizationInfo.AddressLine4 = $scope.Checkout.ContactDetails.MailingAddress.AddressLine4;
                                $scope.CouponObject.ContactDetails.OrganizationInfo.Zip = $scope.Checkout.ContactDetails.MailingAddress.PostalCode;
                                $scope.CouponObject.ContactDetails.OrganizationInfo.City = $scope.Checkout.ContactDetails.MailingAddress.City;
                                $scope.CouponObject.ContactDetails.OrganizationInfo.County = $scope.Checkout.ContactDetails.MailingAddress.County;
                                $scope.CouponObject.ContactDetails.OrganizationInfo.Country = $scope.Checkout.ContactDetails.MailingAddress.Country;
                                $scope.CouponObject.ContactDetails.OrganizationInfo.State = $scope.Checkout.ContactDetails.MailingAddress.StateRegionProvince;
                            }
                        }
                    }
                    else {
                        if ($scope.Checkout.ContactDetails.FirstName !== undefined && $scope.Checkout.ContactDetails.FirstName !== null && $scope.Checkout.ContactDetails.FirstName !== ""
                            && $scope.Checkout.ContactDetails.LastName !== undefined && $scope.Checkout.ContactDetails.LastName !== null && $scope.Checkout.ContactDetails.LastName !== ""
                            && $scope.Checkout.ContactDetails.Email !== undefined && $scope.Checkout.ContactDetails.Email !== null && $scope.Checkout.ContactDetails.Email !== "") {

                            $scope.CouponObject.ContactDetails.IndividualInfo.ContactName = $scope.Checkout.ContactDetails.FirstName;
                            $scope.CouponObject.ContactDetails.IndividualInfo.LastName = $scope.Checkout.ContactDetails.LastName;
                            $scope.CouponObject.ContactDetails.IndividualInfo.Email = $scope.Checkout.ContactDetails.Email;

                            if ($scope.Checkout.ContactDetails.MailingAddress !== undefined && $scope.Checkout.ContactDetails.MailingAddress !== null &&
                                $scope.Checkout.ContactDetails.MailingAddress.AddressLine1 !== undefined && $scope.Checkout.ContactDetails.MailingAddress.AddressLine1 !== null && $scope.Checkout.ContactDetails.MailingAddress.AddressLine1 !== "") {
                                $scope.CouponObject.ContactDetails.IndividualInfo.AddressLine1 = $scope.Checkout.ContactDetails.MailingAddress.AddressLine1;
                                $scope.CouponObject.ContactDetails.IndividualInfo.AddressLine2 = $scope.Checkout.ContactDetails.MailingAddress.AddressLine2;
                                $scope.CouponObject.ContactDetails.IndividualInfo.AddressLine3 = $scope.Checkout.ContactDetails.MailingAddress.AddressLine3;
                                $scope.CouponObject.ContactDetails.IndividualInfo.AddressLine4 = $scope.Checkout.ContactDetails.MailingAddress.AddressLine4;
                                $scope.CouponObject.ContactDetails.IndividualInfo.Zip = $scope.Checkout.ContactDetails.MailingAddress.PostalCode;
                                $scope.CouponObject.ContactDetails.IndividualInfo.City = $scope.Checkout.ContactDetails.MailingAddress.City;
                                $scope.CouponObject.ContactDetails.IndividualInfo.County = $scope.Checkout.ContactDetails.MailingAddress.County;
                                $scope.CouponObject.ContactDetails.IndividualInfo.Country = $scope.Checkout.ContactDetails.MailingAddress.Country;
                                $scope.CouponObject.ContactDetails.IndividualInfo.State = $scope.Checkout.ContactDetails.MailingAddress.StateRegionProvince;
                            }
                        }
                    }
                }

                if ($scope.FunctionType === "EstoreCheckout") {
                    $scope.CouponObject.ItemCost = $scope.TotalAmount();
                    $scope.DiscountData = {
                        CouponCodeObject: {},
                        BatchOrder: {}
                    };

                    angular.copy($scope.CouponObject, $scope.DiscountData.CouponCodeObject);
                    angular.copy($scope.DataObject, $scope.DiscountData.BatchOrder);

                    GuestCartSvc.applyCouponCodeOnEstore($scope.DiscountData).then(function (res) {
                        if (res.data.Result.CouponCodeObject.CouponId > 0) {
                            $scope.CouponObject.CouponId = res.data.Result.CouponCodeObject.CouponId;
                            $scope.CouponObject.Discount = res.data.Result.CouponCodeObject.Discount;
                            angular.copy(res.data.Result.BatchOrder, $scope.DataObject);
                            $scope.CalculateSalesTax();
                        }
                        common.usSpinnerService.stop('spnpageslogin');
                    }, function (err) {
                        common.usSpinnerService.stop('spnpageslogin');
                    });
                }
                else {
                    if ($scope.FunctionType === "EventCheckout")
                        $scope.CouponObject.ItemCost = $scope.RegistrationCost;
                    else
                        $scope.CouponObject.ItemCost = $scope.TotalAmount();

                    GuestCartSvc.applyCouponCodeOnItem($scope.CouponObject).then(function (res) {
                        if (res.data.Message.Type === "Success" && res.data.CouponId > 0) {
                            $scope.CouponObject.CouponId = res.data.CouponId;
                            $scope.CouponObject.Discount = res.data.Discount;
                            $scope.TotalAmount();
                        }
                        else {
                            common.aaNotify.error(res.data.Message.Description);
                        }

                        if ($scope.DataObject.EstoreBatch !== undefined && $scope.DataObject.EstoreBatch !== null && $scope.DataObject.EstoreBatch.Orders !== undefined
                            && $scope.DataObject.EstoreBatch.Orders !== null && $scope.DataObject.EstoreBatch.Orders.length > 0) {

                            $scope.DiscountData = {
                                CouponCodeObject: {},
                                BatchOrder: {}
                            };

                            angular.copy($scope.CouponObject, $scope.DiscountData.CouponCodeObject);
                            angular.copy($scope.DataObject.EstoreBatch, $scope.DiscountData.BatchOrder);

                            GuestCartSvc.applyCouponCodeOnEstore($scope.DiscountData).then(function (res) {

                                if (res.data.ErrorText !== undefined && res.data.ErrorText !== null && res.data.ErrorText !== "") {
                                    $scope.TotalAmount();
                                    common.aaNotify.error(res.data.ErrorText);
                                }
                                else {
                                    if (res.data.Result.CouponCodeObject.CouponId > 0) {
                                        $scope.CouponObject.CouponId = res.data.Result.CouponCodeObject.CouponId;
                                        $scope.CouponObject.Discount = $scope.CouponObject.Discount + res.data.Result.CouponCodeObject.Discount;
                                        angular.copy(res.data.Result.BatchOrder, $scope.DataObject.EstoreBatch);
                                        $scope.CalculateSalesTaxWithEvent($scope.DataObject.EstoreBatch);
                                    }
                                }
                                common.usSpinnerService.stop('spnpageslogin');
                            }, function (err) {
                                common.usSpinnerService.stop('spnpageslogin');
                            });
                        }
                        common.usSpinnerService.stop('spnpageslogin');
                    }, function (err) {
                        common.usSpinnerService.stop('spnpageslogin');
                    });
                }
            }
        };

        $scope.RemoveCouponCode = function () {
            //reset coupon object.
            $scope.CouponObject = {
                CouponCode: "",
                ContactDetails: {
                    IndividualInfo: {}, OrganizationInfo: {}
                },
                Discount: 0,
                CouponId: 0
            };

            switch ($scope.FunctionType) {
                case "EventCheckout":
                    $scope.CouponObject.ItemId = $scope.DataObject.EventId;
                    $scope.CouponObject.ApplicableCategory = "Event";
                    if ($scope.DataObject.EstoreBatch !== undefined && $scope.DataObject.EstoreBatch !== null && $scope.DataObject.EstoreBatch.Orders !== undefined
                        && $scope.DataObject.EstoreBatch.Orders !== null && $scope.DataObject.EstoreBatch.Orders.length > 0) {
                        angular.forEach($scope.DataObject.EstoreBatch.Orders, function (product) {
                            product.Discount = 0;
                        });
                        $scope.CalculateSalesTaxWithEvent($scope.DataObject.EstoreBatch);
                    }
                    else
                        $scope.TotalAmount();
                    break;
                case "MembershipCheckout":
                    $scope.CouponObject.ApplicableCategory = "NewMembership";
                    $scope.CouponObject.ItemId = $scope.DataObject.Membership.MembershipLevel.MembershipLevelId;
                    $scope.TotalAmount();
                    break;
                case "EstoreCheckout":
                    angular.forEach($scope.DataObject.Orders, function (product) {
                        product.Discount = 0;
                    });
                    $scope.CalculateSalesTax();
                    $scope.TotalAmount();
                    break;
                default:
                    break;
            }
        };

        $scope.EventCheckout = function (PaymentOption) {
            common.usSpinnerService.spin('spnpageslogin');
            if (PaymentOption !== undefined && PaymentOption !== null) {
                if (PaymentOption.Key === "CardToken") {
                    $scope.Checkout.CheckoutDetails.CardInformation.CardToken = PaymentOption.Value;
                    $scope.Checkout.CheckoutDetails.CardInformation.Tokenize = PaymentOption.Tokenize;
                }
                else if (PaymentOption.Key === "CardOnFileId") {
                    $scope.Checkout.CheckoutDetails.CardInformation.CardOnFileId = PaymentOption.Value;
                }
                else if (PaymentOption.Key === "PayLater") {
                    $scope.Checkout.CheckoutDetails.PayLater = true;
                }

                //assign coupon code values to registration object so that it can save cart item with discount and it can be validated properly while checkout
                if ($scope.CouponObject.CouponId > 0 && $scope.CouponObject.Discount > 0) {
                    $scope.DataObject.CouponId = $scope.CouponObject.CouponId;
                    $scope.DataObject.Discount = $scope.CouponObject.Discount;
                }

                //first add the donation to the cart and then process cart.
                GuestCartSvc.addEventToCart($scope.DataObject).then(function (res) {
                    $scope.Checkout.CartId = res.data.CartId;
                    //Process cart
                    $scope.ProcessCart();
                }, function (err) {
                    //common.aaNotify.error(err);
                    common.usSpinnerService.stop('spnpageslogin');
                });
            }
        };

        $scope.MembershipCheckout = function (PaymentOption) {
            common.usSpinnerService.spin('spnpageslogin');
            if (PaymentOption !== undefined && PaymentOption !== null) {
                if (PaymentOption.Key === "CardToken") {
                    $scope.Checkout.CheckoutDetails.CardInformation.CardToken = PaymentOption.Value;
                    $scope.Checkout.CheckoutDetails.CardInformation.Tokenize = PaymentOption.Tokenize;
                }
                else if (PaymentOption.Key === "CardOnFileId") {
                    $scope.Checkout.CheckoutDetails.CardInformation.CardOnFileId = PaymentOption.Value;
                }
                else if (PaymentOption.Key === "PayLater") {
                    $scope.Checkout.CheckoutDetails.PayLater = true;
                }

                //assign coupon code values to registration object so that it can save cart item with discount and it can be validated properly while checkout
                if ($scope.CouponObject.CouponId > 0 && $scope.CouponObject.Discount > 0) {
                    $scope.DataObject.CouponId = $scope.CouponObject.CouponId;
                    $scope.DataObject.Discount = $scope.CouponObject.Discount;
                }

                //first add the membership to the cart and then process cart.
                if ($scope.DataObject.Membership.MembershipLevel.Type === "Organization") {
                    GuestCartSvc.addOrganizationMembershipToCart($scope.DataObject).then(function (res) {
                        if (res.data.CartId !== undefined) {
                            $scope.Checkout.CartId = res.data.CartId;
                            //Process cart
                            $scope.ProcessCart();
                        }
                    }, function (err) {
                        common.usSpinnerService.stop('spnMembershipDetail');
                    });
                }
                else {
                    GuestCartSvc.addIndividualMembershipToCart($scope.DataObject).then(function (res) {
                        if (res.data.CartId !== undefined) {
                            $scope.Checkout.CartId = res.data.CartId;
                            //Process cart
                            $scope.ProcessCart();
                        }
                    }, function (err) {
                        common.usSpinnerService.stop('spnMembershipDetail');
                    });
                }

            }
        };

        $scope.EstoreCheckout = function (PaymentOption) {
            common.usSpinnerService.spin('spnpageslogin');
            if (PaymentOption !== undefined && PaymentOption !== null) {
                if (PaymentOption.Key === "CardToken") {
                    $scope.Checkout.CheckoutDetails.CardInformation.CardToken = PaymentOption.Value;
                    $scope.Checkout.CheckoutDetails.CardInformation.Tokenize = PaymentOption.Tokenize;
                }
                else if (PaymentOption.Key === "CardOnFileId") {
                    $scope.Checkout.CheckoutDetails.CardInformation.CardOnFileId = PaymentOption.Value;
                }
                else if (PaymentOption.Key === "PayLater") {
                    $scope.Checkout.CheckoutDetails.PayLater = true;
                }

                //assign coupon code values to registration object so that it can save cart item with discount and it can be validated properly while checkout
                if ($scope.CouponObject.CouponId > 0 && $scope.CouponObject.Discount > 0) {
                    $scope.DataObject.CouponId = $scope.CouponObject.CouponId;
                    $scope.DataObject.Discount = $scope.CouponObject.Discount;
                }

                //first add the donation to the cart and then process cart.
                GuestCartSvc.addProductToCart($scope.DataObject).then(function (res) {
                    $scope.Checkout.CartId = res.data.CartId;
                    //Process cart
                    $scope.ProcessCart();
                }, function (err) {
                    //common.aaNotify.error(err);
                    common.usSpinnerService.stop('spnpageslogin');
                });
            }
        }

        $scope.ProcessCart = function () {
            if ($scope.DisableProfile === true) {
                if ($scope.Checkout.ContactDetails.KeepDetailsSaved === true) {
                    $scope.GuestContactDetails = {};
                    angular.copy($scope.Checkout.ContactDetails, $scope.GuestContactDetails);
                    $scope.GuestContactDetails.CheckoutAs = $scope.Checkout.IsOrganizationCheckout === true ? "O" : "I";
                    PageCartSvc.SetGuestContact($scope.GuestContactDetails);
                }
                else {
                    PageCartSvc.ClearGuestContact();
                }
            }

            if ($scope.CouponObject.CouponId > 0 && $scope.CouponObject.Discount > 0) {
                $scope.Checkout.CheckoutDetails.CouponCode = $scope.CouponObject.CouponCode;
            }

            if ($scope.Checkout.ContactDetails.ShippingAddress !== undefined && $scope.Checkout.ContactDetails.ShippingAddress !== null && $scope.Checkout.ContactDetails.ShippingAddress.AddressId > 0) {
                $scope.Checkout.ContactDetails.ShippingAddress.Id = $scope.Checkout.ContactDetails.ShippingAddress.AddressId;
            }

            GuestCartSvc.checkOut($scope.Checkout).then(function (checkoutRes) {
                publiccardService.validateCardInfo(checkoutRes).then((authResponse) => {
                    switch (authResponse.status) {
                        case window.crm.constants.cardAuthenticationProps.cardApproved:
                            $scope.Checkout.CheckoutDetails.CardInformation.PaymentIntentId = authResponse.paymentIntent.id;
                            $scope.ProcessCart();
                            break;
                        case window.crm.constants.cardAuthenticationProps.cardRejected:
                            common.aaNotify.error(authResponse.description, { showClose: true, iconClass: 'icon-close', ttl: 16000 });
                            $scope.Checkout.CheckoutDetails.CardInformation.PaymentIntentId = null;
                            common.usSpinnerService.stop('spnpageslogin');
                            break;
                        default:
                            common.usSpinnerService.stop('spnpageslogin');
                            $scope.ShowMessageList(checkoutRes.data);
                    }
                }, function (err) {
                    common.aaNotify.error(err);
                    common.usSpinnerService.stop('spnpageslogin');
                });

            }, function (err) {
                common.aaNotify.error(err.data.Message);
                common.usSpinnerService.stop('spnpageslogin');
            });
        };

        $scope.ShowMessageList = function (response) {
            $scope.ErrorMessageList = [];
            if (response.Message.Type === 'Error' || response.Message.Type === '1') {
                $scope.ErrorMessageList.push(response.Message);
                common.aaNotify.error(response.Message.Description);
            }
            else {
                window.location.href = window.crm.constants.baseurl + '/fundraising/#/Thankyou';
            }
        };

        $scope.ContinueAsGuestContact = function () {
            switch ($scope.FunctionType) {
                case "DonationCheckout":
                    $scope.SetCurrentTab("");
                    $scope.CurrentStep = "Checkout";
                    break;
                case "EventCheckout":
                    if ($scope.DisableProfile === false && $scope.DataObject.EstoreBatch !== undefined && $scope.DataObject.EstoreBatch !== null
                        && $scope.DataObject.EstoreBatch.Orders !== undefined && $scope.DataObject.EstoreBatch.Orders !== null
                        && $scope.DataObject.EstoreBatch.Orders.length > 0) {
                        $scope.CalculateSalesTaxWithEvent($scope.DataObject.EstoreBatch);
                    }
                    else {
                        $scope.SetCurrentTab("");
                        $scope.CurrentStep = "Checkout";
                    }
                    break;
                case "EstoreCheckout":
                    $scope.CalculateSalesTax();
                    break;
                case "JoinMembership":
                    //Save values in Temporary storage.
                    $scope.GuestContactDetails = {};
                    angular.copy($scope.Checkout.ContactDetails, $scope.GuestContactDetails);
                    $scope.GuestContactDetails.CheckoutAs = $scope.Checkout.IsOrganizationCheckout === true ? "O" : "I";
                    PageCartSvc.SetGuestContact($scope.GuestContactDetails);
                    $modalInstance.close("ContinueAsGuestContact");
                    break;
                case "MembershipCheckout":
                    $scope.SetCurrentTab("");
                    $scope.CurrentStep = "Checkout";
                    break;
                default:
                    break;
            }
        };

        $scope.CalculateSalesTax = function () {
            common.usSpinnerService.spin('spnpageslogin');
            $scope.RequestData = {
                ContactDetails: {}
            };

            if ($scope.IsAddressSelectedFromList === false && $scope.ShippingAddress !== undefined && $scope.ShippingAddress !== null) {
                $scope.Checkout.ContactDetails.ShippingAddress = angular.copy($scope.ShippingAddress);
            }

            angular.copy($scope.Checkout.ContactDetails, $scope.RequestData.ContactDetails);

            GuestCartSvc.validateMemberContact($scope.RequestData).then(function (validatedResponse) {
                angular.forEach($scope.DataObject.Orders, function (order) {
                    var originaProduct = _.find($scope.OriginalObject, function (d) { return d.ProductId === order.ProductId });
                    if (validatedResponse.data.IsValidMember === true)
                        order.Amount = originaProduct.MemberAmount;
                    else
                        order.Amount = originaProduct.Amount;
                    order.UnitPrice = order.Amount;

                });

                if ($scope.Checkout.ContactDetails.ShippingAddress !== undefined && $scope.Checkout.ContactDetails.ShippingAddress !== null) {
                    $scope.DataObject.ShippingAddress = $scope.Checkout.ContactDetails.ShippingAddress;
                }
                eStorePageSvc.calculateSalesTax($scope.DataObject).then(function (res) {
                    $scope.DataObject.Orders = [];
                    angular.copy(res.data.Result.Orders, $scope.DataObject.Orders);
                    $scope.CalculateProductCost();
                    common.usSpinnerService.stop('spnpageslogin');
                    $scope.SetCurrentTab("");
                    $scope.CurrentStep = "Checkout";
                }, function (error) {
                });

            }, function (err) {
                common.aaNotify.error(err.data.Message);
                common.usSpinnerService.stop('spnEventDetail');
            });
        }

        $scope.CalculateSalesTaxWithEvent = function (batchObject) {
            common.usSpinnerService.spin('spnpageslogin');
            if ($scope.IsAddressSelectedFromList === false && $scope.ShippingAddress !== undefined && $scope.ShippingAddress !== null) {
                $scope.DataObject.EstoreBatch.ShippingAddress = angular.copy($scope.ShippingAddress);
            }
            $scope.Checkout.ContactDetails.ShippingAddress = angular.copy($scope.DataObject.EstoreBatch.ShippingAddress);
            eStorePageSvc.calculateSalesTax(batchObject).then(function (res) {
                angular.copy(res.data.Result.Orders, $scope.DataObject.EstoreBatch.Orders);
                common.usSpinnerService.stop('spnpageslogin');
                $scope.CalculateEventCost();
                $scope.SetCurrentTab("");
                $scope.CurrentStep = "Checkout";
            }, function (error) {
            });
        }

        $scope.TotalAmount = function () {
            if ($scope.DataObject !== undefined && $scope.DataObject !== null) {
                switch ($scope.FunctionType) {
                    case "DonationCheckout":
                        return $scope.DataObject.NetAmount;
                    case "EventCheckout":
                    case "EstoreCheckout":
                        return $scope.DataObject.Cost - $scope.CouponObject.Discount;
                    case "MembershipCheckout":
                        return $scope.DataObject.Membership.Cost - $scope.CouponObject.Discount;
                    default:
                        break;
                }
            }
            else
                return 0;
        };

        $scope.CalculateEventCost = function () {

            $scope.ProductCost = 0;
            $scope.ShippingCost = 0;
            $scope.SalesTax = 0;
            $scope.RegistrationCost = 0;
            $scope.OtherItemTotal = 0;
            $scope.EstoreItemTotal = 0;

            $scope.RegistrationCost = _.chain($scope.DataObject.RegistrationAttendees).filter(function (x) { return x.NoOfSeats > 0; }).reduce(function (m, x) {
                if (x.Availability === "MemberOnly") {
                    return m + (x.MemberRegistrationCost * Number(isNaN(x.NoOfSeats) ? 0 : x.NoOfSeats - (isNaN(x.NoOfFreeSeatsAsMembershipBenefit) ? 0 : x.NoOfFreeSeatsAsMembershipBenefit)));
                }
                else {
                    return m + (x.AttendeeAmount * Number(isNaN(x.NoOfSeats) ? 0 : x.NoOfSeats - (isNaN(x.NoOfFreeSeatsAsMembershipBenefit) ? 0 : x.NoOfFreeSeatsAsMembershipBenefit)));
                }
            }, 0).value();

            $scope.OtherItemTotal = _.chain($scope.DataObject.OtherItemPurchases).filter(function (x) { return x.Qty > 0 }).reduce(function (m, x) { return m + Number(isNaN(x.Cost) ? 0 : x.Cost); }, 0).value();

            if ($scope.DataObject.EstoreBatch !== undefined && $scope.DataObject.EstoreBatch !== null && $scope.DataObject.EstoreBatch.Orders !== undefined
                && $scope.DataObject.EstoreBatch.Orders !== null && $scope.DataObject.EstoreBatch.Orders.length > 0) {
                $scope.EstoreItemTotal = _.chain($scope.DataObject.EstoreBatch.Orders).filter(function (x) { return x.Quantity > 0 }).reduce(function (m, x) {
                    x.ProductCost = $scope.ProductCost + (x.UnitPrice * x.Quantity);

                    $scope.ProductCost = $scope.ProductCost + (x.UnitPrice * x.Quantity);
                    $scope.ShippingCost = $scope.ShippingCost + (x.ShippingCost !== undefined && x.ShippingCost !== null && x.ShippingCost > 0 ? x.ShippingCost : 0);
                    $scope.SalesTax = $scope.SalesTax + (x.SalesTax !== undefined && x.SalesTax !== null && x.SalesTax > 0 ? x.SalesTax : 0);


                    return m + (x.Amount * Number(isNaN(x.Quantity) ? 0 : x.Quantity)) + x.ShippingCost + (x.SalesTax !== undefined && x.SalesTax !== null ? x.SalesTax : 0);
                }, 0).value();
            }

            $scope.DataObject.Cost = $scope.RegistrationCost + $scope.OtherItemTotal + $scope.EstoreItemTotal;
        };

        $scope.CalculateProductCost = function () {
            $scope.ProductCost = 0;
            $scope.ShippingCost = 0;
            $scope.SalesTax = 0;
            angular.forEach($scope.DataObject.Orders, function (product) {
                $scope.ProductCost = $scope.ProductCost + (product.UnitPrice * product.Quantity);
                $scope.ShippingCost = $scope.ShippingCost + (product.ShippingCost !== undefined && product.ShippingCost !== null && product.ShippingCost > 0 ? product.ShippingCost : 0);
                $scope.SalesTax = $scope.SalesTax + (product.SalesTax !== undefined && product.SalesTax !== null && product.SalesTax > 0 ? product.SalesTax : 0);
                var ItemWithShippingRequired = _.find($scope.DataObject.Orders, function (c) { return c.IsShippingRequired === true });
                $scope.IsShippingAddressRequired = ItemWithShippingRequired !== undefined && ItemWithShippingRequired !== null && IsNotNullorEmpty(ItemWithShippingRequired);
            });

            $scope.DataObject.Cost = $scope.ProductCost + $scope.ShippingCost + $scope.SalesTax;
        };

        $scope.SetCurrentTab = function (value) {
            $scope.CurrentTab = value;
            $scope.ShowMainScreen = false;
        }

        $scope.ShowMainPg = function () {
            $scope.ShowMainScreen = true;
            $scope.CurrentTab = '';
        }

        $scope.BackToLogin = function () {
            $scope.message = '';
            $scope.CurrentStep = "Login";
        }

        $scope.GetContactInfo = function () {
            common.usSpinnerService.spin('spnpageslogin');
            ContactProfileSvc.getContactAddresses().then(function (res) {
                if (res.data !== undefined && res.data !== null && res.data.length > 0) {
                    $scope.ContactShippingAddresses = res.data;
                    if ($scope.ContactShippingAddresses !== undefined && $scope.ContactShippingAddresses !== null && $scope.ContactShippingAddresses.length > 0) {
                        angular.forEach($scope.ContactShippingAddresses, function (address) {
                            address.FullAddress = FormatAddress(address);
                        });
                    }
                }
                $scope.ShippingAddress =
                    {
                        AddressLine1: "",
                        AddressLine2: "",
                        SelectedCity: "",
                        StateRegionProvince: "",
                        PostalCode: "",
                        Country: window.crm.constants.defaultCountry
                    };
                $scope.ShippingAddress.AddressType = "Billing";

                common.usSpinnerService.stop('spnpageslogin');
            }, function (err) {
                common.usSpinnerService.stop('spnpageslogin');
            });
        };

        $scope.SelectShippingAddress = function (address) {

            $scope.IsAddressSelectedFromList = true;

            angular.forEach($scope.ContactShippingAddresses, function (address) {
                address.selected = false;
            });

            if ($scope.FunctionType === "EstoreCheckout") {
                $scope.Checkout.ContactDetails.ShippingAddress = angular.copy(address);
                $scope.Checkout.ContactDetails.ShippingAddress.AddressType = "Billing";
            }
            else if (FunctionType === "EventCheckout") {
                $scope.OriginalObject.EstoreBatch.ShippingAddress = angular.copy(address);
                $scope.OriginalObject.EstoreBatch.ShippingAddress.AddressType = "Billing";
            }

            address.selected = true;

            $scope.ShippingAddress =
                {
                    AddressLine1: "",
                    AddressLine2: "",
                    SelectedCity: "",
                    StateRegionProvince: "",
                    PostalCode: "",
                    Country: window.crm.constants.defaultCountry
                };
            $scope.ShippingAddress.AddressType = "Billing";
        };

        $scope.$watch('ShippingAddress', function (newObj) {
            if ($scope.ContactShippingAddresses.length > 0) {
                if (newObj !== undefined && newObj !== null
                    && (newObj.AddressLine1 !== "" || newObj.AddressLine2 !== "" || newObj.SelectedCity !== "" || newObj.StateRegionProvince !== "" || newObj.PostalCode !== "")) {

                    $scope.IsAddressSelectedFromList = false;

                    if (!$scope.IsAddressSelectedFromList) {
                        angular.forEach($scope.ContactShippingAddresses, function (address) {
                            address.selected = false;
                        });
                        //assuming new address
                        $scope.ShippingAddress.AddressId = 0;
                    }
                }
            }
        }, true);

        $scope.InitLoginSignupPopup();

    }]);;
app.controller('DonationFeePopupCtrl', ["$scope", "common", "$location", "$modalInstance", "ExtraFee", "AskArrayDonation",
    function ($scope, common, $location, $modalInstance, ExtraFee, AskArrayDonation) {
        $scope.InitActionCtrl = function () {
            $scope.ExtraFee = ExtraFee;
            $scope.AskArrayDonation = AskArrayDonation;

            $scope.FeeAmount = (parseFloat($scope.AskArrayDonation.Amount) * 100 / (100 - parseFloat($scope.ExtraFee))) - parseFloat($scope.AskArrayDonation.Amount);
            $scope.FeeAmount = parseFloat($scope.FeeAmount);
        };
        $scope.Revert = function () {
            $modalInstance.close({ Operation: "Revert" });
        };
        $scope.Proceed = function () {
            $modalInstance.close({ Operation: "Proceed" });
        };
        $scope.InitActionCtrl();        
    }]);;
var app = angular.module('app');

app.controller('ProductDetailCtrl', ['$scope', 'common', 'ProductDetails', '$modalInstance',
    function ($scope, common, ProductDetails, $modalInstance) {

        $scope.client = window.crm.constants.client;
        $scope.TemplateName = getResolveValue(common, 'TemplateName');

        $scope.PayLaterOn = window.crm.list.clientPageModuleSetting.PayLaterOn;
        $scope.PayLaterLabel = window.crm.list.clientPageModuleSetting.PayLaterLabel;
        $scope.DisableCart = window.crm.constants.DisableCart === "True" ? true : false;
        $scope.DisableProfile = window.crm.constants.DisableProfile === "True" ? true : false;

        $scope.ProductDetail = {};
        $scope.DataObject =
            {
                ContactId: 0,
                InvoiceId: 0,
                Orders: []
            };

        $scope.InitProductDetail = function () {
            if (ProductDetails !== undefined && ProductDetails !== null) {
                $scope.ProductDetail = ProductDetails;
            }
        };

        $scope.CloseProductDetails = function () {
            $modalInstance.close("Close");
        }

        $scope.InitProductDetail();

    }]);;
