/*
 * File: site_base.js
 * Description: JavaScript used on many pages
 *      Author: M D Green
 *              11 February 2010
 *       Email: Mike.Green@saesolved.com
 *         Web: http://www.saesolved.com/
 */

function $(id) {
	if (document.getElementById) {
		return document.getElementById(id);
	} else if (document.all != null) {
		return document.id;
	}
}

function setDisplay (id, display_type) {
	$(id).style.display = display_type;
}

function displayCheckedContent (checked_obj, content_block) {
	if (checked_obj.checked) {
		setDisplay(content_block, 'block');
	} else {
		setDisplay(content_block, 'none');
	}
}

//if (top != self) top.location.href = location.href;

var popup     = new Array();
var popupName = 'popup_';

function openPopup(popupURL, popupNr, popupWidth, popupHeight, popupParms) {
    if (popup[popupNr] == null){
        popup[popupNr] = new Object;
        popupName      = popupName + popupNr;
    }
    if (popupParms == null){
        popupParms = 'toolbar=no,location=no,menubar=no,scrollbars=yes,resizable=yes';
    }
    popup[popupNr] = window.open(popupURL,popupName,popupParms + ',width=' + popupWidth + ',height=' + popupHeight);
    onBlur = popup[popupNr].focus();
}

function printThisPage () {
    if (window.print) {
        window.print();
    } else {
        alert("Your current browser does not support this function.  Please choose File | Print from your browser's menu.");
    }
}

/*  This script is to enable preventing multiple clicking on a submit button.
	it is based on one from The JavaScript Source!! http://javascript.internet.com  */
var submitcount = 0;
var returnValue = false;
function antiMultipleSubmit () {
	if (submitcount == 0) {
		submitcount++;
        returnValue = true;
	} else {
		alert("This form has already been submitted.  Thanks!");
        returnValue = false;
	}
	return returnValue;
}

function verifyEmailAndSubmit (obj, submit_where, actn, popupNr, popupWidth, popupHeight) {
    if (window.RegExp != null) {
        result_str = emailCheck(obj.value);
    } else {
        result_str = emailCheckOld(obj);
    }
    if (result_str != '') {
        alert('Please check your email address. The one you entered is not valid.');
//        alert('Please check your email address. The one you entered is not valid. (' + result_str + ')');
        obj.focus();
        return(false);
    }
    if (submit_where == 'in_popup') {
        submitInPopup(actn, popupNr, popupWidth, popupHeight);
    } else if (submit_where != null) {
        document.forms[validatedFormName].submit();
    }
    return(true);
}

// The following is derived from
// Generic Form Validation
// Jacob Hage (jacob@hage.dk)
// at The JavaScript Source!! http://javascript.internet.com
var validatedFormName = 0;
var checkObjects      = new Array();
var errors            = "";
var returnVal         = false;
var language          = new Array();
language["header"]    = "Please correct the following:"
language["start"]     = "-";
language["field"]     = " ";
// language["field"]   = " Field ";
language["require"]   = " is required";
// language["min"]     = "";
// language["max"]     = "";
// language["minmax"]  = "";
// language["chars"]   = "";
language["min"]       = " and must consist of at least ";
language["max"]       = " and must not contain more than ";
language["minmax"]    = " and no more than ";
language["chars"]     = " characters";
language["num"]       = " and must contain a number";
language["email"]     = " is not a valid e-mail address";
language["email_max"] = " must not contain more than ";
// -----------------------------------------------------------------------------
// define - Call this function in the beginning of the page. I.e. onLoad.
// n = name of the input field (Required)
// type= string, num, email, select (Required)
// min = the value must have at least [min] characters (Optional)
//       or the value that must not be selected for select field
// max = the value must have maximum [max] characters (Optional)
// d = (Optional)
// -----------------------------------------------------------------------------

