var sidebaroffset = -30;

function highlight_on(obj) { obj.style.backgroundColor = '#ffffee'; }
function highlight_off(obj) { obj.style.backgroundColor = ''; }

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

addLoadEvent(function() {
  setSidebarHeight(0);
});


function setSidebarHeight(offset) {
  if(window.innerHeight && offset != 0) {
    // This is the percentage of the height a new row takes up
    offset = 0.0415 * window.innerHeight * -1;
  }
  
  if(!offset) offset = 0;
  if(document.getElementById) {
    document.getElementById("sidebar").style.height = document.getElementById('main').offsetHeight + offset + "px";
  }
}

function deleteParent(deleteme) {
  // Can't delete the first domain field
  if(document.getElementById(deleteme) && deleteme != 'firstDomainDiv') {
    var parent = document.getElementById(deleteme);
    var grandParent = parent.parentNode;
    grandParent.removeChild(parent);
    
    if(document.getElementById('count')) {
      document.getElementById('count').value--;
    }
    if(document.getElementById('addDomain')) {
      document.getElementById('addDomain').style.display = "block";
    }
    if(document.getElementById('domainerror')) {
      document.getElementById('domainerror').innerHTML = "";      
    }    
    setSidebarHeight(sidebaroffset);
    return true;
  }     
  return false;
}
  
function validate(form) {
  validationerror = false;
  emptyerror = false;
  
  /* Cycle through all of the domains (up to 10) and check if they are correct */
  if(document.getElementsByTagName('label')) {   
    var domains = document.getElementsByTagName('input');
    for(i=domains.length-1; i>-1; i--) { // Delete the items in reverse order as they were dynamically created
      if(domains[i] && domains[i].name) {
        if(domains[i].name == 'label[]') { 

          // If domain label is empty just delete it
          if(domains[i].value == '') {
            if(domains[i].parentNode.id && !deleteParent(domains[i].parentNode.id)) {
              emptyerror = true;
            }
          } else if(!isValidDomain(domains[i].value, false)) {
              validationerror = true;
          }
        }        
      }
    }
    // If there were errors show them now
    if(validationerror) {            
      alert("Please enter a valid domain name.\n\nOne or more of the domains you have entered is invalid.");  
      highlighted = document.getElementById('firstDomainDiv'); // remember their mistake
      highlighted.style.background = '#fcc'; // highlight this error          
      return false;
    } else if(emptyerror) {
      alert("Please enter a domain name");  
      highlighted = document.getElementById('firstDomainDiv'); // remember their mistake
      highlighted.style.background = '#fcc'; // highlight this error 
      return false;          
    }    
    
  }
  if (stringtest('namediv',form.firstname,form.firstname.value,'','Please enter your First Name')) {return false;}
  if (stringtest('namediv',form.sname,form.sname.value,'','Please enter your Surname')) {return false;}
  if (stringtest('countrydiv',form.country,form.country.value,'','Please select your Country')) {return false;}
  if (stringtest('companydiv',form.company,form.company.value,'','Please enter your Company Name')) {return false;}  
  if (stringtest('phonediv',form.phone1,form.phone1.value,'','Please enter your Phone Country Code by selecting your country')) {return false;}
  if (booltest('phonediv',form.phone1,countrycode[form.country.value] != form.phone1.value,'Your phone country code should be ' + countrycode[form.country.value])) {return false;}
  if (stringtest('phonediv',form.phone2,form.phone2.value,'','Please enter your Phone Number')) {return false;}
  if (stringtest('emaildiv',form.email,form.email.value,'','Please enter an Email Address')) {return false;}
  if (booltest('emaildiv',form.email,!isValidEmail(form.email.value),'Please enter a valid Email Address')) {return false;}
  form.submit.disabled = true;
  form.submit.value = 'Please wait...';
  return true;
}

var curr = "";
function getCountryInfo(cc)
{
  var form = document.form;

  if (countrycode[cc])
  {
    form.phone1.value = countrycode[cc];
    
  }
  
  
}

/* when a page is loaded, nothing is wrong */
var highlighted = null;

/** GENERIC FUNCTIONS **/
/* tests whether two strings equal each other or not */
function stringtest(div,tofocus,field,value,message)
{ return booltest(div,tofocus,field == value, message); }

/* if the condition is true then
   a) highlights the "div"
   b) gives the "tofocus" field focus
   c) alerts the user with "message"
 */
