/********************************************************************
* Copyright ©  Acsys, Inc.  All rights reserved.
* 
* This material contains the valuable properties and trade secrets of
* Acsys, Inc. embodying substantial creative efforts and confidential 
* information, ideas, and expressions, no part of which may be 
* reproduced or transmitted in any form or by any means, electronic, 
* mechanical, or otherwise, including photocopying and recording or 
* in connection with any information storage or retrieval system 
* without the permission in writing of Acsys, Inc.
*/

/********************************************************************
* This is the main Acsys javascript library. When working with any
* of the javascript libraries, it is recommended that you include
* this file first. 
*
* This library also defines a class for sniffing the browser type, 
* javascript support and flash plug-in support. This is roughly meant 
* to be a client side browser capabilities object.
* 
* It also establishes a window global variable called "querystring"
* which you can use for simplied access to those parameters.
*/

/********************************************************************
* 
* Dependencies: 
*	None
*
* Create global "namespace" for Acsys.  This will hopefully prevent
* the naming collisions and other issues recently experienced due to
* the myriad of third party javascript libraries plugging in to 
* various projects.
*/

var Acsys = {};

// Global variables defined in the Acsys namespace
Acsys.Globals = {
	OnLoadFunctions:	[],
	OnLoadHandled:		false
};

Acsys.BrowserCapabilities = function()
{
	this.Init();
}

Acsys.BrowserCapabilities.prototype = 
{
	UNKNOWN: 
	{
		BROWSER:	"Unknown Browser",
		VERSION:	parseFloat("-1"),
		OS:			"Unknown OS"
	},
	Init: function()
	{
		this.browser = this.SearchString(this.BrowserDefinitions) || this.UNKNOWN.BROWSER;
		this.version = this.SearchVersion(navigator.userAgent) ||
			this.SearchVersion(navigator.appVersion) ||
			this.UNKNOWN.VERSION;
		this.OS = this.SearchString(this.OSDefinitions) || this.UNKNOWN.OS;
		this.Is = 
		{
			Mac:		this.OS == "Mac",
			Windows:	this.OS == "Windows",
			Linux:		this.OS == "Linux",
			OmniWeb:	this.browser == "OmniWeb",
			Safari:		this.browser == "Safari",
			Opera:		this.browser == "Opera",
			ICE:		this.browser == "ICE",
			iCab:		this.browser == "iCab",
			Konqueror:	this.browser == "Konqueror",
			FireFox:	this.browser == "Firefox",
			Camino:		this.browser == "Camino",
			Netscape:	this.browser == "Netscape",
			IE:			this.browser == "Explorer",
			Mozilla:	this.browser == "Mozilla",
			Dom:		document.getElementById != null
		};
	},
	SearchString: function(browsers)
	{
		for (var i = 0, length = browsers.length; i < length; i++)
		{
			var browserString = browsers[i].string;
			var browserProp = browsers[i].prop;
			this.versionSearchString = browsers[i].versionSearch || browsers[i].identity;
			
			if (browserString)
			{
				if (browserString.indexOf(browsers[i].subString) != -1)
				{
					return browsers[i].identity;
				}
			}
			else if (browserProp)
			{
				return browsers[i].identity;
			}
		}
		return null;
	},
	
	SearchVersion: function(data)
	{
		var index = data.indexOf(this.versionSearchString);
		return (index == -1) 
			? null
			: parseFloat(data.substring(index + this.versionSearchString.length + 1));
	},
	
	BrowserDefinitions: 
	[
		{ identity: "OmniWeb",	string: navigator.userAgent,	subString: "OmniWeb",	versionSearch: "OmniWeb/",	prop: null },
		{ identity: "Safari",	string: navigator.vendor,		subString: "Apple",		versionSearch: null,		prop: null },
		{ identity: "Opera",	string: null,					subString: null,		versionSearch: null,		prop: window.opera },
		{ identity: "ICE",		string: null,					subString: null,		versionSearch: null,		prop: (window.ScriptEngine && window.ScriptEngine().indexOf('InScript') != -1) },
		{ identity: "iCab",		string: navigator.vendor,		subString: "iCab",		versionSearch: null,		prop: null },
		{ identity: "Konqueror",string: navigator.vendor,		subString: "KDE",		versionSearch: null,		prop: null },
		{ identity: "Firefox",	string: navigator.userAgent,	subString: "Firefox",	versionSearch: null,		prop: null },
		{ identity: "Camino",	string: navigator.vendor,		subString: "Camino",	versionSearch: null,		prop: null },
		{ identity: "Netscape",	string: navigator.userAgent,	subString: "Netscape",	versionSearch: null,		prop: null },
		{ identity: "Explorer",	string: navigator.userAgent,	subString: "MSIE",		versionSearch: "MSIE",		prop: null },
		{ identity: "Mozilla",	string: navigator.userAgent,	subString: "Gecko",		versionSearch: "rv",		prop: null },
		// for versions of Netscape 4 and below
		{ identity: "Netscape",	string: navigator.userAgent,	subString: "Mozilla",	versionSearch: "Mozilla",	prop: null }
	],
	OSDefinitions:
	[
		{ identity: "Windows",	string: navigator.platform,		subString: "Win" },
		{ identity: "Mac",		string: navigator.platform,		subString: "Mac" },
		{ identity: "Linux",	string: navigator.platform,		subString: "Linux" }
	]
};

