﻿
function KickAppsLoginProvider() {

    this.loginParamsForLoginPopUp = {
        showTermsLink: 'false',
        hideGigyaLink: 'true',
        height: 40,
        width: 200,
        containerID: 'social_signin_login',
        lastLoginIndication: 'none',
        context: { str: 'LoginOverlay', thisScope: this },
        pendingRegistration: true
    };

    this.loginParamsForRegisterPopUp = {
        showTermsLink: 'false',
        hideGigyaLink: 'true',
        height: 50,
        width: 450,
        containerID: 'social_signin_register',
        lastLoginIndication: 'none',
        buttonsStyle: 'fullLogo',
        showWhatsThis: true,
        context: { str: 'RegistrationOverlay', thisScope: this },
        enabledProviders: "facebook, twitter, yahoo, google, linkedin, messenger, aol, orkut, foursquare, blogger",
        disabledProviders: "renren, vkontakte",
        pendingRegistration: true
    };

    this.conf = "";
    this.servicePath = '/development/kickappsservice.svc/';
    this.gigyaUser = "";
    this.hwUser = "";
    this.profileId = 0;
    this.isHWRegisterButtonClicked = false;
    this.isGigyaRegisterButtonClicked = false;

}

KickAppsLoginProvider.prototype.Init = function (conf) {
    this.conf = {
        APIKey: conf,
        connectWithoutLoginBehavior: 'loginExistingUser',
        sessionExpiration: 0
    };
    gigya.services.socialize.addEventHandlers(this.conf, {
        onLogin: this.onLoginHandler
    });
    this.renderSocialHeader();
}

KickAppsLoginProvider.prototype.onLoginHandler = function (eventObj) {
    var thisScope = eventObj.context.thisScope;
    thisScope.gigyaUser = eventObj.user;
    thisScope.lookupDatabase(eventObj.user, thisScope, eventObj.context.str); // look up database for user status and perform action
}


KickAppsLoginProvider.prototype.lookupDatabase = function (user, thisScope, context) {
    var userdata = '{' +
                    '"UID":"' + encodeURIComponent(user.UID) + '",' +
                    '"UIDSignature":"' + encodeURIComponent(user.UIDSignature) + '",' +
                    '"signatureTimestamp":' + user.signatureTimestamp + ',' +
                    '}';

    $.ajax({
        type: "POST",
        url: "/development/kickappsservice.svc/logingigyauserforkickapps",
        data: userdata,
        dataType: "json",
        contentType: 'application/json; charset=utf-8',
        success: function (data) {
            switch (data.status) {
                case 0:
                    // successful login - registration required
                    thisScope.registerNewGigyaUser(user, thisScope, context);
                    break;
                case 2:
                    // successful login - no registration required
                    if ($("#loginOverlayTemplate").is(':visible')) {
						$("#loginOverlayTemplate").dialog("close");
					}
					if ($("#registrationWithLinkOverlayTemplate").is(':visible')) {
						$("#registrationWithLinkOverlayTemplate").dialog("close");
					}
                    window.location = 'http://hanleywood.kickapps.net/' + 'u=' + data.KickAppsUserId + '&as=' + data.KickAppsSiteId + '&st=' + data.KickAppsSessionToken + '&tid=' + data.KickAppsTransactionId ;
                    break;
                case 1:
                case 4:
                default:
                    alert('Error logging in.  Please try again.');
                    break;
            }
        },
        error: function () {
            alert('Error logging in.  Please try again.');
        }
    });

}


KickAppsLoginProvider.prototype.registerNewGigyaUser = function (user, thisScope, context) {

    if (context == 'LoginOverlay' || context == 'RegistrationOverlay') // user has logged in gigya from a login overlay or from lhd page
    {
        //alert('0');
        // close login modal
        if (context == 'LoginOverlay') {
            $("#loginOverlayTemplate").dialog("close");
        }

        thisScope.isGigyaRegisterButtonClicked = true;
        $("#registrationWithLinkOverlayTemplate .leftColumn fieldset.PASSWORD").hide();
        //          if (thisScope.gigyaUser.thumbnailURL.length > 0) {
        //            //$("#registerOverlayHeader2").hide();
        //            $("#registrationWithLinkOverlayTemplate .lhd_user").show();
        //            $("#registrationWithLinkOverlayTemplate .lhd_user").html('<img src=' + thisScope.gigyaUser.thumbnailURL + ' height=50 class="LHD_login_image"/><h3>Welcome ' + thisScope.gigyaUser.firstName + '.<br/>Please confirm your information and complete any missing fields.</h3>');
        //            //$("#LHD_USER_CONFIRM_INFO").show();
        //        }
        //        else {
        //            //$("#registerOverlayHeader2").hide();
        //            $("#registrationWithLinkOverlayTemplate .lhd_user").show();
        //            $("#registrationWithLinkOverlayTemplate .lhd_user").html('<img src="http://cdn.gigya.com/site/images/bsAPI/Placeholder.gif" height=50 class="LHD_login_image"/><h3>Welcome ' + thisScope.gigyaUser.firstName + '.<br/>Please confirm your information and complete any missing fields.</h3>');
        //            //$("#LHD_USER_CONFIRM_INFO").show();
        //        }
        //        if (user.loginProvider.length > 0) {
        //            $("#registerOverlayPara1").text("Please link my existing Builder account with " + user.loginProvider + " for quick, secure access.");
        //            $("#registerOverlayPara2").text("I would like to create a new account with my " + user.loginProvider + " profile information");
        //        }

        if (context == 'LoginOverlay') {

            thisScope.loadStatesAndCountries();
            // display registration modal
            $("#registrationWithLinkOverlayTemplate").dialog({ width: 745, modal: true, opacity: .9, open: function (event, ui) { window.setTimeout(function () { jQuery(document).unbind('mousedown.dialog-overlay').unbind('mouseup.dialog-overlay'); }, 100); }, close: function (ev, ui) { ClearAllFields($(this).attr("id")); thisScope.isGigyaRegisterButtonClicked = false; } });
            $("div.ui-dialog").css("z-index", "1000004");
            $("div.ui-widget-overlay").css("z-index", "1000003");
            $("#registrationWithLinkOverlayTemplate ").css("z-index", "1000006");
            $("#loginOverlayTemplate").css("z-index", "1000008");
            // field focus and blur handlers
            thisScope.RegistrationFocusEvents(thisScope, true);
        }
        // pre-populate form
        thisScope.PrepopulateRegistrationForm(user);

        // register new gigya user handler
        $("#registrationWithLinkOverlayTemplate input[name=submit_user_registration]").unbind('click').click(function (event) {
            if (thisScope.isGigyaRegisterButtonClicked) {
                thisScope.registerGigyaUser(thisScope);
            }
        });

    }
}


