/*
 * @(#)form.js
 *
 *    Version: 0.99.20100301
 * Written by: Yves Kreis <mailto:yves.kreis@education.lu>
 *
 * Copyright (C) 2003-2010 by Yves Kreis
 *
 * This work is licensed under the Creative Commons Attribution-Noncommercial-Share Alike 3.0 Luxembourg License.
 * To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-sa/3.0/lu/ or send a letter to 
 * Creative Commons, 171 Second Street, Suite 300, San Francisco, California, 94105, USA.
 *
 */

/*
 *
 * This JavaScript provides functions for input validation in a form.
 * It uses two variables to specify
 *   - the contribution of an ordinary member (intContributionOrdinary);
 *   - the reduction of the contribution if an email is provided (intContributionEmail);
 *
 * To change its value, use a script environment like in the following example:
 *    <html>
 *    <head>
 *      ...
 *      <script type="text/javascript">
 *      <!--
 *        intForm = 0;
 *        intContributionOrdinary = 0;
 *        intContributionEmail = 0;
 *      //-->
 *      </script>
 *      <script type="text/javascript" src="form.js"></script>
 *      ...
 *    </head>
 *    ...
 *    </html>
 *
 * Functions available in this file:
 * 
 *   addActivity(input)
 *   
 *   getElement(elements, item = 1)
 *   
 *   validInput(input, required = false)
 *   validSelect(select, required = false)
 *   
 *   validCurrency(input, required = false)
 *   validDate(input, required = false)
 *   validEmail(input, required = false, select = null)
 *   validNumber(input, required = false, length = 1)
 *   validTelephone(input, required = false)
 *   validText(input, required = false, length = 1)
 *   
 *   validAccount(inputIBAN, inputBIC, required = false)
 *   validPasswords(inputPassword1, inputPassword2, required = false)
 *   
 *   validPassword(inputPassword, inputButton)
 *   
 *   mySubmit(formElement, message)
 *
 * Usage examples:
 *   <input ... onblur="validInput(this);" onkeyup="validInput(this);"></input>
 *   <select ... size="1" onchange="validSelect(this);" onkeyup="validSelect(this);">...</select>
 *   <input ... onclick="mySubmit(this);"></input>
 *   <input ... onclick="mySubmit(this, 'search');"></input>
 *
 */

if ("undefined" == typeof(intContributionOrdinary)) {
  var intContributionOrdinary = 0;
}
if ("undefined" == typeof(intContributionEmail)) {
  var intContributionEmail = 0;
}

var duration = 0.4;

var colorWhite = '#ffffff';
var colorValid = '#ffffff';
var colorRequired = '#ffffff';
if (document.styleSheets[0].cssRules) {
  cssRules = document.styleSheets[0].cssRules;
} else if (document.styleSheets[0].rules) {
  cssRules = document.styleSheets[0].rules;
}
for (var i = 0; i < cssRules.length; i++) {
  if ('input.white, select.white, option.white' == cssRules[i].selectorText.toLowerCase() || 'input.white' == cssRules[i].selectorText.toLowerCase()) {
    colorWhite = cssRules[i].style.backgroundColor;
  }
  if ('input.valid, select.valid, option.valid' == cssRules[i].selectorText.toLowerCase() || 'input.valid' == cssRules[i].selectorText.toLowerCase()) {
    colorValid = cssRules[i].style.backgroundColor;
  }
  if ('input.required, select.required, option.required' == cssRules[i].selectorText.toLowerCase() || 'input.required' == cssRules[i].selectorText.toLowerCase()) {
    colorRequired = cssRules[i].style.backgroundColor;
  }
}

function passwordStrength(password) {
  var strength = 0;
  
  // Length
  if (10 > password.length) {
    strength = strength + password.length;
  } else {
    strength = strength + 10;
  }
  
  // Letters
  if (password.match(/[a-z]/) && password.match(/[A-Z]/)) {
    strength = strength + 8;
  } else if (password.match(/[a-zA-Z]/)) {
    strength = strength + 5;
  }
  
  // Numbers
  if (password.match(/[0-9].*[0-9]/)) {
    strength = strength + 8;
  } else if (password.match(/[0-9]/)) {
    strength = strength + 5;
  }
  
  // Special Characters
  if (password.match(/[^a-zA-Z0-9].*[^a-zA-Z0-9]/)) {
    strength = strength + 8;
  } else if (password.match(/[^a-zA-Z0-9]/)) {
    strength = strength + 5;
  }
  
  // Combinations
  if (password.match(/[a-zA-Z]/) && password.match(/[0-9]/)) {
    strength = strength + 2;
  }
  if (password.match(/[a-zA-Z]/) && password.match(/[^a-zA-Z0-9]/)) {
    strength = strength + 2;
  } 
  if (password.match(/[a-zA-Z]/) && password.match(/[0-9]/) && password.match(/[^a-zA-Z0-9]/)) {
    strength = strength + 2;
  }
  
  return strength / 40;
}

