function swap_product_html (html) {
    if (document.main.site_id.value) {
        if (html) {
           document.getElementById('part2').innerHTML = html;
        } else {
           // pe_id must be initialised
           document.getElementById('part2').innerHTML = 
           '<input type="hidden" name="pe_id" value="' + document.main.site_id.value + '" />';
        }
    } else {
           document.getElementById('part2').innerHTML = '';
    }
}

function check_form (forceselect) {
    if (forceselect && document.main.site_id && ! document.main.site_id.value) {
        alert ("Please choose a site.");
        return false;
    }
    if (document.main.content_unit_id != undefined) {
         showalert=1;
         if  (! document.main.content_unit_id.length) {
              if (document.main.content_unit_id.checked == true) {
                   showalert=0;
              }
         } else {
            for (i=0; i<document.main.content_unit_id.length; i++) {
                if (document.main.content_unit_id[i].checked == true) {
                    showalert=0;
                    break;
                }
            }
        }
        if (showalert && forceselect) {
            alert ("Please tick one or more titles.");
            return false;
        }

    } else if (forceselect && ! document.main.pe_id.value) {
    // only check for missing product for non pick n mix
        alert ("Please choose a product.");
        return false;
   }
    return true;
}


function get_org_size() {

    id = document.main.account_type_id.value;
    if (id) {
        showit('show_submit',1);
    } else {
        showit('show_submit',0);
    }
    
    showit('show_sites_worldwide',0);
    showit('show_org_size_text', 0);
    showit('show_org_size', 0);

    
    if (org_size_array[id] != undefined) { // 5,6,7
        get_org_size_options(id);
        showit('show_sites_worldwide',0);
        showit('show_concurrency',1);
        showit('show_concurrency_dropdown',0);
        showit ('show_org_size', 1);
        // expand if necessary
        for (i=0; i < document.main.concurrency.length; i++) {
            if (document.main.concurrency[i].value == 'use_dropbox'
                && document.main.concurrency[i].checked
                ) {
                    showit('show_concurrency_dropdown',1);
            }
        }
        showit('show_publication_medium_id',1);
        showit('show_duration',1);
    } else if (id == 3)  { // consortia
    // nothing extra to show
    } else {
        document.main.org_size_id.value="7"; // other
         if (id) {
            showit('show_sites_worldwide',1);
         }
        showit('show_concurrency',0);
        showit('show_concurrency_dropdown',0);
        showit('show_publication_medium_id',0);
        showit('show_duration',0);
    }
    // but override for schools
    if (id == 18) { // schools
        document.main.org_size_id.value=16;
    }
}

function get_org_size_options (account_type_id) {
    output = '<span class="field"><b>Access by Organisation Size (full-time enrolment)</b><select class="drop" name="org_size_id" onchange="large_org_size(\'show_org_size_text\')">';
    for (i=0; i<org_size_array[id].length-1; i+=3) {
        selected= org_size_array[id][i+2] ? 'selected="selected" ' : '';
        output += '<option ' + selected + 'value="' + org_size_array[id][i] + '">' + org_size_array[id][i+1] + '</option>';
    }
    output += '</select></span><br />';
    document.getElementById('show_org_size').innerHTML=output;
}

function large_org_size (div) {
    mylength=document.main.org_size_id.length - 1;
    if (document.main.org_size_id.selectedIndex == mylength) {
        showit(div, 1);
    } else {
        showit(div, 0);
    }
}

function showit (id, show) {
    if (! document.getElementById(id)) {
    // id doesn't exist
    return true;
    }
    if (show) {
        document.getElementById(id).style.display='inline';
    } else {
        document.getElementById(id).style.display='none';
    }
    return true;
}


function toggle_all () {
    // force an array if only one content_unit_id
    if  (! document.main.content_unit_id.length) {
        bool = document.main.content_unit_id.checked == true ? 'false' : 'true';
        eval ('document.main.content_unit_id.checked = ' + bool);
        document.main.toggle.value=
                document.main.content_unit_id.checked ? 'Deselect all' : 'Select all';
    } else {
        bool = document.main.content_unit_id[0].checked == true ? 'false' : 'true';
        var mylength=document.main.content_unit_id.length;
        for (i=0; i<mylength; i++) {
                eval ('document.main.content_unit_id[i].checked = ' + bool);
        }
        document.main.toggle.value=
                document.main.content_unit_id[0].checked ? 'Deselect all' : 'Select all';
    }
}