KickAppsLoginProvider.prototype.registerGigyaUser = function (thisScope) {

    var regFormPath = "#registrationWithLinkOverlayTemplate .LHD_Registration";

    var userNameInput = $(regFormPath + " input[name=user_name]");
    var profileImageInput = $(regFormPath + " input[name=profileimage]");
    var validUserName = thisScope.validateUserName(userNameInput.attr("value"));
    var validProfileImage = thisScope.validateProfileImage(profileImageInput.val());

    var errorText = '';

    if (thisScope.ValidateRegistrationForm(thisScope) || !validUserName || !validProfileImage) {
        // failure, so show errors
        if (!validUserName) {
            userNameInput.addClass("failed");
            if (errorText.length > 0)
                errorText = errorText + "<br/>";
            errorText = errorText + "User Name must be of 3 characters or more.";
        }
        else {
            userNameInput.removeClass("failed");
        }

        if (!validProfileImage) {
            profileImageInput.addClass("failed");
            if (errorText.length > 0)
                errorText = errorText + "<br/>";
            errorText = errorText + "Your profile photo must be in JPEG, PNG, or GIF format";
        }
        else {
            profileImageInput.removeClass("failed");
        }

        if (thisScope.ValidateRegistrationForm(thisScope)) {
            if (errorText.length > 0)
                errorText = errorText + "<br/>";
            errorText = errorText + "Please correct the highlighted fields.";
        }
        $(regFormPath + " div.error").css("display", "block");
        $(regFormPath + " div.error").html(errorText);
        return;
    } else {
        // success, so remove error messenging
        $(regFormPath + " div.error").html("");
        $(regFormPath + " div.error").css("display", "none");
        $(regFormPath + " input").removeClass("failed");
        $(regFormPath + " select").removeClass("failed");

    }

    var userdata = '{' +
					'"UID":"' + encodeURIComponent(thisScope.gigyaUser.UID) + '",' +
					'"UIDSignature":"' + encodeURIComponent(thisScope.gigyaUser.UIDSignature) + '",' +
					'"signatureTimestamp":"' + thisScope.gigyaUser.signatureTimestamp + '",' +
					'"loginProvider":"' + thisScope.gigyaUser.loginProvider + '",' +
                    '"firstname":"' + encodeURIComponent($(regFormPath + " input[name=firstname]").attr("value")) + '",' +
                    '"lastname":"' + encodeURIComponent($(regFormPath + " input[name=lastname]").attr("value")) + '",' +
					'"email":"' + $(regFormPath + " input[name=user_email_address]").attr("value") + '",' +
    				'"address":"' + encodeURIComponent($(regFormPath + " input[name=address]").attr("value")) + '",' +
					'"city":"' + encodeURIComponent($(regFormPath + " input[name=city]").attr("value")) + '",' +
					'"zip":"' + $(regFormPath + " input[name=zip]").attr("value") + '",' +
                    '"StateProvinceCode":"' + $(regFormPath + " select[name=state]").val() + '",' +
                    '"StateProvince":"' + $(regFormPath + " select[name=state] :selected").text() + '",' +
                    '"CountryCode":"' + $(regFormPath + " select[name=country]").val() + '",' +
                    '"Country":"' + $(regFormPath + " select[name=country] :selected").text() + '",' +
					'"BusinessName":"' + $(regFormPath + " input[name=businessname]").attr("value") + '",' +
                    '"PrimaryBusinessCode":"' + $(regFormPath + " select[name=primary_business]").val() + '",' +
                    '"PrimaryBusiness":' + thisScope.GetDemographicItemText(regFormPath, "primary_business", "primary_business_desc", true) + ',' +
					'"Accreditations":' + thisScope.GetDemographicItemTextForOthers(regFormPath, "accreditations") + ',' +
                    '"WorkStatus":' + thisScope.GetDemographicItemTextForOthers(regFormPath, "workstatus") + ',' +
					'"username":"' + $(regFormPath + " input[name=user_name]").attr("value") + '",' +
					'"dateofbirth":"' + $(regFormPath + " input[name=dateofbirth]").attr("value") + '",' +
					'"AIANumber":' + thisScope.GetOptionalText(regFormPath, "aianumber", "AIA Number") + ',' +
    '}';

    $.ajax({
        type: "POST",
        url: "/development/kickappsservice.svc/registergigyauserforkickApps",
        data: userdata,
        dataType: "json",
        contentType: 'application/json; charset=utf-8',
        success: function (data) {
            switch (data.status) {
                case 5:
                    var profileImage = $("#profileimage").val();
                    if (profileImage != "") {
                        thisScope.ajaxFileUpload(data.username, data.profileId);
                    } else {
                        $(regFormPath + " div.error").html("A confirmation e-mail will be sent to the e-mail address.");
                    }
                    break;
                case 7:
                    $(regFormPath + " div.error").html("Error notifying gigya.");
                    $(regFormPath + " div.error").css("display", "block");
                case 6:
                    $(regFormPath + " div.error").html("Email/Username already in use. Please enter a different email/username.");
                    $(regFormPath + " div.error").css("display", "block");
                    break;
                case 11:
                    $(regFormPath + " div.error").html("Error registering with Kickapps.");
                    $(regFormPath + " div.error").css("display", "block");
                    break;
                case 12:
                    $(regFormPath + " div.error").html("Error registering with hanleywood.");
                    $(regFormPath + " div.error").css("display", "block");
                    break;
                case 4:
                default:
                    $(regFormPath + " div.error").html("Error registering.  Please try again.");
                    $(regFormPath + " div.error").css("display", "block");
                    break;
            }
        },
        error: function () {
            $(regFormPath + " div.error").html("Error registering.  Please try again.");
            $(regFormPath + " div.error").css("display", "block");
        }
    });

}

