var Analytics = {
    logEvent: function (eventCategory, eventAction, eventLabel) {
        ga('send', 'event', eventCategory, eventAction, eventLabel);
    }
}
jQuery(window).load(function() { gigya = Gigya.init(); });

function updateCounter(increasingCounter, qtyForUpdating) {
  var increasingCounter = typeof(increasingCounter) !== "undefined" ? increasingCounter : true;
  var qtyForUpdating = qtyForUpdating || 1;
  var basketCounter = document.getElementsByClassName('nav-basket-count')[0];
  var basketCounterContainer = document.getElementById('nav-basket-count-container');

  if (basketCounter) {
    var basketCounterContent = parseInt(basketCounter.innerText);
    var newValue = increasingCounter ? basketCounterContent + qtyForUpdating : basketCounterContent - qtyForUpdating;

    if (newValue > 0 ) {
    basketCounter.innerText = (newValue < 10) ? "0" + newValue : newValue;
    } else {
      basketCounter.innerText = "0"
    }

    if (newValue === 0) {
      $(basketCounterContainer).addClass("basketList-empty");
      $(basketCounterContainer).unwrap();
    } else {
      $(basketCounterContainer).removeClass("basketList-empty");
      $(basketCounterContainer).wrap("<a href='/basket-list' class='BHG-link'></a> ");
    }
  }
}

/*
 * ************************************************************
 * Copyright (C) John Lilley All rights reserved.
 *
 * File Details
 * Creator:         John Lilley
 * Type:            Script (.js)
 * Filename:        gigya.less
 * Description:
 *
 * Versioning Details
 * Version No.      1.0
 * Version History
 *
 * ************************************************************
*/

var isAuthenticated = false;

var GigyaRatingsTemplate = 	'<div class="gig-rating-stars"></div>' +
														'<p class="u-inlineBlock">' +
															'<span id="spanReviewsLink" class="gig-rating-readReviewsLink" onClick="var productTitlea = $(\'#ProductDetail\').attr(\'data-title\');Analytics.logEvent(\'Review\',\'Click Review Count\',productTitlea)"></span>' +
															' | ' +
															'<span class="btn btn-link btn-link--orange gig-rating-writeYourReview" onClick="var productTitlea = $(\'#ProductDetail\').attr(\'data-title\');Analytics.logEvent(\'Review\',\'Click Write Review\',productTitlea)">Add review</span>' +
														'</p>';

var GigyaAvgRatingTemplate = 	'<div class="gig-rating-stars"></div>';

var GigyaTemplate = {
  commentsPlugin: '<div class="gig-comments-composebox"></div>' +
						'<div class=gig-comments-header></div>' +
            '<div class="gig-comments-comments"></div>',

  comment:  '<div class="commentBlock row">' +
             '<div class="commentBlock-generalInfo col-xs-3">' +
               '<span class="gig-comment-username"></span><br />' +
							 '<span class="gig-comment-title"></span>' +
               '<span class="gig-comment-time"></span>' +
             '</div>' +
						 '<div class="commentBlock-body col-xs-9">' +
						 	'<span class="gig-comment-flag"></span>' +
             	'<div class="gig-comment-body"></div>' +
						 '</div>' +
           '</div>' +
           '<div class=gig-comment-replybox ></div>' +
           '<div class=gig-comment-replies></div>',
  composebox: '<div id="composeBox" class="composeBox">' +
                '<div class="gig-composebox-close"></div>' +
                '<div class="composeBox-header">' +
                  '<div class="gig-composebox-authorBox">' +
                    '<div class="gig-composebox-title"></div>' +
                    '<div class="gig-composebox-logout"><i class="fa fa-times" aria-hidden="true"></i></div>' +
                  '</div>' +
                '</div>' +
                '<div class="gig-composebox-ratings"></div>' +
                '<div class="clearfix"></div>' +
                '<div class="gig-composebox-editor"></div>' +
                '<div class="gig-composebox-postContainer">' +
                  '<div class="gig-composebox-postBox">' +
                    '<div class="gig-composebox-post" onClick="var productTitlea = $(\'#ProductDetail\').attr(\'data-title\');Analytics.logEvent(\'Review\',\'Submit Review\',productTitlea)">Post</div>' +
                  '</div>' +
                '</div>' +
                '<div class="clearfix"></div>' +
              '</div>'
};