function define(n, type, HTMLname, min, max, d) {
    var p;
    var i;
    var x;
    var nm;
    if (!d) d = document;
    brack_pos = n.indexOf('[');
    if (brack_pos == -1) {
        x = d.forms[validatedFormName].elements[n];
        nm = n;
    } else {
        el_name = n.substring(0, brack_pos);
        el_idx  = n.substring(brack_pos + 1, n.indexOf(']'));
        tmp_ary = d.forms[validatedFormName].elements[el_name + '[]'];
        x = tmp_ary[el_idx];
        nm = el_name + '_' + el_idx;
    }
    eval("V_" + nm + " = new formResult(x, type, HTMLname, min, max);");
    checkObjects[eval(checkObjects.length)] = eval("V_" + nm);
}

function formResult(form, type, HTMLname, min, max) {
    this.form     = form;
    this.type     = type;
    this.HTMLname = HTMLname;
    this.min      = min;
    this.max      = max;
}

function validate() {
    if (checkObjects.length > 0) {
        errorObject = "";
        for (i = 0; i < checkObjects.length; i++) {
            validateObject          = new Object();
            validateObject.form     = checkObjects[i].form;
            validateObject.HTMLname = checkObjects[i].HTMLname;
            validateObject.type     = checkObjects[i].type;
            if(validateObject.type == "ibt") {
                continue;
            }
            if(validateObject.type == "email") {
                checkObjects[i].form.value = checkObjects[i].form.value.toLowerCase();
            }
            validateObject.val      = checkObjects[i].form.value;
            validateObject.len      = checkObjects[i].form.value.length;
            validateObject.min      = checkObjects[i].min;
            validateObject.max      = checkObjects[i].max;
            if (validateObject.type == "num" || validateObject.type == "string") {
                if ((validateObject.type == "num" && validateObject.len <= 0)
                        || (validateObject.type == "num" && isNaN(validateObject.val))) {
                    errors += language['start'] + language['field'] + validateObject.HTMLname + language['require'] + language['num'] + "\n";
                } else if (validateObject.min && validateObject.max
                            && (validateObject.len < validateObject.min || validateObject.len > validateObject.max)) {
                    errors += language['start'] + language['field'] + validateObject.HTMLname + language['require'] + language['min'] + validateObject.min + language['minmax'] + validateObject.max + language['chars'] + "\n";
                } else if (validateObject.min && !validateObject.max && (validateObject.len < validateObject.min)) {
//                    errors += language['start'] + language['field'] + validateObject.HTMLname + language['require'] + ".\n";
                    errors += language['start'] + language['field'] + validateObject.HTMLname + language['require'] + language['min'] + validateObject.min + language['chars'] + "\n";
                } else if (validateObject.max && !validateObject.min &&(validateObject.len > validateObject.max)) {
                    errors += language['start'] + language['field'] + validateObject.HTMLname + language['require'] + language['max'] + validateObject.max + language['chars'] + "\n";
                } else if (!validateObject.min && !validateObject.max && validateObject.len <= 0) {
                    errors += language['start'] + language['field'] + validateObject.HTMLname + language['require'] + "\n";
                }
            } else if(validateObject.type == "email") {
                verifyTypeEmail (validateObject);
            } else if(validateObject.type == "select") {
                if (validateObject.form.options[validateObject.form.selectedIndex].value == validateObject.min
						|| validateObject.form.options[validateObject.form.selectedIndex].value == validateObject.max)
                    errors += language['start'] + language['field'] + validateObject.HTMLname + language['require'] + "\n";
            }
        }
    }
    if (errors) {
        alert(language["header"].concat("\n" + errors));
        errors = "";
        returnVal = false;
    } else {
        returnVal = true;
    }
}