function addActivity(element) {
  if ('' == element.value || -1 != element.className.indexOf('readonly') || -1 != element.className.indexOf('disabled')) {
    return;
  }
  element.setAttribute('onblur', 'validInput(this);');
  element.setAttribute('onkeyup', 'validInput(this);');
  var name = element.parentNode.parentNode.getElementsByTagName('td')[1].getElementsByTagName('input')[0].name.split(':');
  name = name[0] + ':' + (parseInt(name[1]) + 1);
  var table;
  var tbody;
  var tr;
  var td;
  var text;
  var input;
  table = document.createElement('table');
  table.className = 'profile';
  tbody = document.createElement('tbody');
  table.appendChild(tbody);
  tr = document.createElement('tr');
  tbody.appendChild(tr);
  td = document.createElement('td');
  td.className = 'border-left';
  text = document.createTextNode(element.parentNode.parentNode.getElementsByTagName('td')[0].innerHTML);
  td.appendChild(text);
  tr.appendChild(td);
  td = document.createElement('td');
  td.className = 'border-right';
  input = document.createElement('input');
  input.setAttribute('type', 'hidden');
  input.setAttribute('name', name);
  input.setAttribute('value', '');
  td.appendChild(input);
  input = document.createElement('input');
  input.className = 'profile';
  input.setAttribute('type', 'text');
  input.setAttribute('name', name);
  input.setAttribute('id', name + '_IEfix');
  input.setAttribute('maxlength', '65');
  input.setAttribute('value', '');
  input.setAttribute('onblur', 'validInput(this); addActivity(this);');
  input.setAttribute('onkeyup', 'validInput(this); addActivity(this);');
  td.appendChild(input);
  tr.appendChild(td);
  element.parentNode.parentNode.parentNode.parentNode.parentNode.insertBefore(table, element.parentNode.parentNode.parentNode.parentNode.nextSibling);
  table = document.createElement('table');
  table.className = 'profile';
  tbody = document.createElement('tbody');
  table.appendChild(tbody);
  tr = document.createElement('tr');
  tbody.appendChild(tr);
  td = document.createElement('td');
  td.className = 'border-left border-right';
  tr.appendChild(td);
  element.parentNode.parentNode.parentNode.parentNode.parentNode.insertBefore(table, element.parentNode.parentNode.parentNode.parentNode.nextSibling);
}

function getElement(elements, item) {
  if ('undefined' == typeof(item)) {
    var item = 1;
  }
  
  if (undefined == elements.type) {
    return elements.item(item);
  }
  return elements;
}

function validInput(input, required) {
  if ('' == input.id || -1 != input.className.indexOf('readonly') || -1 != input.className.indexOf('disabled')) {
    return;
  }
  if ('undefined' == typeof(required)) {
    var required = false;
  }
  
  if ('' == input.value) {
    if (required) {
      $(input.id).morph('background-color: ' + colorRequired + ';', { duration: duration / 2 });
    } else {
      $(input.id).morph('background-color: ' + colorWhite + ';', { duration: duration / 2 });
    }
  } else {
    $(input.id).morph('background-color: ' + colorValid + ';', { duration: duration / 2 });
  }
}

function validSelect(select, required) {
  if ('' == select.id || -1 != select.className.indexOf('disabled')) {
    return;
  }
  if ('undefined' == typeof(required)) {
    var required = false;
  }
  
  if ('' == select.value) {
    if (required) {
      $(select.id).morph('background-color: ' + colorRequired + ';', { duration: duration / 2 });
    } else {
      $(select.id).morph('background-color: ' + colorWhite + ';', { duration: duration / 2 });
    }
  } else {
    $(select.id).morph('background-color: ' + colorValid + ';', { duration: duration / 2 });
  }
}

function validCurrency(input, required) {
  if ('' == input.id || -1 != input.className.indexOf('readonly') || -1 != input.className.indexOf('disabled')) {
    return;
  }
  if ('undefined' == typeof(required)) {
    var required = false;
  }
  
  if (input.value.match(/^[0-9]{1,4}([.,][0-9]{0,2})*$/)) {
    $(input.id).morph('background-color: ' + colorValid + ';', { duration: duration / 2 });
  } else if ('' == input.value && !required) {
    $(input.id).morph('background-color: ' + colorWhite + ';', { duration: duration / 2 });
  } else {
    $(input.id).morph('background-color: ' + colorRequired + ';', { duration: duration / 2 });
  }
}