KickAppsLoginProvider.prototype.PrepopulateRegistrationForm = function (user) {
    var regFormPath = "#registrationWithLinkOverlayTemplate .LHD_Registration";
    if (user.nickname.length > 0) {
        $(regFormPath + " input[name=user_name]").attr("value", user.nickname);
    }

    // prepopulate email address
    if (user.email.length > 0) {
        $(regFormPath + " input[name=user_email_address]").attr("value", user.email);
    } else {
        // set to default
        $(regFormPath + " input[name=user_email_address]").attr("value", "E-mail address");
        $(regFormPath + " input[name=user_email_address]").blur();
    }

    // prepoulate first name
    if (user.firstName.length > 0) {
        $(regFormPath + " input[name=firstname]").attr("value", user.firstName);
    }

    // prepoulate last name
    if (user.lastName.length > 0) {
        $(regFormPath + " input[name=lastname]").attr("value", user.lastName);
    }

    // prepoulate city
    if (user.city.length > 0) {
        $(regFormPath + " input[name=city]").attr("value", user.city);
    }

    // prepoulate zip code
    if (user.zip.length > 0) {
        $(regFormPath + " input[name=zip]").attr("value", user.zip);
    }

    if (user.birthDay.length > 0 && user.birthMonth.length && user.birthYear.length) {
        $(regFormPath + " input[name=dateofbirth]").attr("value", user.birthYear + "-" + user.birthMonth + "-" + user.birthDay);
    }
}

KickAppsLoginProvider.prototype.getLoginState = function () {
    //alert('2');
    var loginCookie = $.cookie('KickAppsUser');
    //alert('3' + loginCookie);
    if (!(loginCookie == null || loginCookie == "")) {
        return this.states.LOGGEDIN;
    }
    else {
        return this.states.LOGGEDOUT;
    }
}

KickAppsLoginProvider.prototype.renderSocialHeader = function () {
    //alert('1');
    var userState = this.getLoginState();

    switch (userState) {
        case this.states.LOGGEDOUT:
            // var thisScope = eventObj.context.thisScope;
            // alert('3');
            $("#welcome_message").html('<a href="#" id="kickapps_login_link">Login</a> | <a href="#" id="kickapps_signup_link">New Users (login to upload projects)</a>');
            this.addLoginLinkListener(this);
            this.addSignUpLinkListener(this);
            break;
        case this.states.LOGGEDIN:
            var cookieObj = this.deparam($.cookie('KickAppsUser'));
            if (cookieObj.user == 'GigyaLoggedInUser') {
                var displayName = cookieObj.userNickname.replace(/\+/g, " "); // nickname.length > maxChar ? nickname.substring(0, nickname.indexOf(' ')).length > maxChar ? nickname.substring(0, maxChar) : nickname.substring(0, nickname.indexOf(' ')) : nickname
                if (cookieObj.userThumbnailURL.length > 0) {
                    var welcomeHtml = '<img src=' + cookieObj.userThumbnailURL + ' height=25 class="LHD_login_image"/><p>Hi, ' + displayName + '</p><p><a id="gigyaLogout" href="#">Logout</a></p>';
                } else {
                    var welcomeHtml = '<img src="http://cdn.gigya.com/site/images/bsAPI/Placeholder.gif" height=25 class="LHD_login_image"/><p>Hi, ' + displayName + '</p><p><a id="gigyaLogout" href="#">Logout</a></p>';
                }
                $("#welcome_message").html(welcomeHtml);
                this.addGigyaLogoutListener(this);
            }
            else if (cookieObj.user == 'HWLoggedInUser') {
                if (cookieObj.userFirstName != null && cookieObj.userLastName != null) {
                    var fullName = cookieObj.userFirstName.replace(/\+/g, " ") + ' ' + cookieObj.userLastName.replace(/\+/g, " ");
                    $("#welcome_message").html('<p> Hi, ' + fullName + '</p><p><a id="hwLogout" href="#">Logout</a></p>');
                }
                else if (cookieObj.userFirstName != null) {
                    $("#welcome_message").html('<p> Hi, ' + cookieObj.userFirstName.replace(/\+/g, " ") + '</p><p><a id="hwLogout" href="#">Logout</a></p>');
                }
                else if (cookieObj.userLastName != null) {
                    $("#welcome_message").html('<p> Hi, ' + cookieObj.userLastName.replace(/\+/g, " ") + '</p><p><a id="hwLogout" href="#">Logout</a></p>');
                }
                else {
                    $("#welcome_message").html('<p><a id="hwLogout" href="#">Logout</a></p>');
                }
                this.addHWLogoutListener(this);
            }
            break;
        default:
            break;
    }
}

KickAppsLoginProvider.prototype.addLoginLinkListener = function (thisScope) {
    $("#kickapps_login_link").click(function (event) {
        event.preventDefault();
        $("#loginOverlayTemplate").dialog({ width: 790, modal: true, opacity: .9, open: function (event, ui) { window.setTimeout(function () { jQuery(document).unbind('mousedown.dialog-overlay').unbind('mouseup.dialog-overlay'); }, 100); }, close: function (ev, ui) { thisScope.clearAllFields($(this).attr("id"), thisScope); } });
        $("div.ui-dialog").css("z-index", "1000004");
        $("div.ui-widget-overlay").css("z-index", "1000003");
        $("#registrationWithLinkOverlayTemplate ").css("z-index", "1000006");
        gigya.services.socialize.showLoginUI(thisScope.conf, thisScope.loginParamsForLoginPopUp);
        // In case of Login button click, chk the credentials and log in user and identify him - done
        thisScope.addHWLoginButtonListener(thisScope);
    });
}