Acsys.ParseQueryString = function()
{
	var parameters = {};
	var rawQueryString = window.location.search.substring(1);
	var pairs = rawQueryString.split("&");
	
	for (var i = 0, length = pairs.length; i < length; i++)
	{
		var pair = pairs[i].split("=");
		var parameterName = unescape(pair[0]);
		var parameterValue = unescape(pair[1]);
		
		if (parameters[parameterName])
		{
			if (typeof(parameters[parameterName]) == "string")
			{
				var values = [];
				values[values.length] = parameters[parameterName];
				parameters[parameterName] = values;
			}
			parameters[parameterName][parameters[parameterName].length] = parameterValue;
		}
		else
		{
			parameters[parameterName] = parameterValue;
		}
	}
	
	return parameters;
}

// Provides easy access to querystring parameters
Acsys.QueryString = Acsys.ParseQueryString();
// Browser detection and capabilities object
Acsys.Browser = new Acsys.BrowserCapabilities();

Acsys.Events = {};

Acsys.Events.WindowOnload = function()
{
	for (var i=0,len=Acsys.Globals.OnLoadFunctions.length;
		i<len;
		eval(Acsys.Globals.OnLoadFunctions[i++])
	);
}

Acsys.Events.EventCache = function() 
{
	var registeredList = [];
	
	return {
		RegisteredList: registeredList ,
		Add: function(targetObj, eventName, handler, capture)
		{
			registeredList[registeredList.length] = 
				new Acsys.Events.EventCacheEntry(this, targetObj, eventName, handler, capture);

			if (targetObj.addEventListener)
			{
				targetObj.addEventListener(eventName, handler, capture);
			}
			else if (targetObj.attachEvent)
			{
				targetObj.attachEvent('on' + eventName, handler);
			}
			else
			{
				var existingHandler = targetObj['on' + eventName];
				
				targetObj['on' + eventName] = function()
				{
					if (typeof(existingHandler) == "function")
					{
						existingHandler();
					}
					handler();
				};
			}
		} ,
		Flush: function()
		{
			var cacheItem = null;
			for (var i = registeredList.length - 1; i >= 0; i--)
			{
				cacheItem = registeredList[i];
				
				if(cacheItem.TargetObj.removeEventListener)
				{
					cacheItem.TargetObj.removeEventListener(cacheItem.EventName, cacheItem.Handler, cacheItem.Capture);
				}
				
				///* From this point on we need the event names to be prefixed with 'on"
				if(cacheItem.EventName.substring(0, 2) != "on")
				{
					cacheItem.EventName = "on" + cacheItem.EventName;
				}
				
				if(cacheItem.TargetObj.detachEvent)
				{
					cacheItem.TargetObj.detachEvent(cacheItem.EventName, cacheItem.Handler);
				}
				
				cacheItem.TargetObj[cacheItem.EventName] = null;
			}
		}
	};
}

Acsys.Events.EventCacheEntry = function(cache, targetObj, eventName, handler, capture) 
{
	this.Cache = cache;
	this.TargetObj = targetObj;
	this.EventName = eventName;
	this.Handler = handler;
	this.Capture = capture;
}

Acsys.Events.AddHandler = function(targetObj, eventName, handler, capture)
{
	if(!Acsys.Globals.EventCache)
	{
		Acsys.Globals.EventCache = new Acsys.Events.EventCache();
		Acsys.Globals.EventCache.Add(window, Acsys.Events.BomEvents.UnLoad, Acsys.Globals.EventCache.Flush, false);
	}
	
	Acsys.Globals.EventCache.Add(targetObj, eventName, handler, capture);
}

Acsys.Events.DomEvents =
{
	Click:			"click",
	DoubleClick:	"dblclick",
	MouseDown:		"mousedown",
	MouseUp:		"mouseup",
	MouseOver:		"mouseover",
	MouseMove:		"mousemove",
	MouseOut:		"mouseout",
	KeyPress:		"keypress",
	KeyDown:		"keydown",
	KeyUp:			"keyup"
};

