/*----------------------------------------------------------------------------------

 File            : XLibrary.js

 Use             : Library of JavaScript functions for general use

 Description     : A library of useful functions.

 Dependants      : CBL CharterRequest.js
 				   CBL XDate.js

 Depends On      : XGlobal.js

 Functions		 : 	function FindImageObjBySrc(img_src)
					function PreloadImages()
                   	function IsStringNull(s)
					function IsStringContain(s1, s2)
                   	function AlertErrorFocus(err_msg, err_element)
                   	function AlertHelloWorld()
                   	function IsNumber( s )
                   	function IsEmailAddress( s )
                   	function Parse( s, Separator )
                   	function ParseFindSeparator( s, s_index, Separator )
                   	function ParseIsSeparatorFound( s, s_index, sep )
					function Null2Blank( s )
					function CookieExample()
                    function FixDate(date)
                    function DeleteCookie(name, path, domain)
                    function GetCookie(name)
                    function SetCookie(name, value, expires, path, domain, secure)
					function OpenWindowTerse( window_html, window_name, window_width, window_height ) 
					function OpenWindowTerseNoScroll( window_html, window_name, window_width, window_height )
					function OpenWindowImage(image_file, title_text);					 
					function emailCheck (emailStr)
					function LayerShow(layer_obj, x, y)
					function LayerHide(layer_obj)
					function IsMimeType(mime_type)
					function GetEmailMailTo(emailaddress)                    
					
					//parse file names 
					function FilePathName(file_path_name_ext)
					function FileNameExt(file_path_name_ext)
					function FileName(file_path_name_ext) 
					function FileExt(file_path_name_ext)					 
					function IsFileExtension(file_name, file_extension)

					//image roll over functions
					function jRoll(url, target, img_src, img_tags) {
					function jRollOver(img_src) {
					function jRollOut(img_src) {
					 

 Modfications    : 2002/01/15 JPE Created
                   
-------------------------------------------------------------------------------------*/



//Constants

EMAIL_DOMAIN 			= "vttgroup.com";
ROLLOVER_IMAGE_SUFFIX 	= "_OVER";






// Function Definitions


//return the image object with its source file name and extension equal to img_src's file name and extension 
function FindImageObjBySrc(img_src) {
    var i;
    for (i=0; i<document.images.length; i++) {
        if (FileNameExt(document.images[i].src) == FileNameExt(img_src)) {
            return document.images[i];
        }
    }       
}
 
 
 
function MM_findObj(n, d) { //v3.0
  	var p,i,x;  	  
  	if(!d) d=document; 
  	if((p=n.indexOf("?"))>0&&parent.frames.length) {
    	d=parent.frames[n.substring(p+1)].document; 
    	n=n.substring(0,p);
    }
  	if(!(x=d[n])&&d.all) x=d.all[n]; 
  	for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  	for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document); 
  	return x;
}



function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}
function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}



//  Description:  preload images in body tag's "OnLoad" event
//  Arguments:    list of comma separated image file names
//  Example:      <body onLoad="PreloadImages('images/image1.gif','images/image2.jpg','images/image3.gif')">
function PreloadImages() {
	var d=document;
	alert("hello");
	if (d.images) {
		if (!d.MM_p) {
			d.MM_p=new Array();
		}
    	var i,j=d.MM_p.length;
    	var a=PreloadImages.arguments;
    	for(i=0; i<a.length; i++) {
    		if (a[i].indexOf("#")!=0) {
    			d.MM_p[j]= new Image;
    			d.MM_p[j++].src=a[i];
    		}
    	}
    }
}
 


//  Description:  determines if a string is null or a collection of blanks
//  Arguments:    a string or string object(?)
//  Example:      IsStringNull(" ") returns true
function IsStringNull( s ) {
    var i = 0;
    for (i=0; i<s.length; i++) {
        if (s.substring(i, i+1) != " ") {
            return false;
        }
    }
    return true;
}



