﻿/*****************

  (c) 2006 Q42 B.V.

  The contents of this file, partially or in whole, may not be reproduced
  without prior written permission by Q42 B.V.

*****************/

function MagazineAanvraag()
{
  Spif.DOMEvents.attach(window, "load", this.doLoad, this);
}

function formValidationErrorHandler(errors)
{
  // errors won't be alerted

  // set cursor to next errored field
  //alert(errors[0].field);
  if (errors.length > 0) {
    if (errors[0].field.type != 'hidden') {
      try {
        errors[0].field.focus();
        errors[0].field.select();
      }
      catch (ex) {
      }
    }

    if (magazineAanvraag.formvalidator)
    {
      magazineAanvraag.formvalidator.__defaultShowErrors(magazineAanvraag.formvalidator.__errors);
    }
    
    if (magazineAanvraag.frformvalidator)
    {
      magazineAanvraag.frformvalidator.__defaultShowErrors(magazineAanvraag.frformvalidator.__errors);
    }
  }
}

MagazineAanvraag.prototype = {

  formvalidator: null,
  frformvalidator: null,
  theform: null,
  theFrform: null,
  frSubmitButton: null,
  submitButton: null,
  magazinChkBx: null,
  eMagazinChkBx: null,
  frMagazineChkBx: null,
  formFields: null,
  formFieldsFieldset: null,

  doLoad: function() {
    this.theform = document.getElementById('theform');
    this.theFrform = document.getElementById('theFrForm');
    this.submitButton = document.getElementById("newsletter-ok-button");
    this.frSubmitButton = document.getElementById("fr-newsletter-ok-button");
    this.magazineChkBx = document.getElementById('magazine');
    this.eMagazineChkBx = document.getElementById('e-magazine');
    this.frMagazineChkBx = document.getElementById('fr-magazine');
    this.formFields = document.getElementById('formFields');
    this.formFieldsFieldset = document.getElementById('formFieldsFieldset');

    if (this.theform) {
      this.formvalidator = new FormValidator(this.theform, {
        messages: resources.messages.formvalidator
      });
      this.formvalidator.options.alertHandler = formValidationErrorHandler;
      if (this.submitButton)
        Spif.DOMEvents.attach(this.submitButton, "click", this.handleSubmit, this);
    }

    if (this.theFrform) {
      this.frformvalidator = new FormValidator(this.theFrform, {
        messages: resources.messages.formvalidator
      });
      if (this.frSubmitButton)
        Spif.DOMEvents.attach(this.frSubmitButton, "click", this.handleFrSubmit, this);
    }

    if (this.magazineChkBx)
      Spif.DOMEvents.attach(this.magazineChkBx, "click", function() {
        if (this.magazineChkBx.checked) {
          Spif.ClassNameAbstraction.replace(this.theform, "p-form-fields-hidden", "p-form-fields-visible", Spif.Utils.FIREEVENTS);
          Spif.ClassNameAbstraction.replace(this.theform, "form-collapsed", "form-expanded", Spif.Utils.FIREEVENTS);
          this.changeRequiredState(this.theform, 'pf', 'unrequired', 'required');
          setTimeout(function() { window.location.href = '#form-start'; }, 200);

          if (this.eMagazineChkBx == null) {
            Spif.ClassNameAbstraction.replace(this.theform, "e-form-fields-hidden", "e-form-fields-visible", Spif.Utils.FIREEVENTS);
            Spif.ClassNameAbstraction.replace(this.theform, "form-collapsed", "form-expanded", Spif.Utils.FIREEVENTS);
            this.changeRequiredState(this.theform, 'ef', 'unemail', 'email');
            this.changeRequiredState(this.theform, 'ef', 'unrequired', 'required');
          }
        } else {
          Spif.ClassNameAbstraction.replace(this.theform, "p-form-fields-visible", "p-form-fields-hidden", Spif.Utils.FIREEVENTS);
          if (this.eMagazineChkBx == null) {
            Spif.ClassNameAbstraction.replace(this.theform, "e-form-fields-visible", "e-form-fields-hidden", Spif.Utils.FIREEVENTS);
            Spif.ClassNameAbstraction.replace(this.theform, "form-expanded", "form-collapsed", Spif.Utils.FIREEVENTS);
            this.changeRequiredState(this.theform, 'ef', 'required', 'unrequired');
            this.changeRequiredState(this.theform, 'ef', 'email', 'unemail');
          }
          else if (!this.eMagazineChkBx.checked) {
            Spif.ClassNameAbstraction.replace(this.theform, "form-expanded", "form-collapsed", Spif.Utils.FIREEVENTS);
          }
          this.changeRequiredState(this.theform, 'pf', 'required', 'unrequired');
        }
      }, this);


    if (this.eMagazineChkBx)
      Spif.DOMEvents.attach(this.eMagazineChkBx, "click", function() {
        if (this.eMagazineChkBx.checked) {
          Spif.ClassNameAbstraction.replace(this.theform, "e-form-fields-hidden", "e-form-fields-visible", Spif.Utils.FIREEVENTS);
          Spif.ClassNameAbstraction.replace(this.theform, "form-collapsed", "form-expanded", Spif.Utils.FIREEVENTS);
          this.changeRequiredState(this.theform, 'ef', 'unemail', 'email');
          this.changeRequiredState(this.theform, 'ef', 'unrequired', 'required');
          setTimeout(function() { window.location.href = '#form-start'; }, 200);
        } else {
          Spif.ClassNameAbstraction.replace(this.theform, "e-form-fields-visible", "e-form-fields-hidden", Spif.Utils.FIREEVENTS);
          if (!this.magazineChkBx.checked) {
            Spif.ClassNameAbstraction.replace(this.theform, "form-expanded", "form-collapsed", Spif.Utils.FIREEVENTS);
          }
          this.changeRequiredState(this.theform, 'ef', 'required', 'unrequired');
          this.changeRequiredState(this.theform, 'ef', 'email', 'unemail');
        }
      }, this);

    if (this.frMagazineChkBx)
      Spif.DOMEvents.attach(this.frMagazineChkBx, "click", function() {
        if (this.frMagazineChkBx.checked) {
          Spif.ClassNameAbstraction.replace(this.theFrform, "form-collapsed", "form-expanded", Spif.Utils.FIREEVENTS);
          setTimeout(function() { window.location.href = '#fr-form-start'; }, 200);
          this.changeRequiredState(this.theform, 'ef', 'unrequired', 'required');
        } else {
          Spif.ClassNameAbstraction.replace(this.theFrform, "form-expanded", "form-collapsed", Spif.Utils.FIREEVENTS);
          this.changeRequiredState(this.theform, 'ef', 'required', 'unrequired');
        }
      }, this);

    // Attach the eventhandlers for changes made in the second panel form
    var inputs = document.getElementsByTagName("input");
    for (var i = 0; i < inputs.length; i++) {
      if (inputs[i].getAttribute("type") == "text")
        Spif.DOMEvents.attach(inputs[i], "blur", this.updateChanges);
    }

    var emailChoiceTypeYes = document.getElementById("email-choice-type-yes");
    if (emailChoiceTypeYes != null)
      Spif.DOMEvents.attach(emailChoiceTypeYes, "click", this.handleChoiceYes, this);
    var emailChoiceTypeNo = document.getElementById("email-choice-type-no");
    if (emailChoiceTypeNo != null)
      Spif.DOMEvents.attach(emailChoiceTypeNo, "click", this.handleChoiceNo, this);
  },

  handleChoiceYes: function(evt) {
    var emailadres = document.getElementById("emailadres");
    Spif.ClassNameAbstraction.replace(emailadres, 'unemail', 'email', Spif.Utils.FIREEVENTS);
    Spif.ClassNameAbstraction.replace(emailadres, 'unrequired', 'required', Spif.Utils.FIREEVENTS);
  },

  handleChoiceNo: function(evt) {
    var emailadres = document.getElementById("emailadres");
    Spif.ClassNameAbstraction.replace(emailadres, 'email', 'unemail', Spif.Utils.FIREEVENTS);
    Spif.ClassNameAbstraction.replace(emailadres, 'required', 'unrequired', Spif.Utils.FIREEVENTS);
  },

  updateChanges: function(evt) {
    var el = evt.subject;

    if (el.getAttribute("type") == "text") {
      var inputName = el.getAttribute("name");
      var prefix = (document.forms[0].id == 'theFrForm' ? 'fr-' : '');

      if (document.getElementById('newsletter')) {
        var inputId = el.getAttribute("id");

        if (inputId.indexOf("voorletters") != -1 || inputId.indexOf("naam") != -1) {
          if (el.value.length > 1) el.value = (el.value.substring(0, 1).toUpperCase() + el.value.substring(1, el.value.length));
          else if (el.value.length > 0) el.value = el.value.substring(0, 1).toUpperCase();
        }

        if (el.value.length > 0) {
          if (inputId.indexOf("voorletters") != -1) {
            var url = "/ValidateInput.aspx";
            url += "?Initials=" + el.value;
            url += "&Field=" + inputName;
            url += "&Kind=newsletter";
            url += "&nocache=" + new Date().getTime();
            xmlhttp.request(url, null, true, "magazineAanvraag.processInput", false);
          }
          //if (inputId.indexOf("email") != -1)
          //{
          // var url = "/ValidateInput.aspx";
          //  url += "?Email=" + el.value;
          //  url += "&Field=" + inputName;
          //  url += "&Kind=newsletter";
          //  url += "&nocache=" + new Date().getTime();
          //  xmlhttp.request(url, null, true, "magazineAanvraag.processInput", false);
          //}
          //if (inputId.indexOf("tussenvoegsel") != -1)
          //{
          //  var url = "/ValidateInput.aspx";
          //  url += "?Inbetween=" + el.value;
          //  url += "&Field=" + inputName;
          //  url += "&Kind=newsletter";
          //  url += "&nocache=" + new Date().getTime();
          //  xmlhttp.request(url, null, true, "magazineAanvraag.processInput", false);
          //}
        }
      }
      else {
        if (inputName.indexOf("voorletters") != -1 || inputName.indexOf("achternaam") != -1 || inputName.indexOf("straat") != -1 ||
							inputName.indexOf("plaats") != -1 || inputName.indexOf("plaats2") != -1 || inputName.indexOf("voornaam") != -1) {
          if (el.value.length > 1) el.value = (el.value.substring(0, 1).toUpperCase() + el.value.substring(1, el.value.length));
          else if (el.value.length > 0) el.value = el.value.substring(0, 1).toUpperCase();
        }

        if (el.value.length > 0) {
          var Country = document.forms[0][prefix + 'land'].value;

          if (inputName.indexOf("voorletters") != -1 &&
						    document.getElementById("tussenvoegsels_hidden") == null) {
            var url = "/ValidateInput.aspx";
            url += "?Initials=" + el.value;
            url += "&Field=" + inputName;
            url += "&Country=" + Country;
            url += "&nocache=" + new Date().getTime();
            xmlhttp.request(url, null, true, "magazineAanvraag.processInput", false);
          }
          /*
          if (inputName.indexOf("emailadres") != -1)
          {
          if (el.value.length > 0)
          {
          var emailChoiceTypeYes = document.getElementById("email-choice-type-yes");
          var emailChoiceTypeNo = document.getElementById("email-choice-type-no");
          if (emailChoiceTypeYes != null && emailChoiceTypeNo != null &&
          emailChoiceTypeYes.checked == false && emailChoiceTypeNo.checked == false)
          emailChoiceTypeYes.checked = true;
          }

            var url = "/ValidateInput.aspx";
          url += "?Email=" + el.value;
          url += "&Field=" + inputName;
          url += "&Country=" + Country;
          url += "&nocache=" + new Date().getTime();
          xmlhttp.request(url, null, true, "magazineAanvraag.processInput", false);
          }
          if (inputName.indexOf("tussenvoegsels") != -1)
          {
          var url = "/ValidateInput.aspx";
          url += "?Inbetween=" + el.value;
          url += "&Field=" + inputName;
          url += "&Country=" + Country;
          url += "&nocache=" + new Date().getTime();
          xmlhttp.request(url, null, true, "magazineAanvraag.processInput", false);
          }
          */
        }
      }
    }

    // Fetch address information, based on zipcode and streetnumber
    if (el.name == 'huisnummer' || el.name == 'postcode') {
      var Country = document.forms[0][prefix + 'land'].value;
      if (Country.toUpperCase() == "NL") // If country = NL then lookup the address
      {
        var HouseNumber = document.forms[0][prefix + 'huisnummer'].value;
        var ZipCode = document.forms[0][prefix + 'postcode'].value;
        if (HouseNumber.length > 0 && ZipCode.length > 0) {
          var url = "/Booking/ValidateAddressRestService.aspx";
          url += "?HouseNumber=" + HouseNumber;
          url += "&ZipCode=" + ZipCode;
          url += "&nocache=" + new Date().getTime();
          xmlhttp.request(url, null, true, "magazineAanvraag.processValidateAddress", false);
        }
      }
    }
  },

  processInput: function() {
    if (xmlhttp.req["magazineAanvraag.processInput"].readyState == 4) {
      if (xmlhttp.req["magazineAanvraag.processInput"].status == 200) {
        var resultDocument = xmlhttp.req["magazineAanvraag.processInput"].responseXML;

        if (resultDocument != null && resultDocument.getElementsByTagName("Errors") != null && resultDocument.getElementsByTagName("Errors").item(0) != null) {
          var errorList = resultDocument.getElementsByTagName("Errors").item(0).getElementsByTagName('Error');
          var field = resultDocument.getElementsByTagName("Field").item(0).firstChild.nodeValue;
          var updateField;

          try {
            if (document.getElementById('newsletter')) {
              var updateForm = document.getElementById('theform');
              updateField = updateForm[field];
            }
            else {
              updateField = document.forms[0][field];
            }

            if (errorList.length > 0) {
              var error = errorList.item(0).getElementsByTagName('Description').item(0).firstChild.nodeValue;
              if (error != 'NoCrmValidation') {
                magazineAanvraag.formvalidator.__setInvalidClassName(updateField);
                updateField.focus();
                updateField.title = error;
              }
            } else {
              updateField.value = resultDocument.getElementsByTagName("Result").item(0).firstChild.nodeValue;
            }
          }
          catch (e) { alert('Field:' + field + '; error =>' + e.description); }
        }
      }
    }
  },

  processValidateAddress: function() {
    if (xmlhttp.req["magazineAanvraag.processValidateAddress"].readyState == 4) {

      if (xmlhttp.req["magazineAanvraag.processValidateAddress"].status == 200) {

        var resultDocument = xmlhttp.req["magazineAanvraag.processValidateAddress"].responseXML;

        if (resultDocument != null && resultDocument.getElementsByTagName("Errors") != null && resultDocument.getElementsByTagName("Errors").item(0) != null) {
          var errorList = resultDocument.getElementsByTagName("Errors").item(0).getElementsByTagName('Error');

          if (errorList.length > 0) {
            document.forms[0]['plaats'].disabled = false;
            document.forms[0]['straat'].disabled = false;
            document.forms[0]['plaats-hidden'].value = '';
            document.forms[0]['straat-hidden'].value = '';

            //Remove spaces and make uppercase
            document.forms[0]['postcode'].value = document.forms[0]['postcode'].value.replace(' ', '').toUpperCase();

            Spif.ClassNameAbstraction.add(document.forms[0]['plaats'], "required");
            Spif.ClassNameAbstraction.add(document.forms[0]['straat'], "required");

          } else {

            document.forms[0]['plaats'].disabled = true;
            document.forms[0]['straat'].disabled = true;

            Spif.ClassNameAbstraction.remove(document.forms[0]['plaats'], "required");
            Spif.ClassNameAbstraction.remove(document.forms[0]['straat'], "required");

            for (i = 0; i < document.forms[0]['land'].length; i++) {
              if (document.forms[0]['land'][i].value == "NL") {
                document.forms[0]['land'].selectedIndex = i;
              }
            }

            try {
              document.forms[0]['plaats'].value = resultDocument.getElementsByTagName("Town").item(0).firstChild.nodeValue;
              document.forms[0]['straat'].value = resultDocument.getElementsByTagName("Street").item(0).firstChild.nodeValue;
              //document.forms[0]['huisnummer'].value = resultDocument.getElementsByTagName("HouseNumber").item(0).firstChild.nodeValue;
              document.forms[0]['postcode'].value = resultDocument.getElementsByTagName("ZipCode").item(0).firstChild.nodeValue;

              //Weenro [20061030]
              //Use hidden input to allow content to be posted.
              document.forms[0]['plaats-hidden'].value = document.forms[0]['plaats'].value;
              document.forms[0]['straat-hidden'].value = document.forms[0]['straat'].value;
            }

            catch (e) { }

            magazineAanvraag.formvalidator.__validateOneField(document.forms[0]['land']);
            magazineAanvraag.formvalidator.__validateOneField(document.forms[0]['plaats']);
            magazineAanvraag.formvalidator.__validateOneField(document.forms[0]['straat']);

          }
        }
      }
    }
  },

  changeRequiredState: function(parentEl, contextClass, oldClass, newClass) {
    var els = parentEl.getElementsByTagName('div');
    for (var i = 0; i < els.length; i++) {
      var el = els[i];
      if (Spif.ClassNameAbstraction.contains(el, contextClass)) {
        var inptEls = el.getElementsByTagName('input');
        if (inptEls && inptEls[0]) {
          inptEls[0].value = "";
          if (Spif.ClassNameAbstraction.contains(inptEls[0], oldClass)) {
            Spif.ClassNameAbstraction.replace(inptEls[0], oldClass, newClass, Spif.Utils.FIREEVENTS);
          }
        }
      }
    }
  },

  handleSubmit: function() {
    if (!this.formvalidator.__validate())
      return false;
    else {
      var action = this.theform.getAttribute('action');
      if (this.magazineChkBx && this.magazineChkBx.checked) {
        action += '&magazinerequest=true';
      }
      if (this.eMagazineChkBx && this.eMagazineChkBx.checked) {
        action += '&newsletterrequest=true';
      }
      this.theform.setAttribute('action', action);
      this.theform.submit();
    }
  },

  handleFrSubmit: function() {
    if (!this.frformvalidator.__validate())
      return false;
    else {
      var action = this.theFrform.getAttribute('action');
      if (this.magazineChkBx && this.magazineChkBx.checked) {
        action += '&magazinerequest=true';
      }
      if (this.eMagazineChkBx && this.eMagazineChkBx.checked) {
        action += '&newsletterrequest=true';
      }
      this.theFrform.setAttribute('action', action);
      this.theFrform.submit();
    }
  }
};

var magazineAanvraag = new MagazineAanvraag();
