(function () {

  YAHOO.namespace("applegate.registration");

  var Dom = YAHOO.util.Dom,
    $ = Dom.get,
    Event = YAHOO.util.Event,
    Selector = YAHOO.util.Selector,
    lang = YAHOO.lang,
    applegate = YAHOO.applegate,
    global = YAHOO.applegate.global,
    validation = applegate.validation;

  // Instantiate and configure Loader:
  var loader = new YAHOO.util.YUILoader({

    // Identify the components you want to load.  Loader will automatically identify
    // any additional dependencies required for the specified components.
        require: ["animation"],

    // YUI Base directory
    base: '/javascript/yui-2.8.0/',

    // Configure loader to pull in optional dependencies.  For example, animation
    // is an optional dependency for slider.
    loadOptional: true,

    // The function to call when all script/css resources have been loaded
    onSuccess: function() {

      Event.onDOMReady(function () {
        YAHOO.log('Focus on the email field', 'info', 'register.js');
        var tb = new YAHOO.applegate.resources.TextBundle('ib_msg_i18n');

                renderAutoCompleters();

        function renderAutoCompleters() {

          YAHOO.log('Creating Town datasource', 'info', 'register.js');
                    var dsTownAC = new applegate.dwr.DwrDataSource(RegistrationDwrModel.suggestTowns, [], {
                        appendRequest: true
                    });

          YAHOO.log('Creating County datasource', 'info', 'register.js');
                    var dsCountyAC = new applegate.dwr.DwrDataSource(RegistrationDwrModel.suggestCounties, [], {
                        appendRequest: true
                    });

                    YAHOO.log('Creating Country datasource', 'info', 'register.js');
                    var dsCountryAC = new applegate.dwr.DwrDataSource(RegistrationDwrModel.suggestCountries, [], {
                        appendRequest: true
                    });

                    if (Dom.get('subscriberCountryName')) {
                        YAHOO.log('Creating Country autocompleter', 'info', 'register.js');
                        var acCountry = new applegate.autocomplete.AutoComplete("subscriberCountryName", "countryContainer", dsCountryAC, {
            agSelectProperties: ["name"],
            agSuggestProperties: ["name"],
            agAllowEmptyQuery: true,
                            agTrackingField: {
                                field: "subscriberCountry",
                                property: "id"
                            },
            minQueryLength: 0,
            forceSelection: false
          });
                    }

                    if (Dom.get('cityTownNameInput')) {
                        YAHOO.log('Creating Town autocompleter', 'info', 'register.js');
                        var acTown = new applegate.autocomplete.AutoComplete("cityTownNameInput", "townContainer", dsTownAC, {
            agSelectProperties: ["name"],
            agSuggestProperties: ["name"],
            agAllowEmptyQuery: true,
                            agTrackingField: {
                                field: "cityTown",
                                property: "id"
                            },
            minQueryLength: 0,
            forceSelection: false
          });
        }

                    if (Dom.get('countyNameInput')) {
                        YAHOO.log('Creating County autocompleter', 'info', 'register.js');
                        var acCounty = new applegate.autocomplete.AutoComplete("countyNameInput", "countyContainer", dsCountyAC, {
            agSelectProperties: ["name"],
            agSuggestProperties: ["name"],
            agAllowEmptyQuery: true,
                            agTrackingField: {
                                field: "county",
                                property: "id"
                            },
            minQueryLength: 0,
            forceSelection: false
          });
        }

                }

        function bustCache() {
          var date = new Date();
          return date.getMilliseconds() + Math.random();
        }

        function handleNewCaptcha(p_oEvent) {
          YAHOO.applegate.captcha.handleNewCaptcha();
                    YAHOO.util.Event.preventDefault(p_oEvent);
        }

                function enableRegisterButton() {
                    Dom.removeClass('submitRegistration', 'disabled');
                    Dom.get('submitRegistration').disabled = false;
                    Dom.get('submitRegistration').style.cursor = 'pointer';
                }

                function disableRegisterButton() {
                    Dom.addClass('submitRegistration', 'disabled');
                    Dom.get('submitRegistration').disabled = true;
                    Dom.get('submitRegistration').style.cursor = 'default';
                }

        var clickEvent = {
          companySearch : function (o) {

                        // Search company with out 'Postcode' - show warning message
                        if (lang.trim($('findPostcode').value) == '') {
                            applegate.dialog.showWarning("You must enter a Post Code to search on", "Post Code not supplied");
                        }
                        else {
            renderDatatable();

                            // Show the "Can't find your company?" section on search:
                            Dom.get('cantFindCompany').style.display = 'block';

                            // Remove any warning messages/validation icons:
                            Dom.removeClass(Dom.getElementsByClassName('globalWarningAmber', null, 'newCompany'), 'globalWarningAmber');
                            Dom.removeClass(Dom.getElementsByClassName('globalGoGreen', null, 'newCompany'), 'globalGoGreen');
                            Dom.get('warningMessage').innerHTML = '';
                            Dom.removeClass(Dom.getElementsByClassName('invalid', null, 'newCompany'), 'invalid');
                            Dom.removeClass(Dom.getElementsByClassName('completed', null, 'newCompany'), 'completed');

            if (lang.trim($('findPostcode').value) !== '') {

                                Dom.get('findCompanyBtn').disabled = true;

              var myCallback = function () {

                this.set("sortedBy", null);
                var obj;
                try {
                  obj = YAHOO.lang.JSON.parse(myDataSource._oQueue.conn.conn.responseText);
                                    }
                                    catch (e) {
                  YAHOO.log('Error caught', 'error', 'register.js');
                }

                this.onDataReturnReplaceRows.apply(this, arguments);

                                    Dom.get('findCompanyBtn').disabled = false;

                                    if (obj.hasErrors) {
                                        applegate.dialog.showWarning(tb.getText(obj.globalErrors[0].message), "Post Code Error");
                }

                                    if (obj.totalResults > 0) {
                  this.selectRow(0);
                }

              };
              var callback1 = {
                success : myCallback,
                failure : myCallback,
                scope : myDataTable
              };

              var companyName = lang.trim($('findCompanyName').value),
                postcode = lang.trim($('findPostcode').value);
                emailAddress = lang.trim($('email').value);
                myDataSource.sendRequest('findCompanyName=' + encodeURIComponent(companyName) + '&findPostcode=' + encodeURIComponent(postcode) + '&checkEmailAddress=' + encodeURIComponent(emailAddress) + '&t=' + bustCache(), callback1);
            }
                        }

          },

          newCompany : function (o) {
                        global.clearForm($('newCompany'));
                        global.enableForm($('newCompany'));
                        enableRegisterButton();
          }
        };
                YAHOO.util.Event.addListener("findCompanyBtn", "click", clickEvent.companySearch);


                var fnEnterKeyPressEvent = function(e) {
                    if (e.keyCode == 13) {
                        clickEvent.companySearch();
                    }
                };
                YAHOO.util.Event.addListener('findPostcode', 'keypress', fnEnterKeyPressEvent);


        function handleRegister(p_oEvent) {
          document.body.style.cursor = 'wait';
                    disableRegisterButton();
          var form = Dom.get('registrationForm');
          validation.clearMessages(form);
          var YUC = YAHOO.util.Connect;
          YUC.setForm(form);

          YUC.asyncRequest('POST', global.contextPath() + "/register.json", {
            success: handleRegisterSuccess,
            failure: handleRegisterFailure,
            scope: this
          });
        }

                YAHOO.util.Event.addListener("submitRegistration", "click", handleRegister);

        var handleRegisterSuccess = function (o) {
          var obj = lang.JSON.parse(o.responseText),
             form = Dom.get('registrationForm');
                    if (obj.hasErrors) {

                        // The binding result errors go into a hidden div which
                        // is then copied into a popup dialog.
            validation.applyBindingResultToForm(obj, form);
                        applegate.dialog.showWarning(Dom.get('applegate-validation-messages').innerHTML, "There was a problem");

            YAHOO.applegate.captcha.handleNewCaptcha();
            $('captcha').value = '';
            document.body.style.cursor = 'default';
                        enableRegisterButton();
                        window.scrollTo(0, 0);
            sideburnColumns();
          } else {
            validation.clearMessages(form);
            location.href = global.contextPath() + '/' + obj.view;
          }
        };

        var handleRegisterFailure = function (o) {
          applegate.dialog.showWarning("Your registration failed. Please try again or contact us.", "Registration Failed");
          YAHOO.applegate.captcha.handleNewCaptcha();
                    enableRegisterButton();
          document.body.style.cursor = 'default';
        };

        YAHOO.log('Set JavaScript refresh code for newCaptchaImg', 'info', 'registration.js');
        Event.addListener("newCaptchaImg", "click", handleNewCaptcha);


        sideburnColumns();

        var myDataSource = null,
                myDataTable = null;


        function selectRowEvent(oArgs) {
          var record = this.getRecord(oArgs.el);
          var id = record.getData('id');

          var companyCallback = function (company) {
            if (company !== null && typeof company === 'object') {
                            global.populateForm(company, $('newCompany'));
                            global.disableForm($('newCompany'));

                            // Add the disabled class to the input elements as well
                            // as actually disabling them so they are greyed out:
                            var nodes = Selector.query('input,select', Dom.get('newCompany'));
                            Dom.addClass(nodes, 'disabled');

                            // Remove validation classes as these are not relevant in this situation:
                            Dom.removeClass(nodes, 'error');
                            Dom.removeClass(nodes, 'applegate-validation-error');

                            Dom.removeClass('accountManager', 'disabled');
                            Dom.removeClass('notYourCompany', 'disabled');

              // If there is any form of controller, active or pending, then disable the register button
              if (record.getData('hasController') === true || record.getData('hasControllerValidationPending') === true) {

                                // Display a message indicating why this company cannot be registered:
                                Dom.removeClass(Dom.getElementsByClassName('boxTitle', null, 'newCompany'), 'globalGoGreen');
                                Dom.addClass(Dom.getElementsByClassName('boxTitle', null, 'newCompany'), 'globalWarningAmber');

                                var emailAddress = document.getElementById("email").value;
                                var name = lang.trim(document.getElementById("firstName").value) + " " + lang.trim(document.getElementById("lastName").value);
                                if (record.getData('hasController')) {
                                    Dom.get('warningMessage').innerHTML = 'This company already has a controller, you can <a href="/account/contactUs.html?companyId=' + record.getData("id") + '&ref=registration&emailAddress=' + emailAddress + '&name=' + name + '" title="Contact Us" target="_blank">Contact Us</a> regarding this';
                                } else if (record.getData('hasControllerValidationPending')) {
                                    Dom.get('warningMessage').innerHTML = 'This company has a controller registration pending, you can <a href="/account/contactUs.html?companyId=' + record.getData("id") + '&ref=registration&emailAddress=' + emailAddress + '&name=' + name + '" title="Contact Us" target="_blank">Contact Us</a> regarding this';
                                }

                                disableRegisterButton();
              } else {

                                // Set title class to green:
                                Dom.removeClass(Dom.getElementsByClassName('boxTitle', null, 'newCompany'), 'globalWarningAmber');
                                Dom.addClass(Dom.getElementsByClassName('boxTitle', null, 'newCompany'), 'globalGoGreen');
                                Dom.get('warningMessage').innerHTML = 'Complete your registration to take control of the content of your Applegate listing';

                                enableRegisterButton();
              }
            }
          };
          RegistrationDwrModel.findCompanyById(id, companyCallback);
        }


        function renderDatatable() {

          this.hasControllerFormatter = function (elCell, oRecord, oColumn, sData) {
            if (oRecord.getData("hasController")) {
                            elCell.innerHTML = '<span title="This company already has a controller, you can Contact Us regarding this">Registered</span>';
            } else if (oRecord.getData("hasControllerValidationPending")) {
                            elCell.innerHTML = '<span title="This company has a controller registration pending, you can Contact Us regarding this">Pending</span>';
                        } else {
                            elCell.innerHTML = 'None';
            }
          };

          var myColumnDefs = [
                    {
                        key: "name",
                        label: "Name",
                        sortable: true,
                        width: 140
                    },

                    {
                        key: "town",
                        label: "Town/City",
                        sortable: true,
                        width: 70
                    },

                    {
                        key: "postcode",
                        label: "Post Code",
                        sortable: true,
                        width: 60
                    },

                    {
                        label: 'Controller',
                        sortable: false,
                        formatter: this.hasControllerFormatter,
                        width: 40
                        }
                    ];

          myDataSource = new YAHOO.util.DataSource(global.contextPath() + '/companySearch/search.html?');
          myDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
          myDataSource.connXhrMode = "queueRequests";
                    myDataSource.connMethodPost = true;
          myDataSource.responseSchema = {
            resultsList: "results",
            fields: ["name", "town", "postcode", "hasController", "hasControllerValidationPending", "id"]
          };

          var oConfigs = {
            initialLoad: false
          };

          myDataTable = new applegate.datatable.DataTable('companySearchResults', myColumnDefs, myDataSource, oConfigs);
                    myDataTable.showTableMessage("Loading...");

          // Enables single-mode row selection
          myDataTable.set("selectionMode", "single");
          myDataTable.subscribe("rowSelectEvent", selectRowEvent);
                    myDataTable.subscribe("initEvent", sideburnColumns);
        }

                if ($('ref').value === 'PUBLIC_COMPANY_PAGE') {
          if (lang.trim($('findCompanyName').value) !== '' && lang.trim($('findPostcode').value) !== '') {
            window.setTimeout(function () {
              clickEvent.companySearch();
            }, 1000);
          }
        }

        if ($('currentUserStatus').value === 'LOGGED_IN' || $('currentUserStatus').value === 'PARTIALLY_LOGGED_IN') {
          // Disable the email address because they must have one to be (partially) logged in
          $('email').readOnly = true;
          Dom.addClass('email', 'disabled');
          // Hide the link if they are fully/partially logged in because it's redundant
          Dom.setStyle('already_registered', 'display', 'none');

          // Disable first and last name if they are present
          if (lang.trim($('firstName').value) !== '') {
            $('firstName').readOnly = true;
            Dom.addClass('firstName', 'disabled');
          } else {
            window.setTimeout(function () {
              $('firstName').focus();
            }, 100);
          }

          if (lang.trim($('lastName').value) !== '') {
            $('lastName').readOnly = true;
            Dom.addClass('lastName', 'disabled');
                    } else if ($('firstName').readOnly) {
            window.setTimeout(function () {
              $('lastName').focus();
            }, 100);
          }

                    if ($('firstName').readOnly && $('lastName').readOnly && Dom.inDocument('subscriberCountryName')) {
            window.setTimeout(function () {
                            $('subscriberCountryName').focus();
            }, 100);
          }
        }
                if (!$('email').readOnly) {
          $('email').focus();
        }

      });

    },

    //Set your skins member here:
    skin: {
      // The default skin, which is automatically applied if not
      // overriden by a component-specific skin definition.
      // Use the Applegate specific skin.
      defaultSkin: 'applegate'
    },

    // Configure the Get utility to timeout after 10 seconds for any given node insert
    timeout: 10000,

    // Combine YUI files into a single request (per file type) by using the Yahoo! CDN combo service.
    combine: false
  });

  // Load the files using the insert() method. The insert method takes an optional
  // configuration object, and in this case we have configured everything in
  // the constructor, so we don't need to pass anything to insert().
  loader.insert();

})();