Acsys.Events.BomEvents =
{
	Load:		"load",
	UnLoad:		"unload",
	Abort:		"abort",
	Error:		"error",
	Resize:		"resize",
	Scroll:		"scroll"
};

Acsys.Events.FormEvents =
{
	Select:		"select",
	Change:		"change",
	Submit:		"submit",
	Reset:		"reset",
	Focus:		"focus",
	Blur:		"blur"
};

/********************************************************************
* The input argument must be a string type.
*/
function AddWindowOnload(f)
{
	if (typeof(f) != "string") return;
	Acsys.Globals.OnLoadFunctions[Acsys.Globals.OnLoadFunctions.length] = f;
	
	if (!Acsys.Globals.OnLoadHandled)
	{
		Acsys.Events.AddHandler(window, Acsys.Events.BomEvents.Load, Acsys.Events.WindowOnload, false);
		Acsys.Globals.OnLoadHandled = true;
	}
}

function isValidEmail(email, required) {
    if (required==undefined) {   // if not specified, assume it's required
        required=true;
    }
    if (email==null) {
        if (required) {
            return false;
        }
        return true;
    }
    if (email.length==0) {  
        if (required) {
            return false;
        }
        return true;
    }
    if (! allValidChars(email)) {  // check to make sure all characters are valid
        return false;
    }
    if (email.indexOf("@") < 1) { //  must contain @, and it must not be the first character
        return false;
    } else if (email.lastIndexOf(".") <= email.indexOf("@")) {  // last dot must be after the @
        return false;
    } else if (email.indexOf("@") == email.length) {  // @ must not be the last character
        return false;
    } else if (email.indexOf("..") >=0) { // two periods in a row is not valid
	return false;
    } else if (email.indexOf(".") == email.length) {  // . must not be the last character
	return false;
    }
    return true;
}


function allValidChars(email) {
  var parsed = true;
  var validchars = "abcdefghijklmnopqrstuvwxyz0123456789@.-_";
  for (var i=0; i < email.length; i++) {
    var letter = email.charAt(i).toLowerCase();
    if (validchars.indexOf(letter) != -1)
      continue;
    parsed = false;
    break;
  }
  return parsed;
}

function getQueryVariable(variable) {
  var query = window.location.search.substring(1);
  var vars = query.split("&");
  for (var i=0;i<vars.length;i++) {
    var pair = vars[i].split("=");
    
    if (pair[0] == variable) {
      return pair[1];
    }
    else {
     
    }
  
  } 
  return "";
}

function findControl(controlid)
{

	for (y=0; y < document.forms.length;y++)
	{
	f = document.forms[y] ;	
	for (r=0;r < f.length ; r++)
	{	
		if (f.elements[r].id.indexOf(controlid) > -1 )
		{
			return f.elements[r].id ;
		}	
	}
	}
}

// Declaring valid date character, minimum year and maximum year
var dtCh= "/";
var minYear=1900;
var maxYear=2100;


// Declaring required variables
var digits = "0123456789";
// non-digit characters which are allowed in phone numbers
var phoneNumberDelimiters = "()- ";
// characters which are allowed in international phone numbers
// (a leading + is OK)
var validWorldPhoneChars = phoneNumberDelimiters + "+";
// Minimum no of digits in an international phone no.
var minDigitsInIPhoneNumber = 10;


function iSSSNValidation(ssn) {
var matchArr = ssn.match(/^(\d{3})-?\d{2}-?\d{4}$/);
var numDashes = ssn.split('-').length - 1;
if (matchArr == null || numDashes == 1) {
    return false;
//msg = "does not appear to be valid";
}
else 
if (parseInt(matchArr[1],10)==0) {
//alert("Invalid SSN: SSN's can't start with 000.");
    return false;

}
else {
        return true;
   }
}


function isDate(dtStr){
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strMonth=dtStr.substring(0,pos1)
	var strDay=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	if (pos1==-1 || pos2==-1){
		//alert("The date format should be : mm/dd/yyyy")
		return false
	}
	if (strMonth.length<1 || month<1 || month>12){
		//alert("Please enter a valid month")
		return false
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		//alert("Please enter a valid day")
		return false
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		//alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear)
		return false
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		//alert("Please enter a valid date")
		return false
	}
return true
}


function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   } 
   return this
}


function checkInternationalPhone(strPhone)
{
s=stripCharsInBag(strPhone,validWorldPhoneChars);
return (isInteger(s) && s.length >= minDigitsInIPhoneNumber);
}

function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}
