
function textfocus(o) {
  if (o.value == o.defaultValue)
    o.value = '';
}

function textblur(o) {
  if (o.value == '')
    o.value = o.defaultValue;
}

function copyInputValue(src, dst, name) {
  var s = findInputNodeWithName(src, name);
  if (s == undefined)
    return;

  var d = findInputNodeWithName(dst, name);
  if (d == undefined)
    return;

  d.value = s.value;
}

function findInputNodeWithName(o, n) {
  var c = o.firstChild;
  var r;

  while (c != null) {
    if (c.nodeName.toLowerCase() == 'input' && c.name == n) {
      return c;
    }

    if (c.hasChildNodes())
      r = findInputNodeWithName(c, n);

    if (r != undefined)
      return r;

    c = c.nextSibling;
  }
  return undefined;
}

function findInputNodesWithName(o, n) {
  var c = o.firstChild;
  var r = [];

  while (c != null) {
    if (c.nodeName.toLowerCase() == 'input' && c.name == n)
      r.push(c);

    if (c.hasChildNodes()) {
      var r1 = findInputNodesWithName(c, n);

      for (var i = 0; i < r1.length; i++)
        r.push(r1[i]);
    }
    c = c.nextSibling;
  }

  return r;
}

var timerID = null;
var timerRunning = false;
var origText = null;

function subscriptionhover(text) {
  var o = document.getElementById('descriptionfield');

  if (origText == null)
    origText = o.innerHTML;

  o.innerHTML = '<p style="color: red; font-weight: bold;">The first 3 months are always free!</p>' + text;

  if(timerRunning)
    clearTimeout(timerID);
  timerRunning = false;
}

function subscriptionunhover() {
   timerID = setTimeout(revertText, 5000);
   timerRunning = true;
}

function revertText() {
  var o = document.getElementById('descriptionfield');
  o.innerHTML = origText;
}

var contactsCount = 1;

function subscription_add() {
  var co = document.getElementById('signupcontainer');
  var so = document.getElementById('signuppy');

  var lastSignup = co.lastChild;
  while (lastSignup != null && lastSignup.nodeName.toLowerCase() != 'div')
    lastSignup = lastSignup.previousSibling;

  if (lastSignup == null)
    return;

  ++contactsCount;
  var counterText = document.createElement('P');
  counterText.className = "counter";
  counterText.setAttribute("num", new String(contactsCount));
  counterText.innerHTML = 'Contact #'+ contactsCount + ' (<a href="javascript:remove_subscriber('+contactsCount+')">Remove subscriber</a>)';
  //counterText.appendChild(document.createTextNode('Contact #'+ ++contactsCount))
  co.appendChild(counterText);

  var newChild = so.cloneNode(true);
  newChild.id = '';

  copyInputValue(lastSignup, newChild, 'companyname');
  findInputNodeWithName(newChild, 'name').value = '';
  copyInputValue(lastSignup, newChild, 'address1');
  copyInputValue(lastSignup, newChild, 'address2');
  copyInputValue(lastSignup, newChild, 'zipcode');
  copyInputValue(lastSignup, newChild, 'city');
  findInputNodeWithName(newChild, 'email').value = '';
  copyInputValue(lastSignup, newChild, 'phone');
  copyInputValue(lastSignup, newChild, 'fax');
  copyInputValue(lastSignup, newChild, 'vat');

  co.appendChild(newChild);
}

function removeSignupErrorTexts() {
  var co = document.getElementById('signupcontainer');
  var c = co.firstChild;

  while (c != null) {
    var cn = c.nextSibling;
    if (c.nodeName.toLowerCase() == 'p' && c.className == 'signup-error')
      co.removeChild(c);

    c = cn;
  }
}