function booltest(div,tofocus,condition,message)
{
  if (condition) {
    tofocus.focus(); // give the bad field focus
    alert(message);  // tell the users they've made a mistake
    if (highlighted) { // unhighlight the previous error
      highlighted.style.background = 'transparent';
    }
    if (div != 'none') {
      highlighted = document.getElementById(div); // remember their mistake
      highlighted.style.background = '#fcc'; // highlight this error
    }
  }
  return condition;
}

/* returns true if NO radio button has been selected within a radio set */
function validateRadio(radioset)
{
  for (var i = 0; i < radioset.length; i++) {
    if (radioset[i].checked) {return false;}
  }
  return true;
}

/* returns the value of the radio checked in a radio set */
function getRadioValue(radioset)
{
  for (var i = 0; i < radioset.length; i++) {
    if (radioset[i].checked) {return radioset[i].value;}
  }
  return '';
}

/* hides or shows the given id, display should be true or false */
function showOrHideElementById(element,display) {
  document.getElementById(element).style.display = (display) ? 'block' : 'none';
}
/* calls the above for every element in the array */
function showOrHideElementsById(elements, display) {
  for (var i = 0; i < elements.length; i++) {
    showOrHideElementById(elements[i],display);
  }
}

/** MORE SPECIFIC FUNCTIONS **/

/* sees whether the value given is unique in a input list */
function isUnique(list, value) {
  var count = 0;
  for (var i = 0; i < list.length; i++) {
    if (list[i].value == value) {
      if (count == 1) { // already existed
        return false;
      }
      else {
        count++;
      }
    }
  }
  return true;
}

/* checks whether a domain name is wellformed - www. is permitted */
function isValidDomain(domain,requiresSpace) {  
  // who cares about the space
  if (!requiresSpace && domain.match(/^(www\.|)[A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9]$/)) {
    return true;
  }
  // match all spaces but .name
  if (domain.match(/^(www\.|)[A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9]\.(com|net|org|biz|info|us|mobi|eu|com\.au|net\.au|org\.au|id\.au|asn\.au|cn|com\.cn|com\.fj|com\.hk|hk|jp|la|com\.ph|ph|com\.sg|com\.tw|tv|co\.nz|net\.nz|org\.nz|at|co\.at|be|de|it|nl|com\.ru|com\.es|ch|co\.uk|ca|cc|co\.il|co\.za|to|ws)$/)) {
    return true;
  }
  // match .names
  else {
    return domain.match(/^(www\.|)([A-Za-z0-9][A-Za-z0-9-]*[A-Za-z0-9]\.){2,2}name$/);
  }

}

/* sees whether an email is wellformed or not */
function isValidEmail(email) {
  return email.match(/^[0-9a-zA-Z]([-_.]?[0-9a-zA-Z])*@[0-9a-z]([-.]?[0-9a-z])*\.[a-z]{2,4}$/);
}

/* checks whether a given date is valid or not */
function isValidDate(day, month, year)
{
  // strip leading zeros from day month and year so we can treat them as numbers
  day = day.replace(/^0+/,'');
  month = month.replace(/^0+/,'');
  year = year.replace(/^0+/,'');

  // validate february (and a few others besides)
  var isLeapYear = (year % 4 == 0);
  if (day <= 28) {return true;}
  if (isLeapYear && day == 29) {return true;}
  if (month == 2) {return false;}

  // validate 30 day months
  if (day <= 30) {return true;}
  if (month == 4 || month == 6 || month == 9 || month == 11) {return false;}

  // validate 31 day months
  if (day <= 31) {return true;}

  // everything else should be bogus
  return false;
}

/* returns 1 if the date is after today
   returns 0 if the date IS today 
   returns -1 if the date is before today */
function compareDate(year, month, day)
{
  // strip leading zeros from day month and year so we can treat them as numbers
  if (year) year = year.replace(/^0+/,'');
  if (month) month = month.replace(/^0+/,'');
  if (day) day = day.replace(/^0+/,'');

  // get todays date
  var today = new Date();

  // check if it's before or after today - introducing year 3000 bug - bad
  if (year && year > today.getFullYear() - 2000) return 1;
  if (year && year < today.getFullYear() - 2000) return -1;
  if (month && month > today.getMonth() + 1) return 1;
  if (month && month < today.getMonth() + 1) return -1;
  if (day && day > today.getDate()) return 1;
  if (day && day < today.getDate()) return -1;

  // if all the tests above failed - then it must be today
  return 0;
}