function verifyTypeEmail (validateObject) {
    if (window.RegExp) {
        email_addresses = validateObject.val.split(/\s*,\s*/);
        if (validateObject.min != null && validateObject.min == 0 && email_addresses.length <= 1 && email_addresses[0] == '') {
            return(true);
        }
        for (addr_idx = 0; addr_idx < email_addresses.length; addr_idx++) {
            email_addr = email_addresses[addr_idx];
            result_str = emailCheck(email_addr);
            if (result_str != '') {
               	errors += language['start'] + language['field'] + validateObject.HTMLname + ': ' + email_addr + language['email'] + ' (' + result_str + ").\n";
//                errors += language['start'] + language['field'] + validateObject.HTMLname + ': ' + email_addr + language['email']  + ".\n";
            }
            if (validateObject.max != null && addr_idx >= validateObject.max) {
                errors += language['start'] + language['field'] + validateObject.HTMLname + language['email_max'] + validateObject.max + " e-mail addresses.\n";
                break;
            }
        }
    } else {
        errors += emailCheckOld(validateObject.form);
    }
    return(true);
}

/*  The following is derived from Email Adress Validation
    by Sandeep V. Tamhankar (stamhankar@hotmail.com)

    This script and many more are available free online at
    The JavaScript Source!! http://javascript.internet.com

    V1.1.3: Sandeep V. Tamhankar (stamhankar@hotmail.com)
    Original:  Sandeep V. Tamhankar (stamhankar@hotmail.com)

    Changes:
    1.1.4: Fixed a bug where upper ASCII characters (i.e. accented letters
    international characters) were allowed.

    1.1.3: Added the restriction to only accept addresses ending in two
    letters (interpreted to be a country code) or one of the known
    TLDs (com, net, org, edu, int, mil, gov, arpa), including the
    new ones (biz, aero, name, coop, info, pro, museum).  One can
    easily update the list (if ICANN adds even more TLDs in the
    future) by updating the knownDomsPat variable near the
    top of the function.  Also, I added a variable at the top
    of the function that determines whether or not TLDs should be
    checked at all.  This is good if you are using this function
    internally (i.e. intranet site) where hostnames don't have to
    conform to W3C standards and thus internal organization e-mail
    addresses don't have to either.
    Changed some of the logic so that the function will work properly
    with Netscape 6.

    1.1.2: Fixed a bug where trailing . in e-mail address was passing
    (the bug is actually in the weak regexp engine of the browser; I
    simplified the regexps to make it work).

    1.1.1: Removed restriction that countries must be preceded by a domain,
    so abc@host.uk is now legal.  However, there's still the
    restriction that an address must end in a two or three letter
    word.

    1.1: Rewrote most of the function to conform more closely to RFC 822.

    1.0: Original  */