function validDate(input, required) {
  if ('' == input.id || -1 != input.className.indexOf('readonly') || -1 != input.className.indexOf('disabled')) {
    return;
  }
  if ('undefined' == typeof(required)) {
    var required = false;
  }
  
  var valid = false;
  if (input.value.match(/^[0-9]{1,2}[.\/][0-9]{1,2}[.\/](19|20)[0-9]{2}$/)) {
    var date_array = input.value.split(/[/.]/);
    date_array[1] = date_array[1] - 1;
    var date = new Date(date_array[2], date_array[1], date_array[0]);
    var now  = new Date();
    if (date.getDate() == date_array[0] && date.getMonth() == date_array[1] && date.getFullYear() == date_array[2]) {
      valid = true;
    }
  }
  if (valid) {
    $(input.id).morph('background-color: ' + colorValid + ';', { duration: duration / 2 });
  } else if ('' == input.value && !required) {
    $(input.id).morph('background-color: ' + colorWhite + ';', { duration: duration / 2 });
  } else {
    $(input.id).morph('background-color: ' + colorRequired + ';', { duration: duration / 2 });
  }
}

function validEmail(input, required, select) {
  if ('' == input.id || -1 != input.className.indexOf('readonly') || -1 != input.className.indexOf('disabled')) {
    return;
  }
  if ('undefined' == typeof(required)) {
    var required = false;
  }
  if ('undefined' == typeof(select)) {
    var select = null;
  }
  
  var member = 'Ordinaire (' + intContributionOrdinary + ' €)';
  if (input.value.match(/^[A-Za-z0-9&'+-_]+(\.[A-Za-z0-9&'+-_]+)*@[A-Za-z0-9-]+\.([A-Za-z0-9-]+\.)*?[A-Za-z]+$/)) {
    $(input.id).morph('background-color: ' + colorValid + ';', { duration: duration / 2 });
    member = 'Ordinaire (' + (intContributionOrdinary - intContributionEmail) + ' €)'
  } else if ('' == input.value && !required) {
    $(input.id).morph('background-color: ' + colorWhite + ';', { duration: duration / 2 });
  } else {
    $(input.id).morph('background-color: ' + colorRequired + ';', { duration: duration / 2 });
  }
  if (null != select) {
    for (var i = 0; i < select.options.length; i++) {
      if ('Ordinaire' == select.options[i].text.substring(0, 9)) {
        select.options[i].text = member;
      }
    }
  }
}

function validNumber(input, required, length) {
  if ('' == input.id || -1 != input.className.indexOf('readonly') || -1 != input.className.indexOf('disabled')) {
    return;
  }
  if ('undefined' == typeof(required)) {
    var required = false;
  }
  if ('undefined' == typeof(length)) {
    var length = 1;
  }
  
  if (input.value.match(new RegExp('^[0-9]{' + length + ',}$', ''))) {
    $(input.id).morph('background-color: ' + colorValid + ';', { duration: duration / 2 });
  } else if ('' == input.value && !required) {
    $(input.id).morph('background-color: ' + colorWhite + ';', { duration: duration / 2 });
  } else {
    $(input.id).morph('background-color: ' + colorRequired + ';', { duration: duration / 2 });
  }
}

function validTelephone(input, required) {
  if ('' == input.id || -1 != input.className.indexOf('readonly') || -1 != input.className.indexOf('disabled')) {
    return;
  }
  if ('undefined' == typeof(required)) {
    var required = false;
  }
  
  var value;
  value = input.value;
  value = value.replace(/ /g, '');
  value = value.replace(/\(/g, '');
  value = value.replace(/\)/g, '');
  if (value.match(/^\+(1[0-9]{3}|2[078]|2[1-69][0-9]|3[0-469]|3[578][0-9]|4[013-9]|42[0-9]|5[1-8]|5[09][0-9]|6[0-6]|6[7-9][0-9]|7|8[1-469]|8[0578][0-9]|9[0-58]|9[679][0-9])[1-9][0-9]{5,}$/)) {
    $(input.id).morph('background-color: ' + colorValid + ';', { duration: duration / 2 });
  } else if ('' == input.value && !required) {
    $(input.id).morph('background-color: ' + colorWhite + ';', { duration: duration / 2 });
  } else {
    $(input.id).morph('background-color: ' + colorRequired + ';', { duration: duration / 2 });
  }
}