/* make sure the user has reached a 18 years - ?maybe make age an input */
function isAtleast18(day, month, year)
{
  // strip leading zeros from the day month and year
  day = day.replace(/^0+/,'');
  month = month.replace(/^0+/,'');
  year = year.replace(/^0+/,'');

  // get todays date
  var today = new Date();

  // see whether they're clearly over or under 18
  if ((today.getFullYear() - year) > 18) {return true;}
  if ((today.getFullYear() - year) < 18) {return false;}

  // check the month
  if (today.getMonth() >= month) {return true;}

  // check the day (+ month)
  if (today.getMonth() + 1 == month && today.getDate() >= day) {return true;}

  // not yet 18
  return false;
}

/* somebody thinks they've broken a world record */
function isRidiculousAge(year)
{
  var today = new Date();
  if (today.getFullYear() - year > 129) {return true;}
  return false;
}

/* returns true if the credit card number is invalid
  - assumes non-numeric characters have been stripped */
function isBadCreditCardNumber(cardtype, cardnumber)
{
  if (cardtype == 'VISA') {
    if (cardnumber.match(/^4([0-9]{12,12}|[0-9]{15,15})$/)) {return false;}
  }
  else if (cardtype == 'MASTERCARD') {
    if (cardnumber.match(/^5[1-5][0-9]{14,14}$/)) {return false;}
  }
  else if (cardtype == 'AMEX') {
    if (cardnumber.match(/^3[47][0-9]{13,13}$/)) {return false;}
  }
  else if (cardtype == 'DINERS') {
    if (cardnumber.match(/^3[068][0-9]{12,12}$/)) {return false;}
  }
  else if (cardtype == 'BANKCARD') {
    if (cardnumber.match(/^5610[0-9]{12,12}$/)) {return false;}
  }
  return true;
}

var count = 1;              // the number of domains to register interest in

/* Create another domain search form */
function addAnotherDomainField() {

    
    // Get the count figure
    if(document.getElementById('count')) {
      count = document.getElementById('count').value;      
      document.getElementById('count').value++;
    }

    
    // Create the new form element
    if(document.getElementById('domaindiv')) {
      
      // This method is preferred as it doesn't delete the existing form input
      if(document.createElement) {
        // The wrapper div
        var div = document.createElement("div");
        div.className = "anotherdomain";
        div.id = "anotherdomain" + count;        
        
        // The label
        var label = document.createElement("label");
        //label.for = "label" + count;              // IE hates this
        label.className = "formlabel";
        label.innerHTML = "www.";
        
        // The required Span '*' 
        var span = document.createElement("span");
        span.innerHTML = "*";
    
        label.appendChild(span);
            
        // The input
        var input = document.createElement("input");
        input.type = "text";
        input.size = 43;
        input.id ="label" + count;
        input.maxlength = 15;
        input.name = "label[]";
        
        // The .asia span
        var asiaspan = document.createElement("span");
        asiaspan.className = "extensionspan";
        asiaspan.innerHTML = ".asia";


        // Add elements to form
        label.insertBefore(span,label.firstChild);
        div.appendChild(label)
        div.appendChild(input);    
        div.appendChild(asiaspan);
        
                
        // The delete option (not in IE)
        var deletelink = null;
        
        if(label.parentNode) {
          var deletelink = document.createElement("a");
          deletelink.href = "#contact";
          deletelink.style.padding = "5px";
          deletelink.innerHTML = "remove";
          

          if(window.addEventListener) { // everything but IE
            deletelink.addEventListener("click",function() {deleteParent(div.id);},false);      
          } else {
            deletelink.attachEvent("onclick",function() {deleteParent(div.id);});      
          }
          
          div.appendChild(deletelink);
        }
        
        // Finally add the element
        document.getElementById("domaindiv").appendChild(div);
      } else {
        // This method is easier but removes information within the existing text input fields.
        // So everytime they click "add another domain", they lose what they put in. 
        // i.e. They will have to click n times first, then enter domains

        // Update: works fine with IE and not firefox. But still not proper DOM :)
        document.getElementById('domaindiv').innerHTML = document.getElementById('domaindiv').innerHTML + "<div id='anotherdomain'><label for='label"+count+"' class='formlabel'><span>*</span> www.</label><input value='' name='label[]' type='text' size='43' id='label"+count+"' maxlength='15'/><span style='font-size:10px; color:#666;'>.asiaSADF</span></div>";  
      }
      // If there are now 10 fields showing then remove the 'add more' button
      if(count >= 9 && document.getElementById('count')) {
        if(document.getElementById('addDomain')) {
          document.getElementById('addDomain').style.display = "none";
        }
        if(document.getElementById('domainerror')) {
          document.getElementById('domainerror').innerHTML = "<p>You cannot register for more than 10 domains.</p>";      
        }
      }   
      setSidebarHeight(0);
      
    }

}