function emailCheck (emailStr) {

    emailStr = trimString(emailStr);

    /* The following variable tells the rest of the function whether or not
    to verify that the address ends in a two-letter country or well-known
    TLD.  1 means check it, 0 means don't. */

    var checkTLD = 1;

    /* The following is the list of known TLDs that an e-mail address must end with. */

    var knownDomsPat = /^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;

    /* The following pattern is used to check if the entered e-mail address
    fits the user@domain format.  It also is used to separate the username
    from the domain. */

    var emailPat = /^(.+)@(.+)$/;

    /* The following string represents the pattern for matching all special
    characters.  We don't want to allow special characters in the address.
    These characters include ( ) < > @ , ; : \ " . [ ] */

    var specialChars = "\\(\\)><@,;:\\\\\\\"\\.\\[\\]";

    /* The following string represents the range of characters allowed in a
    username or domainname.  It really states which chars aren't allowed.*/

    var validChars = "\[^\\s" + specialChars + "\]";

    /* The following pattern applies if the "user" is a quoted string (in
    which case, there are no rules about which characters are allowed
    and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
    is a legal e-mail address. */

    var quotedUser = "(\"[^\"]*\")";

    /* The following pattern applies for domains that are IP addresses,
    rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
    e-mail address. NOTE: The square brackets are required. */

    var ipDomainPat = /^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;

    /* The following string represents an atom (basically a series of non-special characters.) */

    var atom = validChars + '+';

    /* The following string represents one word in the typical username.
    For example, in john.doe@somewhere.com, john and doe are words.
    Basically, a word is either an atom or quoted string. */

    var word = "(" + atom + "|" + quotedUser + ")";

    // The following pattern describes the structure of the user

    var userPat = new RegExp("^" + word + "(\\." + word + ")*$");

    /* The following pattern describes the structure of a normal symbolic
    domain, as opposed to ipDomainPat, shown above. */

    var domainPat = new RegExp("^" + atom + "(\\." + atom +")*$");

    /* Finally, let's start trying to figure out if the supplied address is valid. */

    /* Begin with the coarse pattern to simply break up user@domain into
    different pieces that are easy to analyze. */

    var matchArray = emailStr.match(emailPat);

    if (matchArray == null) {
        /*  Too many/few @'s or something; basically, this address doesn't
            even fit the general mould of a valid e-mail address. */
        return 'Address does not fit required pattern for email addresses. Check "@" and "."';
    }

    var user   = matchArray[1];
    var domain = matchArray[2];

    // Start by checking that only basic ASCII characters are in the strings (0-127).
    for (i = 0; i < user.length; i++) {
        if (user.charCodeAt(i) > 127) {
            return 'The username part of the email address contains invalid characters.';
        }
    }
    for (i=0; i<domain.length; i++) {
        if (domain.charCodeAt(i)>127) {
            return 'The domain name part of the email address contains invalid characters.';
        }
    }

    // See if "user" is valid
    if (user.match(userPat) == null) {
        // user is not valid
        return 'The username part of the email address is not valid.';
    }

    /* if the e-mail address is at an IP address (as opposed to a symbolic
    host name) make sure the IP address is valid. */
    var IPArray = domain.match(ipDomainPat);
    if (IPArray != null) {
        // this is an IP address
        for (var i=1; i <= 4; i++) {
            if (IPArray[i] > 255) {
                return 'The destination IP address part of the email address is not valid.';
            }
        }
        return '';
    }

    // Domain is symbolic name.  Check if it's valid.
    var atomPat = new RegExp("^" + atom + "$");
    var domArr  = domain.split(".");
    var len     = domArr.length;
    for (i = 0; i < len; i++) {
        if (domArr[i].search(atomPat) == -1) {
            return 'The domain name part of the email address does not seem to be valid.';
        }
    }

    /* domain name seems valid, but now make sure that it ends in a
    known top-level domain (like com, edu, gov) or a two-letter word,
    representing country (uk, nl), and that there's a hostname preceding
    the domain or country. */
    if (checkTLD && domArr[domArr.length-1].length!=2 && domArr[domArr.length-1].search(knownDomsPat)==-1) {
        return 'The email address must end in a well-known domain or two letter country.';
    }

    // Make sure there's a host name preceding the domain.
    if (len < 2) {
        return 'The email address is missing a hostname.';
    }

    // If we've gotten this far, everything's valid!
    return '';
}

function emailCheckOld (obj) {

    obj = trimString(obj);

    // Checking existence of "@" and ".".
    // Length of must >= 5 and the "." must
    // not directly precede or follow the "@"
    if ((obj.value.indexOf("@") == -1)
            || (obj.value.charAt(0) == ".")
            || (obj.value.charAt(0) == "@")
            || (obj.value.length < 6)
            || (obj.value.indexOf(".") == -1)
            || (obj.value.charAt(obj.value.indexOf("@")+1) == ".")
            || (obj.value.charAt(obj.value.indexOf("@")-1) == ".")) {
        return '"@" and "." must exist, length of must >= 5, and the "." must not directly precede or follow the "@".\n';
    } else {
        return '';
    }
}

function trimString (str) {
    var rtnstr = str.toString();
    rtnstr = lTrim(rtnstr);
    rtnstr = rTrim(rtnstr);
    return rtnstr;
}

function lTrim (str) {
    var rtnstr = str.toString();
    if (window.RegExp) {
        rtnstr = rtnstr.replace(/^\s+/, "");
    } else {
        var firstSpace = rtnstr.indexOf(' ');
        while (firstSpace == 0 && rtnstr.length > 0) {
            rtnstr     = rtnstr.substring(1, rtnstr.length)
            firstSpace = rtnstr.indexOf(' ');
        }
    }
    return rtnstr;
}