function validText(input, required, length) {
  if ('' == input.id || -1 != input.className.indexOf('readonly') || -1 != input.className.indexOf('disabled')) {
    return;
  }
  if ('undefined' == typeof(required)) {
    var required = false;
  }
  if ('undefined' == typeof(length)) {
    var length = 1;
  }
  
  if (input.value.length >= length) {
    $(input.id).morph('background-color: ' + colorValid + ';', { duration: duration / 2 });
  } else if ('' == input.value && !required) {
    $(input.id).morph('background-color: ' + colorWhite + ';', { duration: duration / 2 });
  } else {
    $(input.id).morph('background-color: ' + colorRequired + ';', { duration: duration / 2 });
  }
}

function validAccount(inputIBAN, inputBIC, required) {
  if ('undefined' == typeof(required)) {
    var required = false;
  }
  
  var validIBAN = false;
  var validBIC  = false;
  
  var valueIBAN;
  valueIBAN = inputIBAN.value.toUpperCase();
  valueIBAN = valueIBAN.replace(/ /g, '');
  
  var lengthIBAN = null;
  switch (valueIBAN.substring(0, 2)) {
    case 'DE':
      length = 22;
      break;
    case 'BE':
      length = 16;
      break;
    case 'ES':
      length = 24;
      break;
    case 'FR':
      length = 27;
      break;
    case 'IT':
      length = 27;
      break;
    case 'LU':
      length = 20;
      break;
    case 'PT':
      length = 25;
      break;
  }
  
  if (inputIBAN.value == inputIBAN.defaultValue) {
    validIBAN = true;
  } else if ((null == lengthIBAN && valueIBAN.match(/^[A-Z]{2}[0-9]{2}[0-9A-Z]{5,30}$/)) || valueIBAN.match(new RegExp('^[A-Z]{2}[0-9]{2}[0-9A-Z]{' + (lengthIBAN - 4) + '}$', ''))) {
    var iban = '';
    var position = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    
    for (var i = 4; i < valueIBAN.length; i++) {
      iban = iban + position.indexOf(valueIBAN.charAt(i));
    }
    for (var i = 0; i < 4; i++) {
      iban = iban + position.indexOf(valueIBAN.charAt(i));
    }
    
    var remainder = 0;
    for (var i = 0; i < iban.length; i++) {
      remainder = (remainder * 10 + parseInt(iban.charAt(i))) % 97;
    }
    
    if (1 == remainder) {
      validIBAN = true;
    }
  }
  
  var valueBIC;
  valueBIC = inputBIC.value.toUpperCase();
  valueBIC = valueBIC.replace(/ /g, '');
  
  if (valueBIC.match(/^[A-Z]{8,11}$/)) {
    validBIC = true;
  }
  
  if (2 <= valueIBAN.length && 6 <= valueBIC.length && valueIBAN.substring(0, 2) != valueBIC.substring(4, 6)) {
    validIBAN = false;
    validBIC  = false;
  }
  
  if ('' != inputIBAN.id && -1 == inputIBAN.className.indexOf('readonly') && -1 == inputIBAN.className.indexOf('disabled')) {
    if (validIBAN) {
      $(inputIBAN.id).morph('background-color: ' + colorValid + ';', { duration: duration / 2 });
    } else if ('' == inputIBAN.value && '' == inputBIC.value && !required) {
      $(inputIBAN.id).morph('background-color: ' + colorWhite + ';', { duration: duration / 2 });
    } else {
      $(inputIBAN.id).morph('background-color: ' + colorRequired + ';', { duration: duration / 2 });
    }
  }
  
  if ('' != inputBIC.id && -1 == inputBIC.className.indexOf('readonly') && -1 == inputBIC.className.indexOf('disabled')) {
    if (validBIC) {
      $(inputBIC.id).morph('background-color: ' + colorValid + ';', { duration: duration / 2 });
    } else if ('' == inputIBAN.value && '' == inputBIC.value && !required) {
      $(inputBIC.id).morph('background-color: ' + colorWhite + ';', { duration: duration / 2 });
    } else {
      $(inputBIC.id).morph('background-color: ' + colorRequired + ';', { duration: duration / 2 });
    }
  }
}

