// Common JavaScript Library
// By Bradley Stec, August 2005
// Copyright Bradley Stec

///////////////////////////////////////////////////////
// Initialize Common Variables                       //
///////////////////////////////////////////////////////
var i = 0;
var jsDow = new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday");
var jsMoy = new Array("January","February","March","April","May","June","July","August","September","October","November","December");

// Set Variables for PopUp Calendars
var jsMonth = new Array('January','February','March','April','May','June','July','August','September','October','November','December');
var jsDays = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
var jsShortDow = new Array('Sun','Mon','Tue','Wed','Thu','Fri','Sat');

// Create Some Basic Date Objects for General Use
var jsToday = new Date();
var jsTodayDay = jsToday.getDate();
var jsTodayMonth = jsToday.getMonth();
var jsTodayYear = jsToday.getYear();
if(jsTodayYear < 2000) { jsTodayYear = jsTodayYear + 1900; }

// Create Some Nicely Formatted Strings For General Use
end = "th";
if (jsTodayDay==1 || jsTodayDay==21 || jsTodayDay==31) end="st";
if (jsTodayDay==2 || jsTodayDay==22) end="nd";
if (jsTodayDay==3 || jsTodayDay==23) end="rd";
jsTodayDay+=end;

var jsDow = jsDow[jsToday.getDay()];
var jsDate = (jsMoy[jsToday.getMonth()]+" "+jsTodayDay+", "+jsTodayYear);

// StartTime is a TimeStamp That Can Be Used to Calculate Load and Run Time
// You just need to Create an End TimeStamp and do a calculation for elapsed time.
var jsStartTime = new Date();

// Email Address Build Variables To Hide Them From Spam Target Harvesters
/*
var emDomain="itpdx";
var emSuffix="com";

var emContact="request";
var nmContact="Requests";
var jsContactEmail="<a href='mailto:" + emContact + "@" + emDomain + "." + emSuffix + "'>" + nmContact + "</a>";

var emAdmin="administration";
var nmAdmin="Administrator";
var jsAdminEmail="<a href='mailto:" + emAdmin + "@" + emDomain + "." + emSuffix + "'>" + nmAdmin + "</a>";
*/

// Default Browser Status Bar
//window.defaultStatus = "ITPDX is available now call or write us now!";

///////////////////////////////////////////////////////
// Shared Low-Level Functions                        //
///////////////////////////////////////////////////////

// Validate Month Value and Fix Two Digits
// Valid Numbers are 01 to 12
function validMonth(x) {
	// Confirm All Digits
	var errString = "";
	var n=eval(x.value);
	if ( n < 1 || n > 12 ) {
		errString="Please enter a month between 1 and 12.";
		n=jsTodayMonth;
	}
	if ( n < 10 ) {
		x.value = "0" + n;
	} else {
		x.value = n;
	}
	if (errString != "") {
		alert(errString);
		x.select(0);
		x.focus();
	}
}

// Validate Year Value and Fix Four Digits
// Valid Numbers are between 1980 and 2099
function validYear(x) {
	// Confirm All Digits
	var errString = "";
	var n=eval(x.value);
	if ( n < 1980 || n > 2099) {
		errString="Please enter a year between 1980 and 2099.";
		n=jsTodayYear;
		x.value=jsTodayYear.toString();
		alert(errString);
		x.select(0);
		x.focus();
	}
}

// Validate Month Value and Fix Two Digits
// Valid Numbers are 01 to 31
// Months 1,3,5,7,8,10,12 have 31 days
// Months 4,6,9,11 have 30 days
// Month 2 has 28 days.  
//     29 in leap years starting with 2004.
function validDay(x,pMonth,pYear) {
	// Max Number Is?
	var maxDays = 0;
	var leapYear = 0;
	var intYear = 0;
	var intMonth = 0;
	var intMonth = eval(pMonth.toString());
	var intYear = eval(pYear.toString());
	// Identify Leap Year
	switch (intYear) {
		case 1980 :
		case 1984 :
		case 1988 :
		case 1992 :
		case 1996 :
		case 2000 :
		case 2004 :
		case 2008 :
		case 2012 :
		case 2016 :
		case 2020 :
		case 2024 :
		case 2028 :
		case 2032 :
		case 2036 :
		case 2040 :
		case 2044 :
		case 2048 :
		case 2052 :
		case 2056 :
		case 2060 :
		case 2064 :
		case 2068 :
		case 2072 :
		case 2076 :
		case 2080 :
		case 2084 :
		case 2088 :
		case 2092 :
		case 2096 :
			leapYear = 1;
			break;
		default :
			leapYear = 0;
	}

	// Identify Month
	switch (intMonth) {
		case 1 :
		case 3 :
		case 5 :
		case 7 :
		case 8 :
		case 10 :
		case 12 :
			maxDays = 31;
			break;
		case 2 :
			maxDays = 28;
			if ( leapYear == 1 ) {
				maxDays = 29;
			}
			break;
		default :
			maxDays = 30;
	}

	var errString = "";
	var n=eval(x.value);
	if ( n < 1 || n > maxDays ) {
		errString="Invalid Day. Valid is 1 to " + maxDays.toString();
		n=1;
	}
	if ( n < 10 ) {
		x.value = "0" + n;
	} else {
		x.value = n;
	}
	if (errString != "") {
		alert(errString);
		x.select(0);
		x.focus();
	}
}


