/* jQuery browser detection */
var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{
			string: navigator.userAgent,
			subString: "Chrome",
			identity: "Chrome"
		},
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari",
			versionSearch: "Version"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			   string: navigator.userAgent,
			   subString: "iPhone",
			   identity: "iPhone/iPod"
	    },
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};
BrowserDetect.init();
// A function to open the FAQ pages

function openFaqIndex(page) {

    var userAgent = navigator.userAgent.toLowerCase();
	jQuery.browser = {
	    version: (userAgent.match( /.+(?:rv|it|ra|ie|me)[\/: ]([\d.]+)/ ) || [])[1],
	    chrome: /chrome/.test( userAgent ),
	    safari: /webkit/.test( userAgent ) && !/chrome/.test( userAgent ),
	    opera: /opera/.test( userAgent ),
	    msie: /msie/.test( userAgent ) && !/opera/.test( userAgent ),
	    mozilla: /mozilla/.test( userAgent ) && !/(compatible|webkit)/.test( userAgent )
	    
	};
		
		var so = BrowserDetect.OS;
        var height;
        var width;
        if($.browser.chrome){
        	if(so=='Linux'){
                height = "height=615";
                width = "width=510";
           } else if (so=='Windows') {
                height = "height=557";
                width = "width=500";
           }
        } else {
             height = "height=550";
             width = "width=500";
        }
        
	var w = window.open(page,'faqWin',''+width +','+height+',status=no');
	w.focus();
}
// END function openFaqTop()
// A function to open the FAQ system to a particular page
function openFaqDetail(FaqID) {
	var w = window.open('faq_detail.php?FAQID='+FaqID, 'faqWin', 'width=500,height=550,status=no,resizeable=no');
	w.focus();
} // END function openFaqPage(FaqID)
// Image handling
if (document.images) {
	// browser supports Image object, so preload all images
	var pointer_dn			= new Image()
	pointer_dn.src		= "/img/pointer_dn_lg.gif"     // down arrow
	var pointer_rt			= new Image()
	pointer_rt.src		= "/img/pointer_rt_lg.gif"     // right arrow
} else {
	// browser does NOT support Image object, so set all image vals to ""
	// to prevent errors from arising in onMouseOver/onMouseOut handlers
	pointer_dn = ""; pointer_rt = "";
} // END if (document.images)

// A function to display or hide divs containing links
function setDiv(divName,imgName) {
	var alertMsg = '';
	div = document.getElementById(divName);
	img = document.getElementById(imgName);
	if (img.src == pointer_rt.src) {
		alertMsg = 'display was none';
		img.src=pointer_dn.src;
		div.style.display = 'block';
		div.style.clear = 'both';
	} else {
		alertMsg = 'display was block';
		img.src=pointer_rt.src;
		div.style.display = 'none';
	}
//	alert(alertMsg);
} // END function setDiv(divName,imgName)
// A function to scroll the current page to the top of elementId
function scrollTo(elementId) {
	e = document.getElementById(elementId);
	e.scrollIntoView();
}
/*
 * This function parses ampersand-separated name=value argument pairs from
 * the query string of the URL. It stores the name=value pairs in 
 * properties of an object and returns that object.
 *
 * Credit where credit is due: Taken from JavaScript, The Definitive Guide,
 * 3rd Ed., by David Flanagan, O'Reilly Publishers, 1998.
*/
function getArgs() {
	var args = new Object();
	var query = location.search.substring(1);     // Get query string.
	var pairs = query.split("&");                 // Break at comma.
	for(var i = 0; i < pairs.length; i++) {
		var pos = pairs[i].indexOf('=');          // Look for "name=value".
		if (pos == -1) continue;                  // If not found, skip.
		var argname = pairs[i].substring(0,pos);  // Extract the name.
		var value = pairs[i].substring(pos+1);    // Extract the value.
		args[argname] = unescape(value);          // Store as a property.
	}
	return args;                                  // Return the object.
}