KickAppsLoginProvider.prototype.addHWLoginButtonListener = function (thisScope) {
    $(".button.LOGIN").unbind('click').click(function (event) {
        var userEmailAddressInput = $("#loginOverlayTemplate input[name=user_email_address]");
        var userEmailAddress = userEmailAddressInput.attr("value");
        var userPasswordInput = $("#loginOverlayTemplate input[name=user_password]");
        var userPassword = userPasswordInput.attr("value");
        var errorDiv = $("#loginOverlayTemplate div.error");


        if (!thisScope.validateEmail(userEmailAddress)) {
            // invalid email address format
            userEmailAddressInput.addClass("failed");
            errorDiv.html("Invalid email address. Please re-enter.");
            errorDiv.css("display", "block");
            return;
        }

        if (!thisScope.validatePassword(userPassword)) {
            // invalid password format
            userPasswordInput.addClass("failed");
            errorDiv.html("Invalid password.  Please enter 6 or more characters.");
            errorDiv.css("display", "block");
            return;
        }

        // remove error highlights and messages
        userEmailAddressInput.removeClass("failed");
        userPasswordInput.removeClass("failed");
        errorDiv.html("");
        errorDiv.css("display", "none");

        // email address and password format checkout, so try to login the user
        thisScope.loginHWUser(thisScope, userEmailAddress, userPassword, userEmailAddressInput, userPasswordInput);
    });
}


KickAppsLoginProvider.prototype.loginHWUser = function (thisScope, email, password, emailTxtInput, pwTxtInput) {

    var errorDiv = $("#loginOverlayTemplate div.error");
    var userdata = '{' +
				'"email":"' + email + '",' +
				'"Password":"' + password + '"' +
				'}';

    $.ajax({
        type: "POST",
        url: "/development/kickappsservice.svc/loginhwuserforkickapps",
        data: userdata,
        dataType: "json",
        contentType: 'application/json; charset=utf-8',
        success: function (data) {
			//alert(data.status)
            switch (data.status) {
				
                case 2:
					 if ($("#loginOverlayTemplate").is(':visible')) {
						$("#loginOverlayTemplate").dialog("close");
					}
					if ($("#registrationWithLinkOverlayTemplate").is(':visible')) {
						$("#registrationWithLinkOverlayTemplate").dialog("close");
					}
                    window.location = 'http://hanleywood.kickapps.net/' + 'u=' + data.KickAppsUserId + '&as=' + data.KickAppsSiteId + '&st=' + data.KickAppsSessionToken + '&tid=' + data.KickAppsTransactionId ;
                    break;
				case 11:
					errorDiv.html("Error notifying Kickapps.");
					errorDiv.css("display", "block");
					break;
                case 7:
                    errorDiv.html("Error notifying gigya.");
                    errorDiv.css("display", "block");
					break;
                case 3:
                    // user not found
                    emailTxtInput.addClass("failed");
                    pwTxtInput.addClass("failed");
                    errorDiv.html("Email address and password not found.<br/>Please register or login using  your social media account.");
                    errorDiv.css("display", "block");
                    break;
                case 4:
                default:
                    // error logging in
                    emailTxtInput.addClass("failed");
                    pwTxtInput.addClass("failed");
                    errorDiv.html("Error logging in. Please try again.");
                    errorDiv.css("display", "block");
                    break;
            }
        },
        error: function () {
            // error logging in
            emailTxtInput.addClass("failed");
            pwTxtInput.addClass("failed");
            errorDiv.html("Error loggin in. Please try again.");
            errorDiv.css("display", "block");
        }
    });
}

KickAppsLoginProvider.prototype.addSignUpLinkListener = function (thisScope) {
    $("#kickapps_signup_link").click(function (event) {
        event.preventDefault();
        thisScope.addSignUpListener(thisScope);
    });

}

KickAppsLoginProvider.prototype.addSignUpListener = function (thisScope) {

    thisScope.isHWRegisterButtonClicked = true;
    // show and hide registration fields with corresponding texts
    // $("#registerOverlayHeader1").text("Register a new account with us!");
    //$("#registerOverlayHeader2").hide();
    // $("#registerOverlayPara2").text("Please complete your subscriber information below.");
    //$("#registrationWithLinkOverlayTemplate .centerColumn").hide();
    //$("#registrationWithLinkOverlayTemplate .rightColumn").hide();
    //$("#registrationWithLinkOverlayTemplate .lhd_user").hide();
    //$("#LHD_USER_CONFIRM_INFO").hide();
    $("#registrationWithLinkOverlayTemplate .leftColumn").show();
    // $("#registrationWithLinkOverlayTemplate .leftColumn .LHD_link_create_options").hide();
    // $("#registrationWithLinkOverlayTemplate .LHD_logo").show();


    thisScope.loadStatesAndCountries();

    $("#registrationWithLinkOverlayTemplate").dialog({ width: 470, modal: true, opacity: .9, open: function (event, ui) { window.setTimeout(function () { jQuery(document).unbind('mousedown.dialog-overlay').unbind('mouseup.dialog-overlay'); }, 100); }, close: function (ev, ui) { thisScope.clearAllFields($(this).attr("id"), thisScope); thisScope.isHWRegisterButtonClicked = false; } });
    $("div.ui-dialog").css("z-index", "1000004");
    $("div.ui-widget-overlay").css("z-index", "1000003");
    $("#registrationWithLinkOverlayTemplate ").css("z-index", "1000006");
    $("#loginOverlayTemplate").css("z-index", "1000008");
    gigya.services.socialize.showLoginUI(thisScope.conf, thisScope.loginParamsForRegisterPopUp);
    $("#registrationWithLinkOverlayTemplate .LHD_Registration  select[name=primary_business]").change(function () {
        var val = $(this).find("option:selected").val();
        if (val == '01') {
            $("#aianumber").removeAttr("disabled");
        } else {
            $("#aianumber").attr("disabled", "true");
        }
    });
    thisScope.RegistrationFocusEvents(thisScope, false);
    thisScope.addRegisterButtonListener(thisScope);
}


KickAppsLoginProvider.prototype.addRegisterButtonListener = function (thisScope) {
    //alert('addregister');
    $("#registrationWithLinkOverlayTemplate .LHD_logo").show();
    $("#registrationWithLinkOverlayTemplate .leftColumn").show();
    $("#registrationWithLinkOverlayTemplate .leftColumn div.LHD_reg_login").removeClass("LHD_account_link");
    $("#registrationWithLinkOverlayTemplate .leftColumn fieldset.EMAIL_ADDRESS label").show();
    $("#registrationWithLinkOverlayTemplate .leftColumn fieldset.EMAIL_ADDRESS span").show();
    $("#registrationWithLinkOverlayTemplate .leftColumn fieldset.PASSWORD").show();
    $("#registrationWithLinkOverlayTemplate .leftColumn .LHD_link_create_options").hide();
    $("#regWithLinkOverlayDiv").removeClass("accountLink");

    $("#registrationWithLinkOverlayTemplate input[name=submit_user_registration]").unbind('click').click(function (event) {
        if (thisScope.isHWRegisterButtonClicked) {
            thisScope.registerHWUser(thisScope);
        }
    });
}