function validPasswords(inputPassword1, inputPassword2, required) {
  if ('undefined' == typeof(required)) {
    var required = false;
  }
  
  if ('' != inputPassword1.id && -1 == inputPassword1.className.indexOf('readonly') && -1 == inputPassword1.className.indexOf('disabled')) {
    if ('' == inputPassword1.value && required) {
      $(inputPassword1.id).morph('background-color: ' + colorRequired + ';', { duration: duration / 2 });
    } else {
      inputPassword1.style.backgroundColor = 'transparent';
    }
  }
  if ('' != inputPassword2.id && -1 == inputPassword2.className.indexOf('readonly') && -1 == inputPassword2.className.indexOf('disabled')) {
    if ('' == inputPassword1.value && '' == inputPassword2.value) {
      if (required) {
        $(inputPassword2.id).morph('background-color: ' + colorRequired + ';', { duration: duration / 2 });
      } else {
        $(inputPassword2.id).morph('background-color: ' + colorWhite + ';', { duration: duration / 2 });
      }
    } else if (inputPassword1.value == inputPassword2.value) {
      $(inputPassword2.id).morph('background-color: ' + colorValid + ';', { duration: duration / 2 });
    } else {
      $(inputPassword2.id).morph('background-color: ' + colorRequired + ';', { duration: duration / 2 });
    }
  }
  if ('' != inputPassword1.parentNode.id && -1 == inputPassword1.className.indexOf('readonly') && -1 == inputPassword1.className.indexOf('disabled')) {
    $(inputPassword1.parentNode.id).morph('width: ' + passwordStrength(inputPassword1.value) * 210 + 'px;', { duration: duration });
  }
}

function validPassword(inputPassword, inputButton) {
  validInput(inputPassword, true);
  
  if ('' == inputPassword.value) {
	inputButton.disabled = true;
  } else {
    inputButton.disabled = false;
  }
}

function mySubmit(formElement, message) {
  if ('undefined' == typeof(formElement)) {
    if (1 == document.forms.length) {
      var formElement = document.forms[0];
    } else {
      return;
    }
  } else {
    while ('FORM' != formElement.nodeName) {
      formElement = formElement.parentNode;
    }
  }
  if ('undefined' == typeof(message)) {
    var message = 'sent';
  }
  
  if ('profile.php' == document.location.pathname.substring(1)) {
    var inputButton = null;
    for (var intElement = 0; intElement < formElement.length; intElement++) {
      if ('button' == formElement.elements[intElement].type) {
        inputButton = formElement.elements[intElement];
        break;
      }
    }
    if (null != inputButton && inputButton.disabled) {
      alert('Vous devez entrer votre mot de passe actuel!');
      return;
    }
  }
  
  var separator = '&';
  var position  = formElement.action.length;
  if (-1 != formElement.action.indexOf('#')) {
    position = formElement.action.indexOf('#');
  }
  if (-1 == formElement.action.indexOf('?')) {
    separator = '?';
  }
  formElement.action = formElement.action.substring(0, position) + separator + 'button=' + message + formElement.action.substring(position);
  formElement.submit();
}

function onKeyUpListener(event) {
  keyUpListener(event, true);
}

function noKeyUpListener(event) {
  keyUpListener(event, false);
}

function keyUpListener(event, action) {
  if ('undefined' == typeof(event)) {
    var event = window.event;
  }
  
  var keyCode = 0;
  if (event.keyCode) {
    keyCode = event.keyCode;
  } else if (event.which) {
    keyCode = event.which;
  }
  
  var input = null;
  if (event.target) {
    input = event.target;
  } else if (event.srcElement) {
    input = event.srcElement;
  }
  if (3 == input.nodeType) {
    // Safari Bug
    input = input.parentNode;
  }
  
  if (13 == keyCode) {
    if (action) {
      if (null != input && 'button' != input.type) {
        mySubmit(input);
      }
    } else {
      alert('Choisissez le bouton adéquat s\'il-vous-plaît!');
    }
  }
}

function registerKeyUpListener() {
  for (var intForm = 0; intForm < document.forms.length; intForm++) {
    var buttons = 0;
    for (var intElement = 0; intElement < document.forms[intForm].length; intElement++) {
      if ('button' == document.forms[intForm].elements[intElement].type) {
        buttons++;
      }
    }
    if (1 == buttons) {
      document.forms[intForm].onkeyup = onKeyUpListener;
    } else {
      document.forms[intForm].onkeyup = noKeyUpListener;
    }
  }
}

if (window.addEventListener) {
  window.addEventListener('load', function () { registerKeyUpListener(); }, false);
} else if (window.attachEvent) {
  window.attachEvent('onload', function () { registerKeyUpListener(); });
}