//  Description:  does s1 contain string s2?
//  Arguments:    two strings
//  Example:      IsStringContain("Morning Laura", "Laura") returns true
function IsStringContain(s1, s2) {
    var i;
    for (i=0; i<s1.length; i++) {
        if (s1.substring(i, i+s2.length) = s2) {
            return true;
        }
    }
    return false;
}



//  Description:  show a message box with a string and focus a field
//  Arguments:    a string or string object(?), a form element
//  Example:      AlertFormElementError("The phone number can't be blank", document.form[0].phone_number)
function AlertErrorFocus( err_msg, err_element ) {
    alert( err_msg );
    err_element.focus();
}



//a function for testing where events occur
function AlertHelloWorld() {
	alert( "Hello World" );
}	



//  Description:  if the string can be converted to a number return true;
//  Arguments:    s string to convert
//  Example:      IsNumber( "123.6373") returns true; IsNumber( "123ABC") returns false; IsNumber( "123 ") returns true; IsNumber( "") returns false;
function IsNumber( s ) {
	return !isNaN( s );
}



//  Description:  if s is of the form <text>"@"<text>"."<text> return true;
//  Arguments:    s is a string
//  Example:      IsEmailAddress( "Joe@yahoo.com" ) returns true; IsEmailAddress( "Joe@yahoo..com" ) returns false;
function IsEmailAddress( s ) {
	return emailCheck(s);
}



// These Cookie functions are from http://www.webreference.com/js/column8/functions.html acquired June 18, 2002 JPE
//Here is the syntax of a cookie string: name=value[; EXPIRES=datevalue][; DOMAIN=domainName][; PATH=pathname][; SECURE]
//In JavaScript: document.cookie = CookieString;
// name - name of the cookie
// value - value of the cookie
// [expires] - expiration date of the cookie (defaults to end of current session)
// [path] - path for which the cookie is valid (defaults to path of calling document)
// [domain] - domain for which the cookie is valid (defaults to domain of calling document)
// [secure] - Boolean value indicating if the cookie transmission requires a secure transmission
// * an argument defaults when it is assigned null as a placeholder
// * a null placeholder is not required for trailing omitted arguments
function SetCookie(name, value, expires, path, domain, secure) {
  var curCookie = name + "=" + escape(value) +
      ((expires) ? "; expires=" + expires.toGMTString() : "") +
      ((path) ? "; path=" + path : "") +
      ((domain) ? "; domain=" + domain : "") +
      ((secure) ? "; secure" : "");
  document.cookie = curCookie;
}



// name - name of the desired cookie
// * return string containing value of specified cookie or null if cookie does not exist
function GetCookie(name) {
  var dc = document.cookie;
  var prefix = name + "=";
  var begin = dc.indexOf("; " + prefix);
  if (begin == -1) {
    begin = dc.indexOf(prefix);
    if (begin != 0) return null;
  } else
    begin += 2;
  var end = document.cookie.indexOf(";", begin);
  if (end == -1)
    end = dc.length;
  return unescape(dc.substring(begin + prefix.length, end));
}

// name - name of the cookie
// [path] - path of the cookie (must be same as path used to create cookie)
// [domain] - domain of the cookie (must be same as domain used to create cookie)
// * path and domain default if assigned null or omitted if no explicit argument proceeds
function DeleteCookie(name, path, domain) {
  if (getCookie(name)) {
    document.cookie = name + "=" +
    ((path) ? "; path=" + path : "") +
    ((domain) ? "; domain=" + domain : "") +
    "; expires=Thu, 01-Jan-70 00:00:01 GMT";
  }
}

// date - any instance of the Date object
// * hand all instances of the Date object to this function for "repairs"
function FixDate(date) {
  var base = new Date(0);
  var skew = base.getTime();
  if (skew > 0)
    date.setTime(date.getTime() - skew);
}