function remove_subscriber(num) {
  var divs = [];
  var ps   = [];

  removeSignupErrorTexts();

  var co = document.getElementById('signupcontainer');

  for (var o = co.firstChild; o != null; o = o.nextSibling) {
    if (o.nodeName.toLowerCase() == 'p' && o.className == 'counter')
      ps.push(o);

    if (o.nodeName.toLowerCase() == 'div')
      divs.push(o);
  }

  co.removeChild(ps[num-2]);
  co.removeChild(divs[num-1]);

  var ps = [];
  for (var o = co.firstChild; o != null; o = o.nextSibling) {
    if (o.nodeName.toLowerCase() == 'p' && o.className == 'counter')
      ps.push(o);
  }

  var c = 2;
  for (var p in ps) {
    ps[p].innerHTML = 'Contact #'+ c + ' (<a href="javascript:remove_subscriber('+c+')">Remove subscriber</a>)';
    c++;
  }
  --contactsCount;
}

function findSubNumFromNode(o) {
  while (o != undefined && (o.nodeName.toLowerCase() != 'div' || o.className != 'signuppy')) {
    o = o.parentNode;
  }

  return o;
}

var ERROR_FOUND;

function checkInputNodes(name, origValue, errorText) {
  var co = document.getElementById('signupcontainer');
  var r;

  r = findInputNodesWithName(co, name);

  for (var i = 0; i < r.length; i++) {
    var o = r[i];
    if (o.value == '' || o.value == origValue) {
      ERROR_FOUND = true;
      var p = findSubNumFromNode(o);

      if (p != undefined) {
        var errorP = document.createElement('P');
        errorP.className = "signup-error";
        errorP.innerHTML = errorText;

        co.insertBefore(errorP, p);
      }
    }
  }
}

function checkMailVerifyNodes() {
  var co = document.getElementById('signupcontainer');
  var r;

  r  = findInputNodesWithName(co, 'email');
  r2 = findInputNodesWithName(co, 'emailverify');

  for (var i = 0; i < r.length; i++) {
    var o  = r[i];
    var o2 = r2[i];
    if (o.value != o2.value) {
      ERROR_FOUND = true;
      var p = findSubNumFromNode(o);

      if (p != undefined) {
        var errorP = document.createElement('P');
        errorP.className = "signup-error";
        errorP.innerHTML = 'The \'Verify e-mail\' field does not match your e-mail entry!';

        co.insertBefore(errorP, p);
      }
    }
  }
}

function subscription_form_verify() {
  removeSignupErrorTexts();
  ERROR_FOUND = false;
  checkInputNodes('name',     'Fill in your name',   'You need to fill in a name!');
  checkInputNodes('address1', 'Address',             'You need to fill in an address!');
  checkInputNodes('zipcode',  'zipcode',             'You need to fill in a zip code!');
  checkInputNodes('email',    'Fill in your e-mail', 'You need to fill in an e-mail address!');

  checkMailVerifyNodes();

  return !ERROR_FOUND;
}

function joincontacts_add(maxcontacts) {
  var co = document.getElementById('joincontactscontainer');
  var so = document.getElementById('joincontactser');

  var lastSignup = co.lastChild;
  while (lastSignup != null && lastSignup.nodeName.toLowerCase() != 'div')
    lastSignup = lastSignup.previousSibling;

  if (lastSignup == null)
    return;

  if (maxcontacts != undefined && maxcontacts == contactsCount) {
    alert("This account only allows "+maxcontacts+" contacts per account. Please upgrade your account to add more.");
    return;
  }

  ++contactsCount;
  var counterText = document.createElement('P');
  counterText.className = "counter";
  counterText.setAttribute("num", new String(contactsCount));
  counterText.innerHTML = 'Contact #'+ contactsCount + ' (<a href="javascript:remove_joincontacts('+contactsCount+')">Remove contact</a>)';
  co.appendChild(counterText);

  var newChild = so.cloneNode(true);
  newChild.id = '';

  co.appendChild(newChild);

  var n;
  n = findInputNodeWithName(newChild, 'contactname');   n.value = 'Contact name'; updatevalidcontact(n);
  n = findInputNodeWithName(newChild, 'contactemail');  n.value = 'Email'; updatevalidcontact(n);
  n = findInputNodeWithName(newChild, 'contactphone');  n.value = 'Phone';
  n = findInputNodeWithName(newChild, 'contactfax');    n.value = 'Mobile phone';
  n = findInputNodeWithName(newChild, 'contactmobile'); n.value = 'Fax';
}