KickAppsLoginProvider.prototype.registerHWUser = function (thisScope) {

    var regFormPath = "#registrationWithLinkOverlayTemplate .LHD_Registration";

    var passwordInput = $(regFormPath + " input[name=user_password]");
    var confirmPasswordInput = $(regFormPath + " input[name=confirm_user_password]");
    var userNameInput = $(regFormPath + " input[name=user_name]");
    var profileImageInput = $(regFormPath + " input[name=profileimage]");

    var validPassword = thisScope.validateNewUserPassword(thisScope, passwordInput.attr("value"), confirmPasswordInput.attr("value"));
    var validUserName = thisScope.validateUserName(userNameInput.attr("value"));
    var validProfileImage = thisScope.validateProfileImage(profileImageInput.val());

    var errorText = '';

    if (thisScope.ValidateRegistrationForm(thisScope) || !validPassword || !validUserName || !validProfileImage) {
        // failure, so show errors
        if (!validUserName) {
            userNameInput.addClass("failed");
            if (errorText.length > 0)
                errorText = errorText + "<br/>";
            errorText = errorText + "User Name must be of 3 characters or more.";
        }
        else {
            userNameInput.removeClass("failed");
        }

        if (!validPassword) {
            passwordInput.addClass("failed");
            confirmPasswordInput.addClass("failed");
            if (errorText.length > 0)
                errorText = errorText + "<br/>";
            errorText = errorText + "Passwords must match and be 6 characters or more.";
        }
        else {
            passwordInput.removeClass("failed");
            confirmPasswordInput.removeClass("failed");
        }

        if (!validProfileImage) {
            profileImageInput.addClass("failed");
            if (errorText.length > 0)
                errorText = errorText + "<br/>";
            errorText = errorText + "Your profile photo must be in JPEG, PNG, or GIF format";
        }
        else {
            profileImageInput.removeClass("failed");
        }

        if (thisScope.ValidateRegistrationForm(thisScope)) {
            if (errorText.length > 0)
                errorText = errorText + "<br/>";
            errorText = errorText + "Please correct the highlighted fields.";
        }
        $(regFormPath + " div.error").css("display", "block");
        $(regFormPath + " div.error").html(errorText);
        return;
    } else {
        // success, so remove error messenging
        $(regFormPath + " div.error").html("");
        $(regFormPath + " div.error").css("display", "none");
        $(regFormPath + " input").removeClass("failed");
        $(regFormPath + " select").removeClass("failed");
        $(regFormPath + " password").removeClass("failed");
    }

    var userdata = '{' +
                    '"firstname":"' + encodeURIComponent($(regFormPath + " input[name=firstname]").attr("value")) + '",' +
                    '"lastname":"' + encodeURIComponent($(regFormPath + " input[name=lastname]").attr("value")) + '",' +
					'"email":"' + $(regFormPath + " input[name=user_email_address]").attr("value") + '",' +
					'"Password":"' + $(regFormPath + " input[name=user_password]").attr("value") + '",' +
    				'"address":"' + encodeURIComponent($(regFormPath + " input[name=address]").attr("value")) + '",' +
					'"city":"' + encodeURIComponent($(regFormPath + " input[name=city]").attr("value")) + '",' +
					'"zip":"' + $(regFormPath + " input[name=zip]").attr("value") + '",' +
                    '"StateProvinceCode":"' + $(regFormPath + " select[name=state]").val() + '",' +
                    '"StateProvince":"' + $(regFormPath + " select[name=state] :selected").text() + '",' +
                    '"CountryCode":"' + $(regFormPath + " select[name=country]").val() + '",' +
                    '"Country":"' + $(regFormPath + " select[name=country] :selected").text() + '",' +
					'"BusinessName":"' + $(regFormPath + " input[name=businessname]").attr("value") + '",' +
                    '"PrimaryBusinessCode":"' + $(regFormPath + " select[name=primary_business]").val() + '",' +
                    '"PrimaryBusiness":' + thisScope.GetDemographicItemText(regFormPath, "primary_business", "primary_business_desc", true) + ',' +
					'"Accreditations":' + thisScope.GetDemographicItemTextForOthers(regFormPath, "accreditations") + ',' +
                    '"WorkStatus":' + thisScope.GetDemographicItemTextForOthers(regFormPath, "workstatus") + ',' +
					'"username":"' + $(regFormPath + " input[name=user_name]").attr("value") + '",' +
					'"dateofbirth":"' + $(regFormPath + " input[name=dateofbirth]").attr("value") + '",' +
					'"AIANumber":' + thisScope.GetOptionalText(regFormPath, "aianumber", "AIA Number") + ',' +
    '}';
    // alert(userdata);
    $.ajax({
        type: "POST",
        url: "/development/kickappsservice.svc/registerhwuserforkickapps",
        data: userdata,
        dataType: "json",
        contentType: 'application/json; charset=utf-8',
        success: function (data) {
            switch (data.status) {
                case 5:
                    var profileImage = $("#profileimage").val();
                    if (profileImage != "") {
                        thisScope.ajaxFileUpload(data.username, data.profileId);
                    } else {
                        $(regFormPath + " div.error").html("A confirmation e-mail will be sent to the e-mail address.");
                    }
                    break;
                case 7:
                    $(regFormPath + " div.error").html("Error notifying gigya.");
                    $(regFormPath + " div.error").css("display", "block");
                case 6:
                    $(regFormPath + " div.error").html("Email/Username already in use. Please enter a different email/username.");
                    $(regFormPath + " div.error").css("display", "block");
                    break;
                case 11:
                    $(regFormPath + " div.error").html("Error registering with Kickapps.");
                    $(regFormPath + " div.error").css("display", "block");
                    break;
                case 12:
                    $(regFormPath + " div.error").html("Error registering with hanleywood.");
                    $(regFormPath + " div.error").css("display", "block");
                    break;
                case 4:
                default:
                    $(regFormPath + " div.error").html("Error registering.  Please try again.");
                    $(regFormPath + " div.error").css("display", "block");
                    break;
            }
        },
        error: function () {
            $(regFormPath + " div.error").html("Error registering.  Please try again.");
            $(regFormPath + " div.error").css("display", "block");
        }
    });
}

