// Allows multiple functions to load

function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      oldonload();
      func();
    }
  }
}


// Clears & validates forms

function resetFields(whichform) {
  for (var i=0; i<whichform.elements.length; i++) {
    var element = whichform.elements[i];
    if (element.type == "submit") continue;
    if (!element.defaultValue) continue;
    element.onfocus = function() {
    if (this.value == "enter e-mail here") {
      this.value = "";
     }
    }
    element.onblur = function() {
      if (this.value == "") {
        this.value = "enter e-mail here";
      }
    }
  }
}

function validateForm(whichform) {
  for (var i=0; i<whichform.elements.length; i++) {
    var element = whichform.elements[i];
    if (element.className.indexOf("requ") != -1) {
      if (!isFilled(element)) {
        alert("Please complete all required fields");
        return false;
      }
    }
    if (element.className.indexOf("reqmail") != -1) {
      if (!isFilled(element))  {
        alert("Please enter your e-mail");
        return false;
      }
      if (!isEmail(element)) {
        alert("Please enter your e-mail again - it doesn\'t appear to be correct \n(If the problem persists please e-mail us directly at info@webcredible.co.uk)");
        return false;
      }
    }
    if (element.className.indexOf("reqfrmail") != -1) {
      if (!isEmail(element)) {
        alert("Please enter your friend\'s e-mail again - it doesn\'t appear to be valid \n(if the problem persists please e-mail us directly at info@webcredible.co.uk)");
        return false;
      }
    }
    if (element.className.indexOf("email") != -1) {
      if (!isEmail(element)) {
        alert("Please enter your e-mail again - it doesn\'t appear to be valid \n(If the problem persists please e-mail us directly at info@webcredible.co.uk)");
        return false;
      }
    }
  }
  return true;
}

function isFilled(field) {
  if (field.value.length < 1 || field.value == field.defaultValue) {
    return false;
  } else {
    return true;
  }
}

function isEmail(field)
{
    // you could add a test to see if the brower support regular expression or not here
    if (RegExp) {
        return checkEmail(field.value);
    } else {
      if (field.value.indexOf("@") == -1 || field.value.indexOf(".") == -1) {
        return false;
      } else {
        return true;
      }
   }
}

function checkEmail(addr)
{
    var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,9}(?:\.[a-z]{2})?)$/i
    return filter.test(addr);
}

function prepareForms() {
  for (var i=0; i<document.forms.length; i++) {
    var thisform = document.forms[i];
    resetFields(thisform);
    thisform.onsubmit = function() {
      return validateForm(this);
    }
  }
}


// Opens PDF links in new windows

function doPopups()
{
 if (!document.getElementsByTagName) return false;
 var links = document.getElementsByTagName("a");
 for (var i=0; i < links.length; i++) {
  if (links[i].href.indexOf('.pdf') !== -1) {
   links[i].onclick =
    function() {
     window.open(this.href,'popper','resizable,scrollbars');
     return false;
    }
    links[i].title += "\n(opens in a new window)";
    var img = document.createElement("img");
    img.setAttribute("src", "/i/new-win-icon.gif");
    img.setAttribute("alt", "(opens in a new window)");
    links[i].appendChild(img);
  }
 }
}

// Opens map in new window
function map() {
 if (!document.getElementsByTagName) return false;
 var links = document.getElementsByTagName("a");
 for (var i=0; i < links.length; i++) {
  if (links[i].className.match('map')) {
   links[i].onclick =
    function() {
     window.open(this.href,'map','height=450,width=375,resizable');
     return false;
    }
    links[i].title = "(opens in a new window)";
    var img = document.createElement("img");
    img.setAttribute("src", "/i/new-win-icon.gif");
    img.setAttribute("alt", "(opens in a new window)");
    links[i].appendChild(img);
  }
 }
}

// Opens virtual tour in new window

function doVirtual() {
 if (!document.getElementsByTagName) return false;
 var links = document.getElementsByTagName("a");
 for (var i=0; i < links.length; i++) {
  if (links[i].className.match('virtual')) {
   links[i].onclick =
    function() {
     window.open(this.href,'popper','width=390,height=560,resizable,scrollbars');
     return false;
    }
    links[i].title = "(opens in a new window - may take up to two minutes to download on a dial-up modem)";
    var img = document.createElement("img");
    img.setAttribute("src", "/i/new-win-icon.gif");
    img.setAttribute("alt", "(opens in a new window)");
    links[i].appendChild(img);
  }
 }
}


// Opens tell a friend in new window

function doTellFriend() {
 if (!document.getElementsByTagName) return false;
 var links = document.getElementsByTagName("a");
 for (var i=0; i < links.length; i++) {
  if (links[i].className.match('friend')) {
   links[i].onclick =
    function() {
     window.open(this.href,'popper','width=410,height=540,resizable,scrollbars');
     return false;
    }
    links[i].title += "(opens in a new window)";
    var img = document.createElement("img");
    img.setAttribute("src", "/i/new-win-icon.gif");
    img.setAttribute("alt", "(opens in a new window)");
    links[i].appendChild(img);
  }
 }
}


// Cancel links with # in them