function CookieExample() {
    // create an instance of the Date object
    var now = new Date();
    // fix the bug in Navigator 2.0, Macintosh
    fixDate(now);
    // cookie expires in one year (actually, 365 days)
    // 365 days in a year
    // 24 hours in a day
    // 60 minutes in an hour
    // 60 seconds in a minute
    // 1000 milliseconds in a second
    now.setTime(now.getTime() + 365 * 24 * 60 * 60 * 1000);
    var visits = getCookie("counter");
    // if the cookie wasn't found, this is your first visit
    if (!visits) {
     visits = 1; // the value for the new cookie
     document.write("By the way, this is your first time here.");
    } else {
     // increment the counter
     visits = parseInt(visits) + 1;
     document.write("By the way, you have been here " + visits + " times.");
    }
    // set the new cookie
    setCookie("counter", visits, now);
}



//if UpperCase(s) = "NULL" then set s to a blank string i.e. ""
function Null2Blank( s ) {
	if ( s == null )  {
		return "";
	} else {
		return  s;
	}
}





//author: Sandeep V. Tamhankar (stamhankar@hotmail.com)
function emailCheck (emailStr) {
/* 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]

// 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
var domainArray=domain.match(domainPat)
if (domainArray==null) {
//	alert("The domain name doesn't seem to be valid.")
    return false
}

/* domain name seems valid, but now make sure that it ends in a
   three-letter word (like com, edu, gov) or a two-letter word,
   representing country (uk, nl), and that there's a hostname preceding
   the domain or country. */

/* Now we need to break up the domain to get a count of how many atoms
   it consists of. */
var atomPat=new RegExp(atom,"g")
var domArr=domain.match(atomPat)
var len=domArr.length
if (domArr[domArr.length-1].length<2 ||
    domArr[domArr.length-1].length>3) {
   // the address must end in a two letter or three letter word.
//   alert("The address must end in a three-letter domain, or two letter country.")
   return false
}

// Make sure there's a host name preceding the domain.
if (len<2) {
   var errStr="This address is missing a hostname!"
   alert(errStr)
   return false
}

// If we've gotten this far, everything's valid!
return true;
}



// open an existing html file or create one on the fly with html code passed in parameter window_html    
function OpenWindow(window_html, window_name, window_attributes) {
	var window_obj;	
	if (IsFileExtension(window_html, "html")) {   
		window_obj = window.open(window_html, window_name, window_attributes);
	} else {
		window_obj = window.open("", window_name, window_attributes);
		window_obj.document.write(window_html);
	}
	window_obj.focus();
	return window_obj
}	 



function OpenWindowTerse( window_html, window_name, window_width, window_height ) {
	var window_obj;
	var window_dimensions;
	var window_attributes;
	window_dimensions = "width=" + window_width +"," + "height=" + window_height; //"width=" + window_width + ",height=" + window_height;
	window_attributes = "toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=yes,resizeable=1";
	window_attributes = window_attributes + ',' + window_dimensions;
	return OpenWindow( window_html, window_name, window_attributes ); 
}



function OpenWindowTerseNoScroll( window_html, window_name, window_width, window_height ) {
	var window_obj;
	var window_position;
	var window_dimensions;
	var window_attributes;		
//alert("window_width " + window_width); at this point window_width has been = 0 when it is the wondow opens in lower right hand corner of the screen    	    	
	window_position   = OpenWindowScreenCenter(window_width, window_height);
	window_dimensions = "width=" + window_width +"," + "height=" + window_height; //"width=" + window_width + ",height=" + window_height;
	window_attributes = "toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=no,resizeable=1";
	window_attributes = window_attributes + ',' + window_dimensions + ',' + window_position;	
	return OpenWindow( window_html, window_name, window_attributes ); 
}



// open a new browser window entered and just big enough to hold the image 
function OpenWindowImage(image_file, title_text) {
	var image_object;
	image_object = new Image;
	image_object.src = image_file;
	WaitForImageToLoad(image_object, 150000); 
	window_html = "<title> " 
	  			+     title_text
	  			+ "</title> "
                + "<body> "
	  			+ "    <img src='" + image_file + "' border=0 alt='" + title_text + "'> "		 
	  			+ "</body> ";
	OpenWindowTerseNoScroll(window_html, '', image_object.width + 22, image_object.height  + 27);
}	