KickAppsLoginProvider.prototype.GetOptionalText = function (regFormPath, ddItemName, defaulttext) {
    if ($(regFormPath + " input[name=" + ddItemName + "]").attr("value").length > 0 && $(regFormPath + " input[name=" + ddItemName + "]").attr("value") != defaulttext) {
        return '"' + $(regFormPath + " input[name=" + ddItemName + "]").attr("value") + '"';
    } else {
        return '""';
    }
}

KickAppsLoginProvider.prototype.GetDemographicItemTextForOthers = function (regFormPath, ddItemName) {
    if ($(regFormPath + " select[name=" + ddItemName + "]").val().length > 0) {
        return '"' + $(regFormPath + " select[name=" + ddItemName + "] :selected").text() + '"';
    } else {
        return null;
    }
}

KickAppsLoginProvider.prototype.GetDemographicItemText = function (regFormPath, ddItemName, otherItemName, doEncode) {
    if ($(regFormPath + " select[name=" + ddItemName + "]").val().length > 0) {
        if ($(regFormPath + " select[name=" + ddItemName + "]").val() == "10") {
            if (doEncode) {
                return '"' + encodeURIComponent($(regFormPath + " input[name=" + otherItemName + "]").attr("value")) + '"';
            } else {
                return '"' + $(regFormPath + " input[name=" + otherItemName + "]").attr("value") + '"';
            }
        } else {
            return '"' + $(regFormPath + " select[name=" + ddItemName + "] :selected").text() + '"';
        }
    } else {
        return null;
    }
}

KickAppsLoginProvider.prototype.ValidateRegistrationForm = function (outerScope) {
    var displayErrorMessage = false;
    var baseXPath = "#registrationWithLinkOverlayTemplate .LHD_Registration ";
    var baseInputXPath = baseXPath + "input[name=";
    var baseSelectXPath = baseXPath + "select[name=";

    //validate username
    var ck_username = /^\s*[a-zA-Z0-9,_.\s]+\s*$/;
    var username = $(baseInputXPath + "user_name]");
    if (!ck_username.test(username.attr("value"))) {
        username.addClass("failed");
        displayErrorMessage = true;
    } else {
        username.removeClass("failed");
    }

    // email address validation
    var emailAddress = $(baseInputXPath + "user_email_address]");
    if (!outerScope.validateEmail(emailAddress.attr("value"))) {
        emailAddress.addClass("failed");
        displayErrorMessage = true;
    } else {
        emailAddress.removeClass("failed");
    }

    displayErrorMessage = outerScope.TextInputValidationHandler(baseInputXPath + "firstname]", "First Name", displayErrorMessage);
    displayErrorMessage = outerScope.TextInputValidationHandler(baseInputXPath + "lastname]", "Last Name", displayErrorMessage);
    displayErrorMessage = outerScope.TextInputValidationHandler(baseInputXPath + "businessname]", "Business/Firm Name", displayErrorMessage);
    displayErrorMessage = outerScope.TextInputValidationHandler(baseInputXPath + "address]", "Address", displayErrorMessage);
    displayErrorMessage = outerScope.TextInputValidationHandler(baseInputXPath + "city]", "City", displayErrorMessage);
    //displayErrorMessage = outerScope.TextInputValidationHandler(baseInputXPath + "dateofbirth]", "Date of Birth (yyyy-mm-dd)", displayErrorMessage);

    var birhtdate = $(baseInputXPath + "dateofbirth]");
    if (!outerScope.validateDateOfBirth(birhtdate.attr("value"))) {
        birhtdate.addClass("failed");
        displayErrorMessage = true;
    } else if (!outerScope.validateDateOfBirthWithCurrentYear(birhtdate.attr("value"))) {
        birhtdate.addClass("failed");
        displayErrorMessage = true;
    } else {
        birhtdate.removeClass("failed");
    }

    // state/providence validation
    var stateProvidence = $(baseSelectXPath + "state]");
    var zipPostalCode = $(baseInputXPath + "zip]");
    var country = $(baseSelectXPath + "country]");
    var chosenStateProvidence = null;
    //if (jQuery(stateProvidence.children()[0]).attr("selected") == true) {
    if (stateProvidence.find(":selected").index() == 0) {
        stateProvidence.addClass("failed");
        zipPostalCode.addClass("failed");
        country.addClass("failed");
        displayErrorMessage = true;
    } else {
        stateProvidence.removeClass("failed");
        chosenStateProvidence = stateProvidence.attr("value")
    }

    // zip/postal code validation
    var isUSPostalCode = false;
    var isCanadianPostalCode = false;
    if (chosenStateProvidence != null && isNaN(chosenStateProvidence)) {
        // is a US territory
        if (!outerScope.validateUSZipCode(zipPostalCode.attr("value"))) {
            stateProvidence.addClass("failed");
            zipPostalCode.addClass("failed");
            country.addClass("failed");
            displayErrorMessage = true;
        } else {
            isUSPostalCode = true;
            zipPostalCode.removeClass("failed");
        }
    } else if (chosenStateProvidence != null && !isNaN(chosenStateProvidence) && chosenStateProvidence != 53) {
        // is a Canadian territory
        if (!outerScope.validateCanadianZipCode(zipPostalCode.attr("value"))) {
            stateProvidence.addClass("failed");
            zipPostalCode.addClass("failed");
            country.addClass("failed");
            displayErrorMessage = true;
        } else {
            isCanadianPostalCode = true;
            zipPostalCode.removeClass("failed");
        }
    } else if (chosenStateProvidence != null && !isNaN(chosenStateProvidence) && chosenStateProvidence == 53) {
        // is not a US or Canadian territory
        if (jQuery.trim(zipPostalCode.attr("value")).length == 0 || zipPostalCode.attr("value") == "ZIP/Postal Code") {
            stateProvidence.addClass("failed");
            zipPostalCode.addClass("failed");
            country.addClass("failed");
            displayErrorMessage = true;
        } else {
            zipPostalCode.removeClass("failed");
        }
    } else {
        stateProvidence.addClass("failed");
        zipPostalCode.addClass("failed");
        country.addClass("failed");
        displayErrorMessage = true;
    }

    // country validation
    var chosenCountry = null;
    chosenCountry = country.attr("value");
    if (chosenStateProvidence != null && isNaN(chosenStateProvidence)) {
        // is a US territory{
        if (chosenCountry != "USA" || !isUSPostalCode) {
            stateProvidence.addClass("failed");
            zipPostalCode.addClass("failed");
            country.addClass("failed");
            displayErrorMessage = true;
        } else {
            country.removeClass("failed");
        }
    } else if (chosenStateProvidence != null && !isNaN(chosenStateProvidence) && chosenStateProvidence != 53) {
        // is a Canadian territory
        if (chosenCountry != "CANADA" || !isCanadianPostalCode) {
            stateProvidence.addClass("failed");
            zipPostalCode.addClass("failed");
            country.addClass("failed");
            displayErrorMessage = true;
        } else {
            country.removeClass("failed");
        }
    } else if (chosenStateProvidence != null && !isNaN(chosenStateProvidence) && chosenStateProvidence == 53) {
        if (country.find(":selected").index() == 0 || chosenCountry == "USA" ||
                    chosenCountry == "CANADA") {
            stateProvidence.addClass("failed");
            zipPostalCode.addClass("failed");
            country.addClass("failed");
            displayErrorMessage = true;
        } else {
            country.removeClass("failed");
        }
    } else {
        stateProvidence.addClass("failed");
        zipPostalCode.addClass("failed");
        country.addClass("failed");
        displayErrorMessage = true;
    }

    // validate other field for Primary Business
    var primaryBusiness = $(baseSelectXPath + "primary_business]");
    var primaryBusinessDesc = $(baseInputXPath + "primary_business_desc]");

    if (primaryBusiness.find(":selected").index() == 0) {
        primaryBusiness.addClass("failed");
        displayErrorMessage = true;
    } else {
        primaryBusiness.removeClass("failed");
    }

    var checkPrimaryBusinessOtherField = false;

    if (primaryBusiness.attr("value") == 10) {
        checkPrimaryBusinessOtherField = true;
    }
    if (checkPrimaryBusinessOtherField && (jQuery.trim(primaryBusinessDesc.attr("value")).length == 0 ||
            primaryBusinessDesc.attr("value") == "If \"Other\" please specify")) {
        primaryBusinessDesc.addClass("failed");
        displayErrorMessage = true;
    } else {
        primaryBusinessDesc.removeClass("failed");
    }

    return displayErrorMessage;
}

