﻿/// <reference path="../../jQueryIntellisense.js"/>
/// <reference path="../../Relational.Standard.Core.js"/>

/*
* jQuery RegisterForm Plugin
* Caudill Web
* @requires jQuery v.1.4+
* @requires Relational.Standard.Core 
*/

// TODO: Fix issue that displays a matched organization and the new organization form when an email matching an organization is entered, 
//       then the local gov checkbox is unchecked and rechecked, then a new organization is entered into the search box


(function($) {

    $.fn.registerForm = function(options) {

        var defaults = {};
        this.each(function() {
            var emailIsValid = false;

            var config = $.extend(defaults, options);
            var self = this, $self = $(this);

            var $firstName = $("input.FirstName", self);
            var $lastName = $("input.LastName", self);
            var $email = $("input.Email", self);
            var $isLocalGovernment = $(".IsLocalGovernment :checkbox", self);
            var $organizationID = $("input.OrganizationID", self);
            var $organizationLookup = $("input.OrganizationLookup", self);
            var $emailDomainWarning = $("div.EmailDomainWarning", self);
            var $newOrganizationNotice = $("div.NewOrganizationNotice", self);
            var $newOrganizationWrapper = $("div.NewOrganizationWrapper", self);
            var $newOrganizationDisplayName = $newOrganizationWrapper.find("strong");
            var $newOrganizationTextbox = $("input.NewOrganizationTextbox", self);
            var $newOrganizationClearButton = $("a.NewOrganizationClearButton", self);
            var $newOrganizationForm = $("div.NewOrganizationForm", self);
            var $password = $("input.Password");
            var $passwordConfirm = $("input.PasswordConfirm");
            var $createAccount = $("a.CreateAccount", self);
            var $addNewOrgYesButton = $("a.AddNewOrgYesButton", self);
            var $addNewOrgNoButton = $("a.AddNewOrgNoButton", self);
            var $jurisdictionRow = $("div.JurisdictionRow", self);
            var $autocompletePicker = $(".AutocompletePicker", self);
            var $newOrganizationState = $("select.NewOrganizationState", self);

            init();

            function init() {
                $email.bind("blur", validateEmail);
                $organizationID.bind("change", validateEmail);
                $isLocalGovernment.bind("click", function() {
                    setJurisdictionRowVisibility();
                });
                $newOrganizationClearButton.bind("click", function(event) {
                    showAutoComplete();
                    event.preventDefault();
                });
                $addNewOrgYesButton.bind("click", function(event) {
                    $newOrganizationNotice.hide();
                    $newOrganizationForm.show();
                    var value = $newOrganizationDisplayName.text()
                    var city = $.trim(value.split(",")[0]);
                    var state = '';
                    if (value.indexOf(",") > -1) {
                        state = $.trim(value.split(",")[1]).toUpperCase();
                        $newOrganizationState.val(state);
                    }
                    $newOrganizationWrapper.hide();
                    $newOrganizationTextbox.val(city);
                    event.preventDefault();
                });
                $addNewOrgNoButton.bind("click", function(event) {
                    showAutoComplete();
                    event.preventDefault();
                });
                $autocompletePicker.bind("createNew", function(event, value) {
                    validateEmail();
                    $organizationLookup.hide();
                    $newOrganizationWrapper.show();
                    $newOrganizationDisplayName.text(value);
                    $newOrganizationNotice
                        .show()
                        .find("a:first")
                        .focus();
                    return false;  // this overrides autocompletePicker's default createNew behavior
                });
                $autocompletePicker.bind("clearSelection", clearNewOrganizationFields);
                validateEmail();
                setJurisdictionRowVisibility();
            }
            
            function clearNewOrganizationFields(){
                $newOrganizationTextbox.val("");
                $newOrganizationState.val("");
            }

            function showAutoComplete() {
                $newOrganizationWrapper.hide().find("strong").html("");
                clearNewOrganizationFields();
                $newOrganizationNotice.hide();
                $newOrganizationForm.hide();
                $organizationLookup.val("").show().focus();
            }

            function setJurisdictionRowVisibility() {
                if ($isLocalGovernment.attr("checked") == true) {
                    $jurisdictionRow.show();
                    $organizationLookup.show().focus();
                } else {
                    $jurisdictionRow.hide();
                    // reset any selection that may have been made
                    $organizationLookup.val("");
                    $organizationID.val("");
                    showAutoComplete();
                    $autocompletePicker.trigger("showEditForm");
                }
            }

            function validateEmail() {
                emailIsValid = false;
                $emailDomainWarning.html("");
                var email = $email.val();
                var organizationId = $organizationID.val();
                if (email.length > 0 && email != $email.attr("title")) {
                    if (organizationId == "") {
                        // Try to find the right organization by the email provided
                        organizationId = getOrganizationIdByEmail(email);
                        if (organizationId != '' && organizationId != 0) {
                            emailIsValid = true;
                            // Matched an organization - check the local government checkbox
                            $isLocalGovernment.attr("checked", true);
                            $jurisdictionRow.show();
                            // Assign the looked-up value
                            $autocompletePicker.trigger("dataBind", organizationId);
                        }
                    } else {
                        Relational.Standard.Core.showProgress();
                        $.ajax({
                            url: window.location.href,
                            type: "POST",
                            data: {
                                registerId: self.id,
                                action: "validateemail",
                                emailAddress: email,
                                organizationId: organizationId
                            },
                            success: function(msg) {
                                Relational.Standard.Core.hideProgress();
                                if (msg == "1") {
                                    $emailDomainWarning.html("");
                                    emailIsValid = true;
                                } else {
                                    $emailDomainWarning.html(msg);
                                    emailIsValid = false;
                                }
                                $email.valid();
                            },
                            error: function(XMLHttpRequest, textStatus, errorThrown) {
                                Relational.Standard.Core.updateStatus('warning', errorThrown + ' ' + textStatus)
                                Relational.Standard.Core.hideProgress();
                            }
                        }); // ajax
                    } // if organizationID
                } // if email 
            } // validateEmail()

            function getOrganizationIdByEmail(email) {
                Relational.Standard.Core.showProgress();
                var organizationId = "";
                $.ajax({
                    url: window.location.href,
                    type: "POST",
                    async: false,
                    data: {
                        registerId: self.id,
                        action: "getorganizationidbyemail",
                        emailAddress: email
                    },
                    success: function(msg) {
                        Relational.Standard.Core.hideProgress();
                        organizationId = msg;
                    },
                    error: function(XMLHttpRequest, textStatus, errorThrown) {
                        Relational.Standard.Core.updateStatus('warning', errorThrown + ' ' + textStatus)
                        Relational.Standard.Core.hideProgress();
                    }
                }); // ajax
                return organizationId;
            }

            // Add organizationemaildomain method
            $.validator.addMethod(
                "organizationemaildomain", function() {
                    if ($organizationID.val() == "") { return true };
                    return emailIsValid;
                },
                "Please enter a valid email address for the selected jurisdiction."
            ); // organizationemaildomain


        }); // each

    }; // $.fn.registerForm 

})(jQuery);