// Pop Up A Locked Browser Window
// This one only allows scrolling within it's document.
function popSealedWindow(url,setwidth,setheight,windowname) {
	// If browser is greater than level 3 we can center the pop up window
	// Browser Safety Width
	setwidth = setwidth - 26;
	// Browser Safety Height
	setheight = setheight - 20;
	// Centering Window
	var wide = 0;
	var high = 0;
	var doit = "";
	wide = ((screen.width-setwidth)/2)
	high = ((screen.height-setheight)/2)
	if ( windowname=="") {
		windowname = "popSealed"
	}
	doit = "window.open(\""+url+"\",\""+windowname+"\",\"toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=0,width=" + setwidth + ",height=" + setheight + ",top=" + high + ",left=" + wide + "\");";
	eval(doit);
}

// Pop Up A Browser Window
// This one is an entirely new browser window with full functions.
function popFreeWindow(url,setwidth,setheight,windowname) {
	// If browser is greater than level 3 we can center the pop up window
	// Browser Safety Width
	setwidth = setwidth - 26;
	// Browser Safety Height
	setheight = setheight - 20;
	// Centered
	var wide = 0;
	var high = 0;
	var doit = "";
	wide = ((screen.width-setwidth)/2)
	high = ((screen.height-setheight)/2)
	if ( windowname=="") {
		windowname = "popFreed"
	}
	doit = "window.open(\""+url+"\",\""+windowname+"\",\"toolbar=1,location=1,directories=1,status=1,menubar=1,scrollbars=1,resizable=1,width=" + setwidth + ",height=" + setheight + ",top=" + high + ",left=" + wide + "\");";
	eval(doit);
}

// Test: Invalid Email Address (true = no)
function isInvalidEmail(strTest) {
	locAt = strTest.indexOf("@",0);
	if (locAt > -1) {
		locDot = strTest.indexOf(".",locAt);
	}
	if ( locAt == -1 || locDot == -1 || locDot < locAt ) {
		return 1;
	}
	return 0;
}

// Test: String Is Null (true = yes)
function isNullString(strTest) {
	if ( strTest.length < 1 ) {
		return 1;
	}
	return 0;
}

// Test: String Is Numeric (true = yes)
function isNumber(strTest) {
	if ( isNullString(strTest) ) {
		return 0;
	}
	if ( isNaN(strTest) ) {
		return 0;
	}
	return 1;
}

// Basic String Trimming Function
function trim(s) {
	while (s.substring(0,1) == ' ') {
		s = s.substring(1,s.length);
		}
	while (s.substring(s.length-1,s.length) == ' ') {
		s = s.substring(0,s.length-1);
		}
	return s;
}

function cleanString(s) {
	s = s.replace("'","_");
	return s;
}


///////////////////////////////////////////////////////
// Common Menu System Functions                      //
///////////////////////////////////////////////////////

// These functions must be tailored to the site structure.
// Each section of the menu must have a unique ID so that
// the JavaScript can open and close them as they are clicked.

// This hides all sections of the menu.  If you want to force
// a section to be open, you need to execute a script onLoad
// which opens the section that corresponds to the page you are
// browsing.  See "showTable()" or "openSection()".
function hideAll() {
	<!--- Add A Line Just Like These For each SUBMENU (not link) --->
	<!--- The ID name (membership) must match the submenu table ID below --->
	document.getElementById('about').style.display = 'none';
	document.getElementById('service').style.display = 'none';
	//document.getElementById('articles').style.display = 'none';
	//document.getElementById('register').style.display = 'none';
}


// This function mute glowing sections.
function muteAll() {
	<!--- Add A Line Just Like These For each SUBMENU (not link) --->
	<!--- The ID name (membership) must match the submenu table ID below --->
	document.getElementById('about').style.backgroundColor = '';
	document.getElementById('service').style.backgroundColor = '';
	document.getElementById('articles').style.backgroundColor = '';
	document.getElementById('register').style.backgroundColor = '';
}


// This function shows the menu section that is requested.
function showTable(obj) {	
	if (obj.style.display == 'block') {
		obj.style.display = 'none';
	} else {
		obj.style.display = 'block';
	}
}


// This function glows the menu section that is requested.
function glowTable(obj) {	
	return 0;
	//muteAll();
	//obj.style.backgroundColor = '#9999FF';
}