// wait for the image object to load or wait for time out before passing control back to calling funtion
//THIS DOES NOT APPEAR TO BE WORKING: IT TIMES OUT EVERY TIME! 
function WaitForImageToLoad(image_object, time_out) {
	var time_start = new Date(); 
	var time_now = new Date(); 
	var time_spent = time_now.getTime() - time_start.getTime();
	for (;(time_spent < time_out && image_object.width == 0 );) {
alert(image_object.width);	
    	time_now = new Date();
        time_spent = time_now.getTime() - time_start.getTime();
    }   
}    	
	    
	
	
function GetWindowWidth() {
    if (document.layers) {
		return window.innerWidth;
    } else if (document.all) {
        return document.body.clientWidth;
    }
}



function GetWindowHeight() {
    if (document.layers) {
        return window.innerHeight;
    } else if (document.all) {
        return document.body.clientHeight;
    }
}



function GetScreenWidth() {
    if (document.layers) {
        return window.outerWidth;
    } else if (document.all) {
		return screen.width;
    }
}



function GetScreenHeight() {
    if (document.layers) {
        return window.outerHeight;
    } else if (document.all) {
		return screen.height;
    }
}


function OpenWindowScreenCenter(child_window_width, child_window_height ) {
	var screen_width = GetScreenWidth();
	var screen_height = GetScreenHeight();
	var x = (screen_width - child_window_width)/2; 
	var y = (screen_height - child_window_height)/2;
    return 'top='+y+',screenY='+y+',left='+x+',screenX='+x;
}


	
//remember to use quotes around the layer_object name ex.: LayerShow("LayerLetterFull", 368, 130);
/* declare the layer using CSS as follows:

               <style type="text/css">
                   .myStyle {position: absolute; visibility: hidden;}
               </style>
                                                                          
               <span id="LayerLetterFull" class="myStyle">
                   <img src= "xImages/Letters/L01.jpg" name="imgLetterFull">
               </span>
*/
function LayerShow(layer_obj, x, y) {
    //code for NN4
    if (document.layers && document.layers[layer_obj] != null) {
        document.layers[layer_obj].left = x;
        document.layers[layer_obj].top = y;
    //code for other browsers
    } else if (document.all) {
        document.all[layer_obj].style.posLeft = x;
        document.all[layer_obj].style.posTop = y;
    }
    //code for NN4
    if (document.layers && document.layers[layer_obj] != null) {
        document.layers[layer_obj].visibility = 'visible';
    //code for other browsers
    } else if (document.all) {
        document.all[layer_obj].style.visibility = 'visible';
    }        
}



function LayerHide(layer_obj) {
    if (document.layers && document.layers[layer_obj] != null) {
        document.layers[layer_obj].visibility = 'hidden';
    } else if (document.all) {
        document.all[layer_obj].style.visibility = 'hidden';
    }
}




/* Return the file path and name (extension removed) */  
function FilePathName(file_path_name_ext) {
    var i;
    var file_name_substr = "";
    for (i=0; (i<file_path_name_ext.length) && (file_path_name_ext.substr(i,1)!="."); i++) {
        file_name_substr = file_name_substr +  file_path_name_ext.substr(i,1);
    }
    return file_name_substr;
}



/* Return the file name and extension (path removed) */  
function FileNameExt(file_path_name_ext) {
    var i;
    var file_name_ext;
    file_name_ext = "";
    for (i=file_path_name_ext.length - 1; (i>=0) && (file_path_name_ext.substr(i,1)!="\/") && (file_path_name_ext.substr(i,1)!="\\"); i--) {
        file_name_ext = file_path_name_ext.substr(i,1) + file_name_ext;
    }
    return file_name_ext;
}