var Gigya = {
    vars: {
        // Global Variables
        scriptHost: (document.location.protocol == "https:" ? "https://cdns.gigya.com" : "http://cdn.gigya.com")
        , scriptUrl: '/js/socialize.js?apiKey='
				// , scriptAPI: '3_cnsp6Puhb0GvGxcUJ9KG7P70Rfgqx3SGTRRVru-SGPZZ_Oeod2pqneCmB7V_ol5k' // Update with your API Key
				, scriptAPI: window.gigyaApiKey
        , scriptExtras: ''
        //, providers: 'facebook,linkedin,instagram,googleplus'
        , rassScreenSetRegistration: 'BHGShop-Default-RegistrationLogin'
        , rassMobileScreenSetRegistration: 'BHGShop-DefaultMobile-RegistrationLogin'
        , rassScreenSetProfile: 'BHGShop-Default-ProfileUpdate'
        , userExtraProfileFields: 'languages, address, phones, education, honors, publications, patents, certifications, professionalHeadline, bio, industry, specialties, work, skills, religion, politicalView, interestedIn, relationshipStatus, hometown, favorites, likes, followersCount, followingCount, username, locale, verified, irank, timezone'
        , accountExtraProfileFields: 'identities-active, loginIDs, emails, profile, data, regSource, irank'
        , rassScreenCheckoutRegistration: 'BHGShop-Checkout-RegistrationLogin'
        , rassMobileCheckoutRegistration: 'BHGShop-CheckoutMobile-RegistrationLogin'
        , rassScreenGuestVersionRegistration: 'BHGShop-GuestVersion-RegistrationLogin'
        , rassScreenGuestVersionRegistrationMobile: 'BHGShop-GuestVersion-RegistrationLogin-Mobile'
    },
    init: function () {
        // Initialization Function
        Gigya.loadJS();

    },
    loadJS: function () {
        // Load Gigya JS

        // Global Configuration
        // Doc: http://developers.gigya.com/display/GD/Global%20Conf%20(JS)
        var scriptParams = {
            enabledProviders: Gigya.vars.providers
            //, cid: '% ADD NAME %' // Context ID - For Reporting
            //, actionCounterPath: '/' // Signals
            //, sessionExpiration: -2 // Session Expiry
            //, lang: 'ja' // Locale -- Need to add &lang=ja-jp to API call
        }
        window.__gigyaConf = scriptParams;

        // Add Gigya JS to HEAD
        var s = document.createElement('script');
        s.type = 'text/javascript';
        s.async = true;
        s.src = Gigya.vars.scriptHost + Gigya.vars.scriptUrl + Gigya.vars.scriptAPI + Gigya.vars.scriptExtras;
        s.onload = function () {
            Gigya.pageLoad();
        };
        document.head.appendChild(s);
    },
    pageLoad: function () {
        Gigya.eventHandlers();
        Gigya.raasLogin();
        Gigya.raasRegister();
        Gigya.socialLogin();
        Gigya.raasLogout();
        Gigya.raasUpdateProfile();
        Gigya.engagementShare();
        Gigya.engagementRatingsReviews();

        // Build Authentication
        Gigya.authenticationBuild();
        Gigya.addConnections();
        Gigya.identityObj();
        // Get userInfo
        //gigya.socialize.getUserInfo({ callback: renderUI });

        var checkoutPage = $("#Checkout-paymentMade");
        if (checkoutPage) {
            var userIsAuthenticated = $(checkoutPage).attr("data-userIsAuthenticated");
            if (userIsAuthenticated == "False") {
		          gigya.accounts.showScreenSet({
		            screenSet: Gigya.vars.rassScreenGuestVersionRegistration,
		            mobileScreenSet: Gigya.vars.rassScreenGuestVersionRegistrationMobile,
								context: { nextUrl: null },
		            startScreen: 'gigya-register-screen'
		          });
            }
        }
    },
    eventHandlers: function () {
        // Handle RaaS Events
        // General Doc: http://developers.gigya.com/010_Developer_Guide/84_Using_the_Client_API/50_Events
        gigya.accounts.addEventHandlers({
            onLogin: Gigya.onLoginEvent,
            onLogout: Gigya.onLogoutEvent
        });

        // register for connect status changes
        //gigya.socialize.addEventHandlers({ onConnectionAdded: renderUI, onConnectionRemoved: renderUI });
    },
    onLoginEvent: function (response) {
        // Function (Event) which executed when user logs in.
        Gigya.authenticationBuild();
        /**** Lets do some SERVER-SIDE Stuff!! ****/
        var eventLabel = 'Sign-in by Email';
        var eventAction = 'Submit Sign-in';
        if (response.provider == 'facebook') {
            eventLabel = 'Sign-in by Facebook';
            eventAction = 'Click Sign-in';
        } else if (response.provider == 'googleplus') {
            eventLabel = 'Sign-in by Google';
            eventAction = 'Click Sign-in';
        }
        Analytics.logEvent('Sign-in', eventAction, eventLabel);

        // Get the Users UID, Signature and Timestamp (IMPORTANT - need this to validate Server-Side).
        var userUID = response.UID;
        var userEmail = response.profile.email;
        var userDisplayName = response.profile.firstName + " " + response.profile.lastName;
        var userFirstName = response.profile.firstName;
        var userLastName = response.profile.lastName;
        var nextUrl = response.context.nextUrl;

        var fetchToken = {
            uid: userUID,
            email: userEmail,
            displayName: userDisplayName,
            firstName: userFirstName,
            lastName: userLastName
        };
        // AJAX Call
        $.ajax({
            type: "POST",
            url: "/GigyaLogin/LoginRegisterMember/",
            data: JSON.stringify(fetchToken),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response) {
                var username = response.Name;
                $(".userProfile-welcome").text("Welcome " + username + "!");
                $("#userButtons-desktop").addClass("hidden");
								$(".btn-wishlist").removeClass("hide");
                $(".userProfile-desktop").removeClass("hidden");
                $(".usernameContainer").html(username);
                $(".userButtons").addClass("hidden");
                $(".userButtons-login").removeClass("hidden");
                $("#wishList-btn").removeClass("btn-disabled preventDefault");
								$("#wishList-btn").wrap('<a href="/wish-list" class="BHG-link"></a>')
                $('#btnRaasLogin-profile').after('<a href="/memberprofile" id="account-link" class="BHG-link">My Account</a>');
                $('#btnRaasLogin-profile').remove();
                $('#btnRaasLogin-wishList').after('<a href="/wish-list" class="BHG-link" id="wishList-link">Wishlist</a>');
                $('#btnRaasLogin-wishList').remove();
                if(nextUrl) {
                    window.location.href= nextUrl;
                }
            },
            failure: function (response) {
                NOTIFICATION_CENTER.addNotification({message: "Error", status: "error"});
            }
        });
    },
    onLogoutEvent: function () {
        // Function (Event) executed when a user logs out.
        Gigya.authenticationBuild();
    },
    renderUI: function (response) {
        if (response.user != null && response.user.isConnected) {
            $("gigya-user-name").Text = "Welcome - " + response.user.nickname;
           // document.getElementById("name").innerHTML = response.user.nickname;
            if (res.user.thumbnailURL.length > 0)
                document.getElementById("photo").src = response.user.thumbnailURL;
            else
                document.getElementById("photo").src
                            = "http://cdn.gigya.com/site/images/bsAPI/Placeholder.gif";
            document.getElementById("profile").style.display = "block";
        } else {
            document.getElementById("profile").style.display = "none";}
    },
    raasLogin: function () {
        // User Login
				$(document).on('click', '[id^="btnRaasLogin-"]', function(e) {
            // Gigya 'accounts.showScreenSet' API method.
            // General Doc: http://developers.gigya.com/010_Developer_Guide/10_UM360/040_Raas
            // Working Code Example: http://developers.gigya.com/040_Demos/010_Social_Identity_Management/020_RaaS/010_Hosted_on_Gigya
            // API Method: http://developers.gigya.com/020_Client_API/020_Accounts/accounts.setAccountInfo
            gigya.accounts.showScreenSet({
                screenSet: Gigya.vars.rassScreenSetRegistration,
                mobileScreenSet: Gigya.vars.rassMobileScreenSetRegistration,
                context: {nextUrl: $(e.target).attr('redirectValue')}
            });
        });
    },
    raasRegister: function () {
        // User Registration
				$(document).on('click', '[id^="btnRaasRegister-"]', function (e) {
            // Gigya 'accounts.showScreenSet' API method.
            gigya.accounts.showScreenSet({
                screenSet: Gigya.vars.rassScreenSetRegistration,
                mobileScreenSet: Gigya.vars.rassMobileScreenSetRegistration,
								context: { nextUrl: null },
                startScreen: 'gigya-register-screen' });
        });
    },
    raasUpdateProfile: function () {
        // User Update Profile
				$(document).on('click', '[id^="btnRaasUpdateProfile-"]', function(e) {
            // Gigya 'accounts.showScreenSet' API method.
            gigya.accounts.showScreenSet({
                screenSet: Gigya.vars.rassScreenSetProfile,
                onAfterSubmit: Gigya.getIdentityObjCallback
            });
        });
    },
    getIdentityObjCallback: function (response) {
        var params = {
            extraFields: Gigya.vars.userExtraProfileFields
            , callback: Gigya.identityObjCallback
        }

        gigya.accounts.getAccountInfo(params);

        var userUID = response.UID;
        var userSignature = response.UIDSignature;
        var userSignatureTimestamp = response.signatureTimestamp;
        var userEmail = response.profile.email;
        var userDisplayName = response.profile.firstName + " " + response.profile.lastName;
        var userFirstName = response.profile.firstName;
        var userLastName = response.profile.lastName;
        var userBirthYear = response.profile.birthYear;
        var userAge = response.profile.age;
        var userStreetAddress = response.profile.streetAddress;
        var userState = response.profile.state;
        var userPostCode = response.profile.zip;
        var userCountry = response.profile.country;

        var fetchToken = {
            uid: userUID,
            signature: userSignature,
            timestamp: userSignatureTimestamp,
            email: userEmail,
            displayName: userDisplayName,
            firstName: userFirstName,
            lastName: userLastName,
            birthYear: userBirthYear,
            age: userAge,
            streetAddress: userStreetAddress,
            state: userState,
            postCode: userPostCode,
            country: userCountry
        };
        // AJAX Call
        /*$.ajax({
            type: "POST",
            url: "/MembershipManagement/UpdateUser/",
            data: JSON.stringify(fetchToken),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response) {
                console.log(response);
            },
            failure: function (response) {
                console.log(response);
            }
        });*/
    },
    raasLogout: function () {
        // User Logout
        $("body").on("click", '[id^="btnRaasLogout-"]', function(e) {
						$(".userProfile-desktop-welcome").popover("hide");
            // API Method: http://developers.gigya.com/020_Client_API/020_Accounts/accounts.logout
            gigya.accounts.logout({
                callback: function (response) {
                    if (response.errorCode == 0) {
                        // Logout Successful
                        $.ajax({
                            type: "GET",
                            url: "/GigyaLogin/LogoutUser/",
                            success: function (response) {
                                $("#wishList-btn").addClass("btn-disabled preventDefault");
																$(".btn-wishlist").addClass("hide");
																$(".userProfile-welcome").text("Welcome!");
																$("#wishList-btn").unwrap();
                                $("#userButtons-desktop").removeClass("hidden");
                                $(".userButtons").removeClass("hidden");
                                $(".userButtons-login").addClass("hidden");
                                $(".userProfile-desktop").addClass("hidden");
                                $("#account-link").after('<button class="btn btn-profileLink" id="btnRaasLogin-profile">My Account</button>');
                                $("#account-link").remove();
                                $("#wishList-link").after('<button class="btn btn-profileLink" id="btnRaasLogin-wishList">Wishlist</button>');
                                $("#wishList-link").remove();
                                if((window.location.href.indexOf("memberprofile") >-1) || (window.location.href.indexOf("wish-list") > -1)) {
                                    window.location.href = "/";
                                }
                            },
                            failure: function (response) {
                                console.log(response);
                            }
                        });
                    }
                    else {
                        // Logout Unsuccessful
                        NOTIFICATION_CENTER.addNotification({message: "Error", status: "error"});
                    }
                }
            });
        });
    },
    socialLogin: function () {
        // User Login
        $('#btnSocialLogin').click(function (e) {
            // Gigya 'socialize.showLoginUI' API method.
            // General Doc: http://developers.gigya.com/display/GD/socialize.showLoginUI+JS
            // Working Code Example: http://developers.gigya.com/display/GD/Basic+Social+Login+Demo
            params = {
                version: 1
                    , buttonsStyle: "fullLogoColored"
                //, width: 380
                //, height: 200
                    , showTermsLink: false
                    , hideGigyaLink: false
            };
            gigya.socialize.showLoginUI(params);
        });
    },
    authenticationBuild: function () {
        // Function used to determine whether user is currently authenticated?
        gigya.socialize.getUserInfo({
            callback: function (response) {
                if (response.user.UID) {
                    // User is Authenticated (if user has a UID)
                    isAuthenticated = true;
                    Gigya.authenticatedView(response)


                } else {
                    // User Is Unauthenticated
                    isAuthenticated = false;
                    Gigya.unAuthenticatedView()

                }
            }
        });
    },
    authenticatedView: function (response) {
        // Used to Build an Authneticated Experience
        $('.unauthenticated').hide();
        $('.authenticated').show();

        // Build User Details in DOM
        // Nickname
        $profileName = $("#profileName");
        if (response.user.nickname) {
            $profileName.html(response.user.nickname);
        } else {
            $profileName.html(response.user.firstName);
        }

        // Avatar
        if (response.user.thumbnailURL) {
            $profileAvatar = $("#profileAvatar");
            $profileAvatar.attr("src", response.user.thumbnailURL);
            $profileAvatar.attr("alt", response.user.nickname);
        }

        $("#profileBtn").attr("title", response.user.nickname);

        Gigya.act = new gigya.socialize.UserAction();
        Gigya.act.setTitle("Testing sharing!!!");
        Gigya.act.setLinkBack("localhost:51473");
        Gigya.act.addMediaItem({ type: 'image', src: 'http://demo.gigya.com/images/recipe2.png', href: 'http://demo.gigya.com/recipe2.php' });

        var showShareBarUI_params =
        {
            containerID: 'componentDiv',
            shareButtons: 'Facebook-Like,Twitter-Tweet,googleplus-share,Share',
            userAction: Gigya.act
        };

        gigya.socialize.showShareBarUI(showShareBarUI_params);

    },
    unAuthenticatedView: function () {
        // Used to Build an Unauthneticated Experience
        $('.authenticated').hide();
        $('.unauthenticated').show();
    },
    identityObj: function () {

        $("#btnUserObject").on("click", function () {

            var params = {
                extraFields: Gigya.vars.userExtraProfileFields
            , callback: Gigya.identityObjCallback
            }

            gigya.socialize.getUserInfo(params);
        });

    },
    identityObjCallback: function (response) {
        var userObj = JSON.stringify(response, null, 4);
        $("#preUserObject").html(Gigya.prettyJson(userObj));
    },
    prettyJson: function (json) {
        json = json.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
        return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
            var cls = 'number';
            if (/^"/.test(match)) {
                if (/:$/.test(match)) {
                    cls = 'key';
                } else {
                    cls = 'string';
                }
            } else if (/true|false/.test(match)) {
                cls = 'boolean';
            } else if (/null/.test(match)) {
                cls = 'null';
            }
            return '<span class="' + cls + '">' + match + '</span>';
        });
    },
    addConnections: function () {

        params = {
            containerID: "connections"
            , width: 260
            , height: 100
            , showTermsLink: true
            , hideGigyaLink: true
            , showEditLink: true
        }

        params['onConnectionAdded'] = function (evt) {
            Gigya.onConnection(evt, conID);
        };

        // Initialize Connections
        gigya.socialize.showAddConnectionsUI(params);


    },
    onConnection: function (e, conID) {
        // Alert the user
        alert("You have been connected to your " + e.provider + " account.");
    },
    engagementShare: function () {
        // Gigya Engagement Plugin - Ratings and Reviews

        // Gigya 'gigya.comments.showRatingUI' & gigya.comments.showCommentsUI API methods.
        // General Doc/Setup: http://developers.gigya.com/display/GD/socialize.showShareUI%20JS
        // Working Code Example: http://developers.gigya.com/display/GD/Share%20Plugin%20Demo


        $('#btnShare').click(function (e) {
            // Constructing a UserAction Object
            var userAct = new gigya.socialize.UserAction();
            userAct.setTitle("Title");  // Setting the Title
            userAct.setDescription("Description");   // Setting Description
            //userAct.setLinkBack("");  // Setting the Link Back
            //userAct.addActionLink();  // Adding Action Link
            // Adding a Media (image)
            userAct.addMediaItem({ type: 'image', src: 'http://www.gigya.com/wp-content/uploads/2011/11/Share-Plugins-400.png', href: $("#shareLink").val() });

            var params =
            {
                userAction:userAct
                //, onError: this.sendError
                //, onSendDone: this.sendDone
                , showMoreButton: true // Enable the "More" button and screen
                , showEmailButton: true // Enable the "Email" button and screen
            };
            // API: http://developers.gigya.com/display/GD/socialize.showShareUI+JS
            gigya.socialize.showShareUI(params);
        });


    },
		engagementRatingsReviews: function () {
			// Gigya Engagement Plugin - Share

			var productDetailPage = $("#ProductDetail");
			if (productDetailPage.length > 0) {
				var productSku = $(productDetailPage).attr("data-info");

				var initialState = window.__INITIAL_STATE__ || {};
				if (!initialState.productDetail.isAuthenticated) {
					$("#btnRaasLogout-Desktop").click();
				}

				var ratingsParams = {
				  categoryID: 'product-reviews',
				  streamID: 'product-' + productSku,
					useHiResIcons: true,
					ratingTemplate: GigyaRatingsTemplate,
				  containerID: 'ratingDiv', // <div> ID  in which to present the plugin
				  linkedCommentsUI: 'commentsDiv' // link the Ratings plugin to the Comments plugin.
				};
				gigya.comments.showRatingUI(ratingsParams);

				// Present the Comments plugin
				var commentsParams = {
				  categoryID: 'product-reviews',
				  streamID: 'product-' + productSku,
				  containerID: 'commentsDiv',
				  version: 2,
					showLoginBar: true,
					templates: GigyaTemplate,
	      	cid:'',
	      	enabledShareProviders: 'facebook, googleplus',
					moreEnabledProviders: 'facebook, googleplus',
					useSiteLogin: true,
					hideShareButtons: true,
					onSiteLoginClicked: function() {
						// Use site modal login
						gigya.accounts.showScreenSet({
			        screenSet: Gigya.vars.rassScreenSetRegistration,
			        mobileScreenSet: Gigya.vars.rassMobileScreenSetRegistration,
							context: { nextUrl: null },
			        startScreen: 'gigya-login-screen'
			      });
					},
					onCommentSubmitted: function() {
						// Update average rating when new rating has been added
						gigya.comments.showRatingUI(ratingsParams);
					}
				};
				gigya.comments.showCommentsUI(commentsParams);
			}

			$(".avgRating").each(function() {
				var productSku = $(this).attr("data-sku");
				var avgRatingParams = {
					categoryID: 'product-reviews',
					streamID: 'product-' + productSku,
					useHiResIcons: true,
					ratingTemplate: GigyaAvgRatingTemplate,
					containerID: 'avgRating_' + productSku // <div> ID  in which to present the plugin
				}
				gigya.comments.showRatingUI(avgRatingParams);
			});

		}
	};