// This function will detect the subdirectory that the page is loaded
// from and correspond that subdirectory to an openSection of the menu.
// If you load the proper directory names here you can use this function
// in a page onLoad event to get the menu to correspond.
function openSection() {
	hideAll();
	var strSection = "none";
	var strTemp = document.URL;
	//alert(document.URL);
	if ( document.URL.indexOf("/about/") > 0 ) { strSection = "about"; }
	if ( document.URL.indexOf("/service/") > 0 ) { strSection = "service"; }
	if ( document.URL.indexOf("/articles/") > 0 ) { strSection = "articles"; }
	if ( document.URL.indexOf("/register/") > 0 ) { strSection = "register"; }
	if ( strSection != "none" ) {
		showTable(document.getElementById(strSection));
	}
}

// This function stops someone from wandering out of a secured area without
// understanding the consequences, such as when they're working through a multi-page
// transaction.
function confirmSecureExit(url) {
	if (confirm("Are you sure you want to leave this secured page?\nYou'll lose any form data you already typed in if you do.")) {
		document.location.href = url;
	}
}


// This function validates Login Authentication
function loginForm(username,password) {
	document.btnLogin.src='/p/btnLogin_dn.gif';
	if ( isNullString(password) && isNullString(username) ) {
		// If both fields are blank, assume a new registration
		this.location.href="/register/index.php";
	} else {
		// If one or the other is not blank, do error checking
		if ( isNullString(password) ) {
			alert("You must provide a password to login.");
		}
		if ( isNullString(username) ) {
			alert("You must provide a username with your password.");
		}
	}
	document.btnLogin.src='/p/btnLogin_up.gif';
}

function checkEnter(e, frm){ //e is event object passed from function invocation
    var characterCode; //literal character code will be stored in this variable

    if(e && e.which){ //if which property of event object is supported (NN4)
        e = e
        characterCode = e.which //character code is contained in NN4's which property
    } else {
        e = event
        characterCode = e.keyCode //character code is contained in IE's keyCode property
    }

    if(characterCode == 13){ //if generated character code is equal to ascii 13 (if enter key)
        document.forms[0].submit() //submit the form
        return false
    } else {
        return true
    }

}
function show_hide_log(log_id)
{
    var el_log = document.getElementById(log_id + '_logentries');
    var el_img = document.getElementById(log_id + '_img');
    if( el_log )
    {
        if( el_log.style.display == 'block' )
        {
            el_log.style.display = 'none';
            el_img.src = '/p/collapse_open.gif';
        } else {
            el_log.style.display = 'block';
            el_img.src = '/p/collapse_close.gif';
        }
    }
    return false;
    
}

function check_email (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. */

        //alert("Email address seems incorrect (check @ and .'s)");
        return false;
    }
    
    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) {
        //alert("Ths username contains invalid characters.");
        return false;
       }
    }
    for (i=0; i<domain.length; i++) {
        if (domain.charCodeAt(i)>127) {
        //alert("Ths domain name contains invalid characters.");
        return false;
       }
    }

    // See if "user" is valid 

    if (user.match(userPat)==null) {

        // user is not valid

        //alert("The username doesn't seem to be valid.");
        return false;
    }

    /* 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) {
            //alert("Destination IP address is invalid!");
            return false;
           }
        }
        return true;
    }

    // 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) {
        //alert("The domain name does not seem to be valid.");
        return false;
       }
    }

    /* 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) {
        //alert("The address must end in a well-known domain or two letter " + "country.");
        return false;
    }

    // Make sure there's a host name preceding the domain.

    if (len<2) {
        //alert("This address is missing a hostname!");
        return false;
    }

    // If we've gotten this far, everything's valid!
    return true;
}

function validatePhoneNumber(PhoneNumber)
{
	var PNum = new String(PhoneNumber);
	
	//	555-555-5555
	//	(555)555-5555
	//	(555) 555-5555
	//	555-5555

        // NOTE: COMBINE THE FOLLOWING FOUR LINES ONTO ONE LINE.
	var regex = /^[0-9]{3,3}\-[0-9]{3,3}\-[0-9]{4,4}$|^\([0-9]{3,3}\) [0-9]{3,3}\-[0-9]{4,4}$|^\([0-9]{3,3}\)[0-9]{3,3}\-[0-9]{4,4}$|^[0-9]{3,3}\-[0-9]{4,4}$/;
	
	return regex.test(PNum);
}

function strpos( haystack, needle, offset){
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Onno Marsman    
    // +   bugfixed by: Daniel Esteban
    // *     example 1: strpos('Kevin van Zonneveld', 'e', 5);
    // *     returns 1: 14
 
    var i = (haystack+'').indexOf(needle, (offset ? offset : 0));
    return i === -1 ? false : i;
}