// A utility function that returns true if a string contains only 
// whitespace characters.
function isblank(s) {
    for(var i = 0; i < s.length; i++) {
        var c = s.charAt(i);
        if ((c != ' ') && (c != '\n') && (c != '\t')) return false;
    }
    return true;
} // END function isblank(s) {

// return the value of the radio button that is checked
// return an empty string if none are checked, or
// there are no radio buttons
function getCheckedValue(radioObj) {
	if(!radioObj)
		return "";
	var radioLength = radioObj.length;
	if(radioLength == undefined)
		if(radioObj.checked)
			return radioObj.value;
		else
			return "";
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].checked) {
			return radioObj[i].value;
		}
	}
	return "";
}
function getSelectedRadio(buttonGroup) {
	// returns the array number of the selected radio button or -1 if no button is selected
	if (buttonGroup['form1']) { // if the button group is an array (one button is not an array)
		for (var i=0; i<buttonGroup.length; i++) {
			if (buttonGroup[i].checked) {
				return i;
			}
		}
	} else {
		if (buttonGroup.checked) {
			return 0;
		} // if the one button is checked, return zero
	}
	// if we get to this point, no radio button is selected
	return -1;
}
function getSelectedRadioValue(buttonGroup) {
	// returns the value of the selected radio button or "" if no button is selected
	var i = getSelectedRadio(buttonGroup);
	if (i == -1) {
		return "";
	} else {
		if (buttonGroup[i]) { // Make sure the button group is an array (not just one button)
			return buttonGroup[i].value;
		} else { // The button group is just the one button, and it is checked
			return buttonGroup.value;
		}
	}
} 

////////////// BEGIN Mozilla-Recommended Procedure for Launching Popups ////////////////////////////////
//	See http://developer.mozilla.org/en/docs/window.open#Best_practices for more

var WindowObjectReference = null; // global variable
var PreviousUrl; /* global variable which will store the url currently in the secondary window */

function openRequestedSinglePopup(strUrl) {
	
	if(WindowObjectReference == null || WindowObjectReference.closed) {
		WindowObjectReference = window.open(strUrl, "SingleSecondaryWindowName", "resizable=yes,scrollbars=yes,status=yes");
	} else if(previousUrl != strUrl) {
		WindowObjectReference = window.open(strUrl, "SingleSecondaryWindowName", "resizable=yes,scrollbars=yes,status=yes");
			/* if the resource to load is different, then we load it in the already opened secondary window and then
			we bring such window back on top/in front of its parent window. */
    WindowObjectReference.focus();
	} else {
		WindowObjectReference.focus();
	};
	PreviousUrl = strUrl;

		/* explanation: we store the current url in order to compare url in the event of another call of this function. */
}

// A dedicated modification for launching KQ Ind/Fam App Window:
// It seams it's only for California
function openKQPage() {
	var size;
	if($.browser.safari){
         size = "width=1020,height=1020";
    } else {
         size = "width=1020,height=1020";
    }
  //var strUrl = 'https://kaiser.healthinsurance-asp.com/expressweb/user/URLDecryptAction.action;jsessionid=cwI4PhFx9BkI+zSivCY2uA**.wa04_prod03?refID=bcg8nd4zamrbff9vvpclfhq7tbpkq77mpr39y9sn9ou8in842x7cs4i5u9i0tg';
	var strUrl = 'https://kaiser.healthinsurance-asp.com/expressweb/user/URLDecryptAction.action?refID=1864b226lfqqd3jybssyzz9f6bnp9y9kejgst7fdidnkbn8eed0ai5eliqevmg4h7mi2ckrxe0s&selectedPlanId=&zipCode=#4';
	if(WindowObjectReference == null || WindowObjectReference.closed) {
		WindowObjectReference = window.open(strUrl, "SingleSecondaryWindowName", "resizable=yes,scrollbars=yes,status=yes,"+size);
	} else if(previousUrl != strUrl) {
		WindowObjectReference = window.open(strUrl, "SingleSecondaryWindowName", "resizable=yes,scrollbars=yes,status=yes,"+size);
			/* if the resource to load is different, then we load it in the already opened secondary window and then
			we bring such window back on top/in front of its parent window. */
    WindowObjectReference.focus();
	} else {
		WindowObjectReference.focus();
	};
	PreviousUrl = strUrl;
		/* explanation: we store the current url in order to compare url in the event of another call of this function. */
}
////////////// END Mozilla-Recommended Procedure for Launching Popups ////////////////////////////////