/* Create another .tel domain search form */
function addAnotherTelDomainField() {
    
    // Get the count figure
    if(document.getElementById('count')) {
      count = document.getElementById('count').value;      
      document.getElementById('count').value++;
    }
		
		for (i = 1; i < count; i++) {
			if(!document.getElementById('label' + i)) {
				count = i;
				break;
			}
		}

    // Create the new form element
    if(document.getElementById('domaindiv')) {
			
      // This method is preferred as it doesn't delete the existing form input
      if(document.createElement) {
        // The wrapper div
        var div = document.createElement("div");
        div.className = "anotherdomain";
        div.id = "anotherdomain" + count;        
        
        // The label
        var label = document.createElement("label");
        //label.for = "label" + count;              // IE hates this
        label.className = "formlabel";
        label.innerHTML = "www.";
        
        // The required Span '*' 
        var span = document.createElement("span");
        span.innerHTML = "";
    
        label.appendChild(span);
            
        // The input
        var input = document.createElement("input");
        input.type = "text";
        input.size = 43;
        input.id ="label" + count;
        input.maxlength = 15;
        input.name = "label[]";
        
        // The .tel span
        var telSpan = document.createElement("span");
        telSpan.className = "extensionspan";
        telSpan.innerHTML = ".tel";


        // Add elements to form
        label.insertBefore(span,label.firstChild);
        div.appendChild(label)
        div.appendChild(input);    
        div.appendChild(telSpan);
        
                
        // The delete option (not in IE)
        var deletelink = null;
        
        if(label.parentNode) {
          var deletelink = document.createElement("a");
          deletelink.href = "javascript: return false;";
          deletelink.style.padding = "5px";
          deletelink.innerHTML = "remove";
          

          if(window.addEventListener) { // everything but IE
            deletelink.addEventListener("click",function() {deleteParent(div.id); return false;},false);      
          } else {
            deletelink.attachEvent("onclick",function() {deleteParent(div.id); return false;});      
          }
          
          div.appendChild(deletelink);
        }
        
        // Finally add the element
        document.getElementById("domaindiv").appendChild(div);
      } else {
        // This method is easier but removes information within the existing text input fields.
        // So everytime they click "add another domain", they lose what they put in. 
        // i.e. They will have to click n times first, then enter domains

        // Update: works fine with IE and not firefox. But still not proper DOM :)
        document.getElementById('domaindiv').innerHTML = document.getElementById('domaindiv').innerHTML + "<div id='anotherdomain'><label for='label"+count+"' class='formlabel'><span>*</span> www.</label><input value='' name='label[]' type='text' size='43' id='label"+count+"' maxlength='15'/><span style='font-size:10px; color:#666;'>.tel</span></div>";  
      }
      // If there are now 10 fields showing then remove the 'add more' button
      if(count >= 9 && document.getElementById('count')) {
        if(document.getElementById('addDomain')) {
          document.getElementById('addDomain').style.display = "none";
        }
        if(document.getElementById('domainerror')) {
          document.getElementById('domainerror').innerHTML = "<p>You cannot register for more than 10 domains.</p>";      
        }
      }   
      setSidebarHeight(0);
    }
}
		
	/*Toggles the tips div*/
	function showTip(pelem, name) {
		var elem = document.getElementById(name);
		elem.style.position = "absolute";
		//pelem.offsetTop + 
		var elHeight = pelem.style.height;
		elem.style.top = elHeight + "px";
		//offsetLeft + 
		var elWidth = pelem.style.width;
		elem.style.left = elWidth + "px";
		elem.style.display = "block";
		return true;
	}
	
	function hideTip(name) {
		var elem = document.getElementById(name);
		elem.style.display = "block";
		return true;
	}