function remove_joincontacts(num) {
  var divs = [];
  var ps   = [];

  //removeErrorTexts();

  var co = document.getElementById('joincontactscontainer');

  for (var o = co.firstChild; o != null; o = o.nextSibling) {
    if (o.nodeName.toLowerCase() == 'p' && o.className == 'counter')
      ps.push(o);

    if (o.nodeName.toLowerCase() == 'div')
      divs.push(o);
  }

  co.removeChild(ps[num-2]);
  co.removeChild(divs[num-1]);

  var ps = [];
  for (var o = co.firstChild; o != null; o = o.nextSibling) {
    if (o.nodeName.toLowerCase() == 'p' && o.className == 'counter')
      ps.push(o);
  }

  var c = 2;
  for (var p in ps) {
    ps[p].innerHTML = 'Contact #'+ c + ' (<a href="javascript:remove_joincontacts('+c+')">Remove contact</a>)';
    c++;
  }
  --contactsCount;
}


function formVerifyJoinContactsCompanyCategory() {
  if (document.forms.companytype.companytype.selectedIndex == 0) {
    alert("You must choose a company category.\nIf no category matches your company, you may choose 'Others'");
    return false;
  }

  return true;
}

function lingualJoin(a) {
  if (a.length == 0)
    return "";
  if (a.length == 1)
    return a[0];

  var s = a[0];
  for (var i = 1; i < a.length - 1; i++) {
    s += ', ' + a[i];
  }
  s += ' and ' + a[a.length-1];
  
  return s;
}

function formVerifyJoinContactsCompanyInformation() {
  var f = document.forms.companyinformation;
  
  var fields = [['companyname', 'Company Name'],
                ['address1',    'Address'],
                ['zipcode',     'Zip code'],
                ['city',        'City'],
                ['country',     'Country'],
                ['email',       'Contact email']
               ];

  var need = [];
  
  for (var i in fields) {
    var o = f[fields[i][0]];
    if (o.value == '' || o.value == fields[i][1])
      need.push(fields[i][1]);
  }

  if (need.length > 0) {
    var s = lingualJoin(need);
    alert("You forgot to fill out the following field" + (need.length == 1 ? '' : 's') + ":\n\n" + s + "\n\nYou must fill out all the required fields.");
    return false;
  }

  return true;
}

function updatevalid(o, n) {
  var isvalid = !(o.value == '' || o.value == o.defaultValue);
  
  var vo = document.getElementsByName('isvalid_'+o.name)[0];
  if (vo) {
    vo.style.color = isvalid ? 'lime' : 'red';
  }
}

function helpInternetExplorerFindElementsByName_sub(root, name, res) {
  for (var o = root.firstChild; o != null; o = o.nextSibling) {
    if (o.name == name)
      res.push(o);

    if (o.firstChild)
      res = helpInternetExplorerFindElementsByName_sub(o, name, res);
  }
  return res;
}

function helpInternetExplorerFindElementsByName(root, name) {
  return helpInternetExplorerFindElementsByName_sub(root, name, []);
}

function updatevalidcontact(v) {
  var c = v;
  while (c && c.parentNode && c.parentNode.id != 'joincontactscontainer')
    c = c.parentNode;

  var co = document.getElementById('joincontactscontainer');
  var no = 0;
  for (var o = co.firstChild; o != null; o = o.nextSibling) {
    if (o.nodeName.toLowerCase() == 'div') {
      if (o == c)
        break;
      no++;
    }
  }

  if (o == c) {
    var isvalid = !(v.value == '' || v.value == v.defaultValue);

    var vos = document.getElementsByName('isvalid_'+v.name);
    
    if (vos.length == 0)
      vos = helpInternetExplorerFindElementsByName(co, 'isvalid_'+v.name);

    vo = vos[no];
    if (vo) {
      vo.style.color = isvalid ? 'lime' : 'red';
    }
  }
}