KickAppsLoginProvider.prototype.validateEmail = function (emailAddr) {
    var filter = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
    if (!filter.test(emailAddr)) {
        return false;
    }
    return true;
}


KickAppsLoginProvider.prototype.validateUserName = function (username) {
    if (username.length < 3 || username.length > 24) {
        return false;
    }
    return true;
}

KickAppsLoginProvider.prototype.validatePassword = function (password) {
    if (password.length < 6) {
        return false;
    }
    return true;
}

KickAppsLoginProvider.prototype.validateProfileImage = function (val) {
    if (val != "") {
        var ext = val.substring(val.lastIndexOf('.') + 1).toLowerCase();
        if (ext == "jpg" || ext == "png" || ext == "gif" || ext == "jpeg") {
            return true;
        } else {
            return false;
        }
    } else {
        return true;
    }

}

KickAppsLoginProvider.prototype.validateNewUserPassword = function (thisScope, password, confirmPassword) {
    if (thisScope.validatePassword(password) && thisScope.validatePassword(confirmPassword) && password == confirmPassword) {
        return true;
    } else {
        return false;
    }
}

KickAppsLoginProvider.prototype.validateDateOfBirth = function (birthdate) {
     var re = /^(18|19|20)\d\d[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])$/;
    return (re.test(birthdate))
}

KickAppsLoginProvider.prototype.validateDateOfBirthWithCurrentYear = function (birthdate) {
    var currentYear = (new Date).getFullYear();
    var givenYear = (new Date("01/01/" + birthdate.split("-")[0])).getFullYear();
    if (givenYear <= currentYear) {
        return true;
    }
    else { return false; }

}

KickAppsLoginProvider.prototype.validateUSZipCode = function (zipCodeStringToValidate) {
    var re = /^\d{5}([\-]\d{4})?$/;
    return (re.test(zipCodeStringToValidate));
}

KickAppsLoginProvider.prototype.validateCanadianZipCode = function (zipCodeStringToValidate) {
    var re = /^([ABCEGHJKLMNPRSTVXY][0-9][A-Z] [0-9][A-Z][0-9])*$/;
    return (re.test(zipCodeStringToValidate));
}

KickAppsLoginProvider.prototype.TextInputValidationHandler = function (xpath, text, displayErrorMessage) {
    var inputTag = $(xpath);
    if (jQuery.trim(inputTag.attr("value")).length == 0 || inputTag.attr("value") == text) {
        inputTag.addClass("failed");
        displayErrorMessage = true;
    } else {
        inputTag.removeClass("failed");
    }
    return displayErrorMessage;
}

KickAppsLoginProvider.prototype.states = {
    LOGGEDOUT: 0,
    LOGGEDIN: 1
};


KickAppsLoginProvider.prototype.loadStatesAndCountries = function () {
    var listCountries = "";
    var listStates = "";
    $.ajax({
        type: "GET",
        url: "/development/lhduserservice.svc/GetStatesAndCountriesData",
        data: '{}',
        contentType: 'application/json; charset=utf-8',
        success: function (data) {
            //parse and build coutries
            $.each(data.countries, function (itemNo, country) {
                listCountries += "<option value='" + country.Id + "'>" + country.Name + "</option>";

            });
            $('select[name$=country]').html(listCountries);
            //parse and build states
            $.each(data.states, function (itemNo, state) {
                listStates += "<option value='" + state.Id + "'>" + state.Name + "</option>";

            });
            $('select[name$=state]').html(listStates);

        },
        error: function (xhr) {
            if (xhr.responseText) {
                alert("Problem in loading Countries and States");
            }
        }
    });
}