function check_required_fields () {
    foundempty=0;
    for (i=0; i<arguments.length; i++) {
        eval ('var isundef=0; if (document.main.' + arguments[i] + '== undefined) { isundef++ } ');
        if (isundef) { // if the field doesn't appear on the page, don't validate it
            continue;
        }
        eval ('myval = document.main.' + arguments[i] + '.value');
        if (! myval) {
            alert ("Please fill in the required fields (" + arguments[i] + ")");
            foundempty++;
            break;
        } 
    }
    return foundempty ? false : true;
}

function check_email () {
    if (document.main.email == undefined) { // dont' check if not present on form
        return true;
    }
    var email = document.main.email.value;
    if ((email == "") || (email.indexOf ('@') == -1) || (email.indexOf ('.') == -1)) {
        alert ("Please enter a valid email address");
        return false;
    } else {
       return true;
    }
}

function check_ips () {
    if (document.main.allowed_ips == undefined) { // dont' check if not present on form
        return true;
    }
    
    var input = document.main.allowed_ips.value;

    var lines=[];
    lines = input.split(/[\n\r]/);
    for (var i=0; i < lines.length; i++) {
        if (lines[i] != '' && ! isValidIP(lines[i])) {
            return false;
        }
    }
    return true;
}

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

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



function isValidIP (input) {
    var re = /\//;
    var inputparts=[];
    if (isValidIPaddressSyntax(input)) {
        // skip to range check
        inputparts[0] = input;
    } else if (re.test(input)) {
        // contains /
        inputparts = input.split(re);
        if (! (
            isValidIPaddressSyntax (inputparts[0]) &&
            inputparts[1] != '' &&
            ! isNaN ( inputparts[1]) &&
            inputparts[1] >=0 &&
            inputparts[1] <=32
           )) {
            alert ("Ip range " + input + " has an incorrect format");
            return false;
        }
    } else {
        alert ( input + " :unknown ip format");
        return false; // unknown format
    }
    // format is good
    // check the address or the range
    // does not fall within disallowed networks

    
    var lowerinput='';
    var upperinput='';
    if (inputparts[1] != undefined && inputparts[1]) {
        // input is cidr
        lowerinput = aton (ntoa(netaddr(inputparts[0],inputparts[1])));
        upperinput = aton (ntoa(broadcast(inputparts[0],inputparts[1])));
    } else {
        // input is ip address
        lowerinput = upperinput = aton (ntoa(netaddr(inputparts[0],32))); 
    }
    
    // convert disallowed ranges to 32-bit numbers;
    var disallowed = ['10.0.0.0/8','127.0.0.0/8','172.16.0.0/12','192.168.0.0/16','224.0.0.0/3'];
    
    for (var i=0; i < disallowed.length; i++) {
        var disallowedparts = disallowed[i].split(re);
        var lower = aton (ntoa(netaddr(disallowedparts[0],disallowedparts[1])));
        var upper = aton (ntoa(broadcast(disallowedparts[0],disallowedparts[1])));
        // see if the disallowed range appears anywhere in the input range
        if (
            (lowerinput >= lower && lowerinput <= upper) 
            ||
           (upperinput >= lower && upperinput <= upper)
           )
                {
                    alert (input + " falls within a disallowed ip range (" + disallowed[i] + ")");
                    return false;
        }
    }
    return true; // made it through all tests
}



function isValidIPaddressSyntax (ipaddr) {
    var re = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
    if (re.test(ipaddr)) {
        var parts = ipaddr.split(".");
        if (parseInt(parseFloat(parts[0])) == 0) { 
            return false;
        }
        for (var i=0; i < parts.length; i++) {
            if (parseInt(parseFloat(parts[i])) > 255) { 
                return false;
            }
        }
        return true;
   } else {
        return false;
   }
}