function cancelLink() {
 if (!document.getElementsByTagName) return false;
 var links = document.getElementsByTagName("a");
 for (var i=0; i < links.length; i++) {
  if (links[i].href.match(/#$/)) {
   links[i].onclick =
    function() {
     return false;
    }
  }
 }
}


// Puts rounded corners on to menu items

function roundedCorners() {
  if (!document.getElementsByTagName) return false;
  var divs = document.getElementsByTagName('div');
  var rounded_divs = [];
  for (var i = 0; i < divs.length; i++) {
    if (/\bbox\b/.exec(divs[i].className)) {
      rounded_divs[rounded_divs.length] = divs[i];
    }
  }
  for (var i = 0; i < rounded_divs.length; i++) {
    var original = rounded_divs[i];
    original.className = original.className.replace('box', '');
    var div2 = document.createElement('div');
    div2.className = 'box2';
    original.parentNode.replaceChild(div2, original);
    for (var ii = 3; ii < 9; ++ii) {
        eval("var div" + ii + " = document.createElement('div');");
    }
    for (var iii = 2; iii < 8; ++iii) {
        eval("div" + iii + ".appendChild(div" + (iii + 1) + ");");
    }
    div8.appendChild(original);
  }
}


// Turns e-mail addresses into mailtos

function changeMail() {
 if (!document.getElementsByTagName) return false;
 var span = document.getElementsByTagName("span");
 for (var i=0; i < span.length; i++) {
  if (span[i].className.match('email')) {
   var innerspan = span[i].getElementsByTagName("span")[0].firstChild.nodeValue;
   span[i].innerHTML = "<a href='mailto:"+innerspan+"@webcredible.co.uk'>"+innerspan+"@webcredible.co.uk"
  }
 }
}

// Link displayer for printing

function footnoteLinks(containerID, targetID)
{
      if (!document.getElementById || !document.getElementsByTagName || !document.createElement) return false;
      if (!document.getElementById(containerID) || !document.getElementById(targetID)) return false;

      var container = document.getElementById(containerID);
      var target    = document.getElementById(targetID);
      var h2        = document.createElement('h2');
      addClass.apply(h2,['printOnly']);

      var h2_txt    = document.createTextNode('Links');
      h2.appendChild(h2_txt);

      var coll = container.getElementsByTagName('*');
      var ol   = document.createElement('ol');
      addClass.apply(ol,['printOnly']);

      var myArr = [];
      var thisLink;
      var num = 1;
      for (var i=0; i< coll.length; i++) {
        var thisClass = coll[i].className;
        if ( (coll[i].getAttribute('href') || coll[i].getAttribute('cite')) && (thisClass == '' || thisClass.indexOf('nop') == -1)) {
          thisLink = coll[i].getAttribute('href') ? coll[i].href : coll[i].cite;
          var note = document.createElement('sup');
          addClass.apply(note,['printOnly']);
          var note_txt;
          var j = inArray.apply(myArr,[thisLink]);
          if ( j || j===0 ) {
            note_txt = document.createTextNode(j+1);
          } else {
            var li     = document.createElement('li');
            var li_txt = document.createTextNode(thisLink);
            li.appendChild(li_txt);
            ol.appendChild(li);
            myArr.push(thisLink);
            note_txt = document.createTextNode(num);
            num++;
          }
          note.appendChild(note_txt);
          if (coll[i].tagName.toLowerCase() == 'blockquote') {
            var lastChild = lastChildContainingText.apply(coll[i]);
            lastChild.appendChild(note);
          } else {
            coll[i].parentNode.insertBefore(note, coll[i].nextSibling);
          }
        }
      }
      target.appendChild(h2);
      target.appendChild(ol);
      addClass.apply(document.getElementsByTagName('html')[0],['noted']);
      return true;
}

 function doFootNoteLinks()
 {
    footnoteLinks('content','content');
 }

   function inArray(needle) {
      for (var i=0; i < this.length; i++) {
        if (this[i] === needle) {
          return i;
        }
      }
      return false;
    }
    function addClass(theClass) {
      if (this.className != '') {
        this.className += ' ' + theClass;
      } else {
        this.className = theClass;
      }
    }
    function lastChildContainingText() {
      var testChild = this.lastChild;
      var contentCntnr = ['p','li','dd'];
      while (testChild.nodeType != 1) {
        testChild = testChild.previousSibling;
      }
      var tag = testChild.tagName.toLowerCase();
      var tagInArr = inArray.apply(contentCntnr, [tag]);
      if (!tagInArr && tagInArr!==0) {
        testChild = lastChildContainingText.apply(testChild);
      }
      return testChild;
    }
function linkIncrease() {
 if (!document.getElementsByTagName || !document.getElementById || !document.getElementById("home") || !document.getElementById("ad")) return false;

 var ad = document.getElementById("ad");
 var div = ad.getElementsByTagName("div");
 var link = ad.getElementsByTagName("a");
 var para = ad.getElementsByTagName("p");

   for (var i=0; i < div.length; i++) {

    div[i].onmouseover = function () {
     this.style.cursor = "pointer";
     this.style.background = "#c4130d";
     link[0].style.color = "#fff";
     para[0].style.color = "#fff";
    }
    div[i].onmouseout = function () {
     this.style.background = "#f3eaef";
     link[0].style.color = "#c4130d";
     para[0].style.color = "#000";
    }
    div[i].onclick = function () {
     window.location = link[0].href;
  }
 }
}
addLoadEvent(map);
addLoadEvent(linkIncrease);
addLoadEvent(prepareForms);
addLoadEvent(doPopups);
addLoadEvent(doVirtual);
addLoadEvent(doTellFriend);
addLoadEvent(cancelLink);
addLoadEvent(roundedCorners);
addLoadEvent(changeMail);
addLoadEvent(doFootNoteLinks);