KickAppsLoginProvider.prototype.populateCityStateCountryByZip = function (zip) {
    $.ajax({
        type: "GET",
        url: "/development/KickAppsService.svc/PopulateCityStateCountryByZip?zipCode=" + zip,
        data: '{}',
        contentType: 'application/json; charset=utf-8',
        success: function (data) {

            $.each(data, function (itemNo, item) {
                //alert("item.City :" + item[0]);
                $('input[name$=city]').val(item.City);
                //$('input[name$=county]').val(item.CountyName);
                $('select[name$=state]').val(item.StateAbbr);
                $('select[name$=country]').val(item.CountryAbbr);
            });
        },
        error: function (xhr) {
            if (xhr.responseText) {
                alert("Problem in populating City, State and Country");
            }
        }
    });
}

KickAppsLoginProvider.prototype.clearAllFields = function (_container, thisScope) {
    $("#" + _container + " input.textInput").each(function () { $(this).val(thisScope.getDefaultValue($(this).attr("name"))).removeClass("failed"); });
    $("#" + _container + " select").each(function () { $(this).val("").removeClass("failed"); });
    $("#" + _container + " div.error").html("");
    $("#" + _container + " div.error").css("display", "none");
    $("#" + _container + " div.success").html("");
    $("#" + _container + " div.success").css("display", "none");
}

KickAppsLoginProvider.prototype.getDefaultValue = function (control) {
    switch (control) {
        case 'firstname': return 'First Name';
        case 'lastname': return 'Last Name';
        case 'title': return 'Title (optional)';
        case 'companyname': return 'Company Name';
        case 'address': return 'Street Address';
        case 'city': return 'City';
        case 'zip': return 'ZIP/Postal Code';
        case 'phone': return 'Business Phone (optional)';
        case 'primary_business_desc': return 'If "Other" please specify';
        case 'job_title_desc': return 'If "Other" please specify';
    }
}

KickAppsLoginProvider.prototype.ajaxFileUpload = function (user, profileid) {
    var regFormPath = "#registrationWithLinkOverlayTemplate .LHD_Registration";
    $.ajaxFileUpload
		(
			{
			    url: '/development/ImageHandler.ashx?username=' + user + '&profileid=' + profileid,
			    secureuri: false,
			    fileElementId: 'profileimage',
			    dataType: 'json',
			    success: function (data) {
			        switch (data.status) {
			            case 1:
			                $(regFormPath + " div.error").html("A confirmation e-mail will be sent to the e-mail address.");
			                $(regFormPath + " div.error").css("display", "block");
			                break;
			            default:
			                $(regFormPath + " div.error").html("Error uploading photo.<br/>A confirmation e-mail will be sent to the e-mail address.");
			                $(regFormPath + " div.error").css("display", "block");
			                break;
			        }
			    },
			    error: function () {
			        $(regFormPath + " div.error").html("Error in photo upload.<br/>A confirmation e-mail will be sent to the e-mail address.");
			        $(regFormPath + " div.error").css("display", "block");
			    }
			}
		)
    return false;
}



///// Focus and Blur Functionality - START /////////////////////////////////////////
KickAppsLoginProvider.prototype.RegistrationFocusEvents = function (thisScope, handleEmail) {
    var basePath = "#registrationWithLinkOverlayTemplate .LHD_Registration";
    if (handleEmail) {
        thisScope.TextInputFocusEventHandler("E-mail address", basePath + " input[name=user_email_address]");
    }
    thisScope.TextInputFocusEventHandler("First Name", basePath + " input[name=firstname]");
    thisScope.TextInputFocusEventHandler("Last Name", basePath + " input[name=lastname]");
    thisScope.TextInputFocusEventHandler("Title (optional)", basePath + " input[name=title]");
    thisScope.TextInputFocusEventHandler("Business/Firm Name", basePath + " input[name=businessname]");
    thisScope.TextInputFocusEventHandler("Street Address", basePath + " input[name=address]");
    thisScope.TextInputFocusEventHandler("City", basePath + " input[name=city]");
    thisScope.TextInputFocusEventHandlerForZip("ZIP/Postal Code", basePath + " input[name=zip]", thisScope);
    thisScope.TextInputFocusEventHandler("If \"Other\" please specify", basePath + " input[name=primary_business_desc]");
    thisScope.TextInputFocusEventHandler("Date of Birth (yyyy-mm-dd)", basePath + " input[name=dateofbirth]");
}

KickAppsLoginProvider.prototype.TextInputFocusEventHandler = function (defaultText, xpath) {
    $(xpath).focus(function () {
        if (jQuery.trim(jQuery(this).attr("value")).toLowerCase() == defaultText.toLowerCase() ||
            jQuery.trim(jQuery(this).attr("value")).toLowerCase().length == 0) {
            jQuery(this).attr("value", "");
        }
    }).blur(function () {
        if (jQuery.trim(jQuery(this).attr("value")).toLowerCase().length == 0) {
            jQuery(this).attr("value", defaultText);
        }
    });
}
KickAppsLoginProvider.prototype.TextInputFocusEventHandlerForZip = function (defaultText, xpath, thisScope) {
    $(xpath).focus(function () {
        if (jQuery.trim(jQuery(this).attr("value")).toLowerCase() == defaultText.toLowerCase() ||
            jQuery.trim(jQuery(this).attr("value")).toLowerCase().length == 0) {
            jQuery(this).attr("value", "");
        }
    }).blur(function () {
        if (jQuery.trim(jQuery(this).attr("value")).toLowerCase().length == 0) {
            jQuery(this).attr("value", defaultText);
        }
        else {
            var zipValue = jQuery(this).attr("value");
            if (xpath.indexOf("input[name=zip]") != -1 && zipValue != defaultText) {
                thisScope.populateCityStateCountryByZip(zipValue);
            }
        }
    });
}
///// Focus and Blur Handlers - END   /////////////////////////////////////////