function aton(ipstr) {
    var ipint = 0;
    var ipary = [];

    ipary = ipstr.split(".");
    ipint = (ipary[0] * 256 * 256 * 256) +
            (ipary[1] * 256 * 256) +
            (ipary[2] * 256) +
            (ipary[3] * 1);             // Convert to number.  Like awk...
    return ipint;
}


/*
 * Create a mask of a specified length.
 */
function mask(len) {
    var bits = 0;

    // Count up, but really work down from bit 31.
    for (var b=0; b < len; b++) {
        bits |= (1 << (31 - b));
    }
    return bits;
}

/*
 * Return the broadcast address of a CIDR network.
 */
function broadcast(net, prefixlen) {
    var netmask = mask(prefixlen);

    return (aton(net) | ~netmask);
}

/*
 * Return the network address of a CIDR network.
 */
function netaddr(net, prefixlen) {
    var netmask = mask(prefixlen);

    return (aton(net) & netmask);
}

/*
 * Convert an Integer to an IP address string.
 */
function ntoa(ipint) {
    var ipary = [];
    var ipstr = "";

    // Use right shift with zero fill, to avoid coming out with a
    // negative number...
    ipary[0] = (ipint & 0xff000000) >>> 24;
    ipary[1] = (ipint & 0x00ff0000) >> 16;
    ipary[2] = (ipint & 0x0000ff00) >> 8;
    ipary[3] = (ipint & 0x000000ff);

    ipstr = ipary[0] + "." +
            ipary[1] + "." +
            ipary[2] + "." +
            ipary[3];
    return ipstr;
}


function check_start_date() {
    var DateField = document.main.start_date;
    
    if (DateField == undefined) { // don't check if it's not present on the form
        return true
    }
    var leap = 0;
    var err = 0;
    
    err = 0;
    
    var DateValue = DateField.value;
    
    var re = /^\d\d\/\d\d\/\d\d\d\d$/;
    if (! re.test(DateValue)) {
        alert ("Please check the start date format is dd/mm/yyyy");
        return false;
    }
  
    var year = DateValue.substr(6,4);
    if (year < 2004) {
        alert ("Please check the start date year");
        return false;
    } 
    
    var month = DateValue.substr(3,2);
    if ((month < 1) || (month > 12)) {
        alert ("Please check the start date month");
        return false;
    }
  
    day = DateValue.substr(0,2);
    var badday='';

    if (day < 1 || day > 31) {
        badday++;
    }

    /* Validation leap-year / february / day */
    if ((year % 4 == 0) || (year % 100 == 0) || (year % 400 == 0)) {
        leap = 1;
    }
  
    if ((month == 2) && (leap == 1) && (day > 29)) {
        badday++;
    }
  
    if ((month == 2) && (leap != 1) && (day > 28)) {
        badday++
    }
  
    /* Validation of other months */
        if ((day > 31) && ((month == "01") 
        || (month == "03") 
        || (month == "05") 
        || (month == "07") 
        || (month == "08") 
        || (month == "10") 
        || (month == "12")
        )) {
            badday++;
  }
  
    if ((day > 30) && ((month == "04") || (month == "06") || (month == "09") || (month == "11"))) {
        badday++;
    }

    if (badday) {
        alert ("Please check the day of the start date");
        return false;
    }

    return true;
}


function check_free_access_code () {
    var code = document.main.access_code.value;
    if (! code) { return false }
    re = /^\d{12}$/;
    if (re.test(code)) {
        return true;
    } else {
        alert ("Please check your access code is correct");
        return false;
    }
}
function setDay( change_what, month, year )
{
     if (parseInt(month.value) == 2 && parseInt(change_what.value) >28){
          if  (IsLeapYear(parseInt(year.value))) change_what.value=29
          else change_what.value=28
     }
     if (( parseInt(month.value) == 4 ||
           parseInt(month.value) == 6 ||
           parseInt(month.value, 10) == 9 ||
           parseInt(month.value) == 11) &&
           parseInt(change_what.value) >30)
         change_what.value=30

}

function IsLeapYear(y){
  if (((y%4)==0) && (((y%100)>0) || ((y%400)==0)))
    return(true);
  else
    return(false);
}
// vim: set ai et sw=4 :
// $Id: ams.js,v 1.25 2005/05/04 13:58:22 laura Exp $
