// Originally from
// <http://simon.incutio.com/archive/2004/05/26/addLoadEvent>
// @(#) $Id: public.js 79373 2009-11-20 17:11:42Z simon $
function addLoadEvent(func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    } else {
        window.onload = function() {
           if (oldonload){ 
            oldonload();
            }
            func();
        }
    }
}

function token_field_name(field) {

  if (field=='account_type_id') {
    return 'Organization Type';
  }else if (field=='country_id') {
    return 'Country';
  }else if (field=='contact_name') {
    return 'Surname';
  }else if (field=='contact_forename') {
    return 'First name';
  }else if (field=='organisation') {
    return 'Organization Name';
  }else if (field=='email'){
    return 'Email address';
  } else if (field=='sources'){
    return 'How did you acquire your copy of The Statesman\'s Yearbook';
  }else { return field; }
}
function check_token_form(form) {

  var $ok = check_required_fields(form, 'account_type_id', 'country_id',
				  'contact_name', 'contact_forename', 'organisation', 'email', 'sources');
    if ($ok == false) return false;

    // nasty case - if 'sources=1' must have 'suppliers'
    if (document.getElementById('sources').value == 1 &&
        !document.getElementById('suppliers').value) {
          alert ("Please fill in the required field (Name of supplier/wholesaler)");
          return false;
    }
    //nastier case - 'sources=1' and 'suppliers=Other' Must have supplier notes
    var $suppliers =document.getElementById('suppliers');
    if (document.getElementById('sources').value == 1 &&
	$suppliers.options[$suppliers.selectedIndex].text=='Other (please specify)' &&
        !document.getElementById('supplier_notes').value)
         {
          alert ("Please specify the supplier (Supplier Notes)");
          return false;
    }

    $ok =  check_email(form);
    if ($ok == false) return false;

    $ok = check_userpass(form);
    if ($ok == false) return false;

    $ok = check_allowed_ips(form);
     if ($ok == false) return false;
   
     $ok = check_userorip();

    return $ok;

}
function check_userorip(){
  //if we have an account, no need to get auth info
  if (document.getElementById('acc_id')){
       return true;
   }
   var divuserorip=document.getElementById('divuserorip');
   if (divuserorip.style.display=='block'){
     alert("please set your authentication information");
     return false;
   }
   return true;

}

function check_free_access_code (access_code) {
  return true;
}

function check_required_fields () {
    foundempty=0;
    form= arguments[0];
    for (i=1; i<arguments.length; i++) {
      if (!document.getElementById(arguments[i])) {
        continue;
      }
      if (!document.getElementById(arguments[i]).value) {
	alert ("Please fill in the required fields. \"" + token_field_name(arguments[i]) + "\" is empty.");
          foundempty++;
          break;
      }
    }
    return foundempty ? false : true;
}

function check_email (form) {
  if (!document.getElementById("email")) { // dont' check if not present on form
        return true;
    }
  var email = document.getElementById("email").value;
    if ((email == "") || (email.indexOf ('@') == -1) || (email.indexOf ('.') == -1)) {
        alert ("Please enter a valid email address");
        return false;
    }else if(email.indexOf (',') != -1){
      alert("Email addresses cannot contain commas, please enter a single valid email address");
      return false;
    } else {
       return true;
    }
}

function check_userpass (form) {
    var divuserpass=document.getElementById('divuserpass');
    if (divuserpass.style.display =='none'){ // dont' check if not present on form
        return true;
    }
    var input = form.userpass.value;
    var lines = input.split(/[\n\r]+/);
    for (var i=0; i < lines.length; i++) {
        if ( ! isValidUserpass(lines[i])) {
            return false;
        }
    }
    return true;
}

function check_allowed_ips (form) {
    var divallowedips = document.getElementById('divallowedips');
    if (divallowedips.style.display =='none'){ // dont' check if not present on form
        return true;
    }
    var input = form.allowed_ips.value;
    var lines = input.split(/[\n\r]+/);
    for (var i=0; i < lines.length; i++) {
        if (! isValidAllowedIP(lines[i])) {
            return false;
        }
    }
    return true;
}