/* Return the file name (path and extension removed) */  
function FileName(file_path_name_ext) {
    var i;
    var file_name_ext = FileNameExt(file_path_name_ext);
    var file_name;
    file_name = "";
    for (i=0; ((i<file_name_ext.length - 1) && (file_name_ext.substr(i,1)!=".")); i++) {
        file_name = file_name + file_name_ext.substr(i,1);
    }
    return file_name;    
}



/* Return the extension (path and file name and dot '.' removed) */  
function FileExt(file_path_name_ext) {
    var i;
    var file_ext;
    file_ext = "";
    for (i=file_path_name_ext.length - 1; (i>=0) && (file_path_name_ext.substr(i,1)!="."); i--) {
        file_ext = file_path_name_ext.substr(i,1) + file_ext;
    }
    return file_ext;    
}




/* does the file_name end in fileextension? */
function IsFileExtension(file_name, file_extension) {
	return FileExt(file_name).toUpperCase() == file_extension.toUpperCase();
}   
 
 

function PadZeroLeft(x, width) {
	if (width = 2) {
		if (x < 10) {
			return "0" + x;
		} else {
			return "" + x;
		}
	} else {
		return "" + x;
	}		
}                       



/* function to identify if a plug in has been installed as of 2003/09/11 this function is not working */
function IsMimeType(mime_type) {
	mime_type = mime_type.toLowerCase();
	alert(navigator.mimeTypes[0]);
	alert(navigator.mimeTypes[1]);
	alert(navigator.mimeTypes[2]);
	
	if (navigator.mimeTypes[mime_type].toLowerCase()) {
		return true;
	} else {
		return false;
	}
}



/* to defeat bots looking to "scrape" email addresses from our page I am hiding them in this Java Script routine */
function GetEmailMailTo(emailaddress) {
	return "<a href=\"mailto:" + emailaddress + "@" + EMAIL_DOMAIN + "\">" + emailaddress + "@" + EMAIL_DOMAIN + "</a>";
}	



/* to defeat bots looking to "scrape" email addresses from our page I am hiding them in this Java Script routine */
function GetEmailMailTo2(emailaddress) {
	return "mailto:" + emailaddress + "@" + EMAIL_DOMAIN;
}






/* for a very simple roll over implementation use these three functions (along with helper functions FindImageObjBySrc, FilePathName
   and FileExt. Note that images have to conform to the following naming convention: the rollover image file name must be the same 
   as the roll out image file name except with a suffix on the name that is equal to ROLLOVER_IMAGE_SUFFIX 
   Usage (in html file do the following):
   	    <script>
           jRoll( "http://www.buses.org", "_blank", "xImages/LogoABA.jpg",  "border=0 alt='American Bus Association'" );  
   	    <script>
   Note: there would have to be two image files xImagaes/LogoABA.jpg and xImagaes/LogoABA_OVER.jpg     
*/
function jRoll(url, target, img_src, img_tags) {
	var html_code = "";
	html_code = html_code + "<a " + " href='" + url + "'" + " target=" + target;
	html_code = html_code + " onMouseOver=jRollOver('" + img_src + "')";
	html_code = html_code + " onMouseOut=jRollOut('" + img_src + "')>";
    html_code = html_code + "<img src='" + img_src + "' " + img_tags + ">";
    html_code = html_code + "</a>";
    document.write(html_code);
}



function jRollOver(img_src) {
	var img_object = FindImageObjBySrc(img_src);
	var img_file = FilePathName(img_src);       
	var img_extn = FileExt(img_src);   
	if (img_object) {
		img_object.src = img_file + ROLLOVER_IMAGE_SUFFIX + "." + img_extn;
	}
}



function jRollOut(img_src) {
	var img_file = FilePathName(img_src);       
	var img_extn = FileExt(img_src);   
	var img_object = FindImageObjBySrc(img_file + ROLLOVER_IMAGE_SUFFIX + "." + img_extn);
	if (img_object) {
		img_object.src = img_src;
	}
}