////////////// BEGIN Series of functions to support QuoteIt Redirects, etc. ////////////////////////////////

function centeredWindow(url, popW, popH, features, returnWindowHandle) {
//	Copyright 2008 Quotit Corporation.	
	if(!features) {
		features = "toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=1";
	}	
	var w = 800, h = 600;
		
	if (document.all || document.layers) {
  		w = screen.availWidth;
  		h = screen.availHeight;
	}
	var leftPos = (w-popW)/2;
	var topPos = (h-popH)/2;
	features += ",width=" + popW + ",height=" + popH + ",top=" + topPos + ",left=" + leftPos;	
	link = window.open(url, "link", features);
//	try {
//		link.focus();
//	}
//	catch(ex) {}
	
	if(returnWindowHandle) {
		return link;
	}
}
function centeredDiffWindow(url, popW, popH, windowName) {
	
	var features
	var returnWindowHandle
	if(!features)
	{
		features = "toolbar=0,status=0,menubar=0,scrollbars=1,resizable=1";
	}	
	var w = 800, h = 600;
		
	if (document.all || document.layers) {
  		w = screen.availWidth;
  		h = screen.availHeight;
	}
	var leftPos = (w-popW)/2;
	var topPos = (h-popH)/2;
	features += ",width=" + popW + ",height=" + popH + ",top=" + topPos + ",left=" + leftPos;	
	
	
	var link = window.open(url, windowName, features);
	
	
	try
	{
	link.focus();
	}
	catch(ex)
	{
	}
	
	if(returnWindowHandle)
	{
		return link;
	}
}
function centeredWindowSettings(url, popW, popH, popScroll) {
	var w = 800, h = 600;
		
	if (document.all || document.layers) {
  		w = screen.availWidth;
  		h = screen.availHeight;
	}
	var leftPos = (w-popW)/2;
	var topPos = (h-popH)/2;
	var link = window.open(url, "link", "toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=" + popScroll + ",resizable=0,width=" + popW + ",height=" + popH + ",top=" + topPos + ",left=" + leftPos);
	try
	{
	link.focus();
	}
	catch(ex)
	{
	}
}

////////////// END Series of functions to support QuoteIt Redirects, etc. ////////////////////////////////

// A function to determine if a value is a valid month number, i.e., is an integer between 1 and 12, inclusive
function validMonth(n) {
	if ( (n < 1) || (n > 12) ) return false;
	return true;
} // END function validMonth(n)
// A function to determine if the number of days (n) is valid for a given month number (m)
function validDay(m,n) {
	var days = [31,29,31,30,31,30,31,31,30,31,30,31];
	if (n != parseInt(n,10)) return false;
	n = parseInt(n,10);
	if ( (n < 1) || (n > days[m-1]) ) return false;
	return true;
} // END function validDay(m,n)
// A function to determine if a year value is realistic - must be an integer between 1 and 99 or 1900 and current year number
function validYear(y) {
	// Check for possible leading zero: if present, remove
	if ( (y.length == 2) && (y.substr(0,1) == '0') ) {
		y = y.substr(1,1);
	}
	var currentTime = new Date();
	var curYear = currentTime.getFullYear();
	if (y != parseInt(y,10)) return false;
	y = parseInt(y,10);
	if (
		(y < 0) ||
		( (y > 99) && (y < 1900) ) ||
		(y > curYear)
	) return false;
	return true;
} // END function validYear(y)