function rTrim (str) {
    var rtnstr = str.toString();
    if (window.RegExp) {
        rtnstr = rtnstr.replace(/\s+$/, "");
    } else {
        var lastSpace = rtnstr.lastIndexOf(' ');
        var lastPosn  = rtnstr.length - 1;
        while (lastSpace == lastPosn && lastPosn >= 0) {
            rtnstr    = rtnstr.substring(0, lastPosn)
            lastSpace = rtnstr.lastIndexOf(' ');
            lastPosn  = rtnstr.length - 1;
        }
    }
    return rtnstr;
}


/*
 * Added functions to handle writing Flash object;
 * Added functions to read and write cookies
 */

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

//v1.0
//Copyright 2006 Adobe Systems, Inc. All rights reserved.
function AC_AddExtension(src, ext)
{
  if (src.indexOf('?') != -1)
    return src.replace(/\?/, ext+'?');
  else
    return src + ext;
}

function AC_Generateobj(objAttrs, params, embedAttrs)
{
  var str = '<object ';
  for (var i in objAttrs)
    str += i + '="' + objAttrs[i] + '" ';
  str += '>';
  for (var i in params)
    str += '<param name="' + i + '" value="' + params[i] + '" /> ';
  str += '<embed ';
  for (var i in embedAttrs)
    str += i + '="' + embedAttrs[i] + '" ';
  str += ' ></embed></object>';

  document.write(str);
}

function AC_FL_RunContent(){
  var ret =
    AC_GetArgs
    (  arguments, ".swf", "movie", "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
     , "application/x-shockwave-flash"
    );
  AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
}

function AC_SW_RunContent(){
  var ret =
    AC_GetArgs
    (  arguments, ".dcr", "src", "clsid:166B1BCA-3F9C-11CF-8075-444553540000"
     , null
    );
  AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
}

function AC_GetArgs(args, ext, srcParamName, classid, mimeType){
  var ret = new Object();
  ret.embedAttrs = new Object();
  ret.params = new Object();
  ret.objAttrs = new Object();
  for (var i=0; i < args.length; i=i+2){
    var currArg = args[i].toLowerCase();

    switch (currArg){
      case "classid":
        break;
      case "pluginspage":
        ret.embedAttrs[args[i]] = args[i+1];
        break;
      case "src":
      case "movie":
        args[i+1] = AC_AddExtension(args[i+1], ext);
        ret.embedAttrs["src"] = args[i+1];
        ret.params[srcParamName] = args[i+1];
        break;
      case "onafterupdate":
      case "onbeforeupdate":
      case "onblur":
      case "oncellchange":
      case "onclick":
      case "ondblClick":
      case "ondrag":
      case "ondragend":
      case "ondragenter":
      case "ondragleave":
      case "ondragover":
      case "ondrop":
      case "onfinish":
      case "onfocus":
      case "onhelp":
      case "onmousedown":
      case "onmouseup":
      case "onmouseover":
      case "onmousemove":
      case "onmouseout":
      case "onkeypress":
      case "onkeydown":
      case "onkeyup":
      case "onload":
      case "onlosecapture":
      case "onpropertychange":
      case "onreadystatechange":
      case "onrowsdelete":
      case "onrowenter":
      case "onrowexit":
      case "onrowsinserted":
      case "onstart":
      case "onscroll":
      case "onbeforeeditfocus":
      case "onactivate":
      case "onbeforedeactivate":
      case "ondeactivate":
      case "type":
      case "codebase":
        ret.objAttrs[args[i]] = args[i+1];
        break;
      case "width":
      case "height":
      case "align":
      case "vspace":
      case "hspace":
      case "class":
      case "title":
      case "accesskey":
      case "name":
      case "id":
      case "tabindex":
        ret.embedAttrs[args[i]] = ret.objAttrs[args[i]] = args[i+1];
        break;
      default:
        ret.embedAttrs[args[i]] = ret.params[args[i]] = args[i+1];
    }
  }
  ret.objAttrs["classid"] = classid;
  if (mimeType) ret.embedAttrs["type"] = mimeType;
  return ret;
}