function isValidUserpass (input) {
  if (!input){
    alert("please enter username or password")
       return false;
  }
    var slash = /\//;
    var inputparts=[];
    if (slash.test(input)) {
        inputparts = input.split(slash);
        if (inputparts[0].length < 6
         || inputparts[1].length < 6) {
            alert (input + " : Username and password must be at least 6 characters");
            return false;
        }
    } else {
        alert ("Please check the format of the username field");
        return false;
    }
    return true;
}
function isValidAllowedIP (ipaddr) {

    if (!ipaddr) {
       alert( "Please enter an IP address." );
       return false;
    }

    var result = ipaddr.match( 
        /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(\/(\d{1,2}))?$/
    );

    var isValid=1;
    if (!result){
        isValid=0;
    } else {
        if (result[6] && parseInt(result[6]) > 32) isValid = 0;
        if (result[6] && parseInt(result[6]) < 9) {
            alert("The IP range you have input exceeds the limit for this licence. Please resubmit a smaller range, or alternatively contact us to request a full site licence.");
            return false;
        }
        var i;
        for ( i = 1; i < 5; i++ ) {
            if ( parseInt(result[i]) > 255 ) isValid = 0;
        }
    }
    if (!isValid) {
        alert("Please check the format of the IP field. Expected format is a single IP address (e.g. 192.168.2.11) or a CIDR range if you require more than one IP address. Please contact your organisation's technical support if you are unsure of the exact values to use.");
        return false;
    }
    return true;
}
function focusUsername() {
	if (!document.getElementById) return;
	if (!document.getElementById('username')) return;
	document.getElementById('username').focus();
}

addLoadEvent(focusUsername);

function setUserOrIP(orgType) {
   var divuserorip=document.getElementById('divuserorip');
   var divuserpass=document.getElementById('divuserpass');
   var divallowedips=document.getElementById('divallowedips');
   var labelorgname=document.getElementById('orgname').firstChild;
   if ( orgType.value == ''){
     divuserorip.style.display='block';
     divuserpass.style.display='none';
     divallowedips.style.display='none';
   } else if ( parseInt(orgType.value) == 2 ||
               parseInt(orgType.value) == 4 ||
               parseInt(orgType.value) == 5 || 
               parseInt(orgType.value) == 6 || 
               parseInt(orgType.value) == 19 || 
               parseInt(orgType.value) == 20 || 
               parseInt(orgType.value) == 21 || 
               parseInt(orgType.value) == 22 || 
               parseInt(orgType.value) == 23 
              ){
       divuserorip.style.display='none';
       divuserpass.style.display='block';
       divallowedips.style.display='none';
       labelorgname.nodeValue='Your account name';
  }else {
       divuserorip.style.display='none';
       divuserpass.style.display='none';
       divallowedips.style.display='block';
       labelorgname.nodeValue='Organization name';
   }
}

function popup_link(URL){
  window.open( URL, null, "resizable=1,height=600,width=800,scrollbars=1"); 
}

function setupSuppliersField (sourceControl) {
    var regsupp = document.getElementById('regsuppliers');
    if (sourceControl.selectedIndex == 1) {
        regsupp.style.display = 'block';
    }
    else {
        regsupp.style.display = 'none';
    }
}

function checkOther(supplier){
  if (supplier.options[supplier.selectedIndex].text=='Other (please specify)'){
      document.getElementById('suppliernoteslabel').innerHTML='Supplier Notes<span class="mandatory">*</span>';
  }else{
    document.getElementById('suppliernoteslabel').innerHTML='Supplier Notes (where applicable)';
  }
}

function initRevealFields() {

    // when 'sources/1' selected, reveal the 'suppliers' field
	if (!document.getElementById) return;
    var sourceControl = document.getElementById('sources');
	if (!sourceControl) return;
    setupSuppliersField(sourceControl);
 
    document.getElementById('sources').onchange = function() {
        setupSuppliersField(this);
        }

    var suppliersf = document.getElementById('suppliers');
	if (!suppliersf ) return;

   checkOther(suppliersf);
 
   document.getElementById('suppliers').onchange = function(){
      checkOther(this);
    }


}
// addLoadEvent(initRevealFields);

// Seems to be a problem trying to call addLoadEvent when
// <body onload="load_worldmap"> is used
function public_onload_setup() {
    initRevealFields();
    var sourceControl = document.getElementById('sources');
    if (!sourceControl) return;
    setupSuppliersField(sourceControl);
}

// vim: set ai et sw=4 :