function validate_email(emailStr) {
	emailStr = emailStr.toLowerCase();

	/* The following will hold our email error message for return to the calling function. */
	
	var emailErr = '';
	
	/* 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. */
	
	/* Original list:
	var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;
	*/
	/* List Updated 12/03/2008 from http://data.iana.org/TLD/tlds-alpha-by-domain.txt */
	var knownDomsPat=/^(ac|ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|asia|at|au|aw|ax|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cat|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|in|info|int|io|iq|ir|is|it|je|jm|jo|jobs|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mil|mk|ml|mm|mn|mo|mobi|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|rs|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tel|tf|tg|th|tj|tk|tl|tm|tn|to|tp|tr|travel|tt|tv|tw|tz|ua|ug|uk|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|xn|ye|yt|yu|za|zm|zw)$/;
	
	/* 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. */
		emailErr += "Email address seems incorrect (check @ and .'s)";
		return emailErr;
	}
	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) {
			emailErr += "The email username contains invalid characters.";
		return emailErr;
		}
	}

	for (i=0; i<domain.length; i++) {
		if (domain.charCodeAt(i)>127) {
			emailErr += "The email domain name contains invalid characters.";
			return emailErr;
	   }
	}

	// See if "user" is valid 
	
	if (user.match(userPat)==null) {
		// user is not valid
		emailErr += "The email username doesn't seem to be valid.";
		return emailErr;
	}
	
	/* 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) {
				emailErr += "The email destination IP address is invalid.";
				return emailErr;
		   }
		}
	}
	
	// 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) {
			emailErr += "The email address domain name does not seem to be valid.";
			return emailErr;
	   }
	}
	
	/* 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) {
		emailErr += "The email address must end in a recognized domain or two letter country.";
		return emailErr;
	}
	
	// Make sure there's a host name preceding the domain.
	
	if (len<2) {
		emailErr += "This email address is missing a hostname.";
		return emailErr;
	}

	return true;

}

// A generic function to format numbers as desired
//	Credit where credit is due:
//		From "Four Guys from Rolla" website
//		http://www.4guysfromrolla.com/webtech/code/FormatNumber.shtml
function FormatNumber(num,decimalNum,bolLeadingZero,bolParens,bolCommas)
/**********************************************************************
	IN:
		NUM - the number to format
		decimalNum - the number of decimal places to format the number to
		bolLeadingZero - true / false - display a leading zero for
										numbers between -1 and 1
		bolParens - true / false - use parenthesis around negative numbers
		bolCommas - put commas as number separators.
 
	RETVAL:
		The formatted number!
 **********************************************************************/
{ 
        if (isNaN(parseInt(num))) return "NaN";

	var tmpNum = num;
	var iSign = num < 0 ? -1 : 1;		// Get sign of number
	
	// Adjust number so only the specified number of numbers after
	// the decimal point are shown.
	tmpNum *= Math.pow(10,decimalNum);
	tmpNum = Math.round(Math.abs(tmpNum))
	tmpNum /= Math.pow(10,decimalNum);
	tmpNum *= iSign;					// Readjust for sign
	
	
	// Create a string object to do our formatting on
	var tmpNumStr = new String(tmpNum);

	// See if we need to strip out the leading zero or not.
	if (!bolLeadingZero && num < 1 && num > -1 && num != 0)
		if (num > 0)
			tmpNumStr = tmpNumStr.substring(1,tmpNumStr.length);
		else
			tmpNumStr = "-" + tmpNumStr.substring(2,tmpNumStr.length);
		
	// See if we need to put in the commas
	if (bolCommas && (num >= 1000 || num <= -1000)) {
		var iStart = tmpNumStr.indexOf(".");
		if (iStart < 0)
			iStart = tmpNumStr.length;

		iStart -= 3;
		while (iStart >= 1) {
			tmpNumStr = tmpNumStr.substring(0,iStart) + "," + tmpNumStr.substring(iStart,tmpNumStr.length)
			iStart -= 3;
		}		
	}

	// See if we need to use parenthesis
	if (bolParens && num < 0)
		tmpNumStr = "(" + tmpNumStr.substring(1,tmpNumStr.length) + ")";

	return tmpNumStr;		// Return our formatted string!
}


