// ******************************************************************
// Tinh tuoi tu DOB
// ******************************************************************
function dobToAge(objDOB,objAge){
	if (objDOB.value!=""){
		if (!isDate(objDOB.value)){
			objDOB.value="";
			objDOB.focus();
			return;
		} else {
			var todayDate = new Date();
			var birthDate = new Date(objDOB.value);
			var age = todayDate.getFullYear() - birthDate.getFullYear();
			if (birthDate.getMonth()  > todayDate.getMonth() ) {
				age = age-1;
	    	} else if ( birthDate.getMonth() == todayDate.getMonth() && birthDate.getDate() > todayDate.getDate() ) {
		        age = age -1;
		    }
		    if (age<0) {
				alert("Invalid DOB.");
				objDOB.value="";
				objDOB.focus();
				return false;
			}
			objAge.value = age;
		}
	}
}
// ******************************************************************
// 
// ******************************************************************
function clearcontrol(obj,format)
{
	if (obj.value==format)
	{
		savevalue=obj.value;
		obj.value="";		
	}
}
// ******************************************************************
// Trim 1 string
// ******************************************************************
function trim(strText) {
    while (strText.substring(0,1) == ' ')
        strText = strText.substring(1, strText.length);

    while (strText.substring(strText.length-1,strText.length) == ' ')
        strText = strText.substring(0, strText.length-1);

   return strText;
}
// ******************************************************************
//
// ******************************************************************
function calc_age(objDOB,objAge,strEffectiveDate){
	var effectiveDate;;
	if (strEffectiveDate!=undefined) {
		effectiveDate = new Date(strEffectiveDate);
	} else {
		var txt_date = document.forms[0].effect_date;
		effectiveDate = new Date(txt_date.options[txt_date.selectedIndex].text);
	}
	if (validateDOB(objDOB,effectiveDate)){
		var birthDate = new Date(objDOB.value);
		age = effectiveDate.getFullYear() - birthDate.getFullYear();
		if (birthDate.getMonth()  > effectiveDate.getMonth() ) {
			age = age -1;
    	} else if ( birthDate.getMonth() == effectiveDate.getMonth() && birthDate.getDate() > effectiveDate.getDate() ) {
	        age = age -1;
	    }
	    if (!isNaN(age)){
			objAge.value = age;
		}
	}
}
// ******************************************************************
//
// ******************************************************************
function valid_date(obj_valid,begin_age,end_age){
	if ((obj_valid.value<begin_age)&&obj_valid.value!=""){
		alert("Age must be "+begin_age+" or more than "+begin_age+", please enter correct age or DOB or back to chose another plan type.");
		obj_valid.focus();
		return false;
	}
	else{
		if ((obj_valid.value>end_age)&&obj_valid.value!=""){
			alert("Age must be under "+end_age+", please enter correct age or DOB or back to chose another plan type.");
			obj_valid.focus();
			return false;
		}else{
			return true;
		}
	}
}
// ******************************************************************
// This function accepts a string variable and verifies if it is a
// proper date or not. It validates format matching either
// mm-dd-yyyy or mm/dd/yyyy. Then it checks to make sure the month
// has the proper number of days, based on which month it is.

// The function returns true if a valid date, false if not.
// ******************************************************************

function isDate(dateStr) {
	//var datePat = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
	var datePat = /^(\d{1,2})(\/)(\d{1,2})(\/)(\d{4})$/;
	var matchArray = dateStr.match(datePat); // is the format ok?

	if (matchArray == null) {
		//alert("Please enter date as either mm/dd/yyyy or mm-dd-yyyy.");
		alert("Please enter date as mm/dd/yyyy format.");
		return false;
	}

	var month = matchArray[1]; // parse date into variables
	var day = matchArray[3];
	var year = matchArray[5];

	if (month < 1 || month > 12) { // check month range
		alert("Month must be between 1 and 12.");
		return false;
	}

	if (day < 1 || day > 31) {
		alert("Day must be between 1 and 31.");
		return false;
	}

	if ((month==4 || month==6 || month==9 || month==11) && day==31) {
		alert("Month "+month+" doesn't have 31 days!");
		return false;
	}

	if (month == 2) { // check for february 29th
		var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
		if (day > 29 || (day==29 && !isleap)) {
			alert("February " + year + " doesn't have " + day + " days!");
			return false;
		}
	}
	return true; // date is valid
}
// ******************************************************************
//Detect popup blocker
//Output: true if using blocking software
// ******************************************************************
function popUpsBlocked(){
	var mine = window.open('','','width=1,height=1,left=0,top=0,scrollbars=no');
	var popUpsBlocked;
	if(mine){
		popUpsBlocked = false;
		mine.close();
	} else
    	popUpsBlocked = true;
 	if(popUpsBlocked) alert('We have detected that you are using popup blocking software.');
}
// ******************************************************************
//Su dung cho tinh hop le cua 1 form 
//Input : Ten cua form validate_form(<ten cua form>)
//        Name cua input field phai co chua 1 trong nhung chuoi : email, phone, zipcode, birth, ssn, age
//        Required input field : co chua chuoi NEEDVALUE
// *****************************************************************
function validate_form(form_name)
{
	var mainstring;
	var obj_form=document.forms[form_name];
	for(var i=0;i<obj_form.length;i++)
	{
		mainstring=obj_form.elements[i].name;
        if (mainstring==null){continue;}
		if (mainstring.search(/email/)>=0)
		{
			var filter=/^.+@.+\..{2,3}$/
			if (obj_form.elements[i].value!=""){
				if (!filter.test(obj_form.elements[i].value)){
					alert("Please enter a valid email address");
					obj_form.elements[i].focus();
					return false;
				}
			}
		}
		//Kiem tra nhap lieu cua zipcode
		if (mainstring.search(/zipcode/)>=0)
		{
			var filter=/^[0-9][0-9][0-9][0-9][0-9]$/
			var filter2=/^[0-9][0-9][0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]$/
			if (obj_form.elements[i].value!='')
			{
				if (!(filter.test(obj_form.elements[i].value)||filter2.test(obj_form.elements[i].value))){
					alert("Please enter a valid Zip code");
					obj_form.elements[i].focus();
					return false;
				}
			}
		}
		//Kiem tra viec nhap ngay thang dung khuon dang hay khong ?
		if (mainstring.search(/birth/)>=0){
			if (obj_form.elements[i].value=='mm/dd/yyyy'){
				obj_form.elements[i].value='';
			}
			if (obj_form.elements[i].value!='')
			{
				if (!isDate(obj_form.elements[i].value)){
					obj_form.elements[i].focus();
					return false;
				}
			}
		}
		//Kiem tra nhap SSN
		if (mainstring.search(/ssn/)>=0)
		{
			var filter=/^\d{3}-\d{2}-\d{4}$/
			
			if (obj_form.elements[i].value!='')
			{
				if (!filter.test(obj_form.elements[i].value))
				{
					alert("SSN must be input format XXX-XX-XXXX\nExample: 564-45-2474" );
					obj_form.elements[i].focus();
					return false;
				}
			}
		}
		//Kiem tra nhap dinh dang so Phone
		if (mainstring.search(/phone/)>=0||mainstring.search(/mobi/)>=0||mainstring.search(/fax/)>=0)
		{
			var filter=/^\d{3}-\d{3}-\d{4}$/
			
			if (obj_form.elements[i].value!='')
			{
				if (!filter.test(obj_form.elements[i].value))
				{
					alert("Phone must be input format XXX-XXX-XXXX\nExample: 714-396-7651" );
					obj_form.elements[i].focus();
					return false;
				}
			}
		}
		//Kiem tra nhap dinh dang age
		if (mainstring.search(/age\b/)>=0)
		{
			var filter=/^\d*$/
				if (obj_form.elements[i].value!=""){
					if (!filter.test(obj_form.elements[i].value)){
						alert("Wrong age!");
						obj_form.elements[i].focus();
						return false;
					}
				}
		}
		//Nhung ID co chua chuoi NEEDVALUE la bat buoc input du lieu
		if (obj_form.elements[i].id.indexOf('NEEDVALUE')!=-1)
		{
			if (obj_form.elements[i].value=='')
			{
				// Xac dinh cac input co' id co' dang: NEEDVALUE_name de focus va dua ra chi'nh xa'c cau thong ba'o
                var inputName = obj_form.elements[i].id.substring(10,obj_form.elements[i].id.length)
                if (inputName != '') alert(inputName+" is required field.");
                else alert("You must input data here !");
				obj_form.elements[i].focus();
				return false;
			}
		}
	}
	return true;
}

//
function confim(){
var accept =window.confirm('Are you sure ?');
	if (accept)
	{
		return true;
	}
	else
	{
		return false;
	}
}
// ******************************************************************
//Validate email
// ******************************************************************
function validate_email(email_address){
	var filter=/^.+@.+\..{2,3}$/
	if (email_address.value!=""){	
	 	if (filter.test(email_address.value)){
    		return true;
    	}
	 	else {
	    	alert("Please enter a valid email address");
	    	email_address.focus();
    		return false;
    	}
	}
}
// ******************************************************************
//Validate zipcode
// ******************************************************************
function validate_zipcode(zipcode){
	var filter=/^[1-9][0-9][0-9][0-9][0-9]$/
 	if (filter.test(zipcode.value)){
   		return true;
   	}
 	else {
    	alert("Please enter a valid Zip code");
    	zipcode.focus();
   		return false;
   	}
}	
// ******************************************************************
//validate DOB
//input : field DOB, string of effec
// ******************************************************************
function validateDOB(objDOB,effectiveDate){
		if ((objDOB.value!="") && (objDOB.value!="mm/dd/yyyy")){
			var birthDate = new Date(objDOB.value);
			if (!isDate(objDOB.value)){
				objDOB.focus();
				return false;
			}
			else if ((effectiveDate-birthDate)<=0) {
				alert("DOB must be less than effective date.");
				objDOB.focus();
				return false;
			}
			return true;
		}
		else{
			objDOB.value="mm/dd/yyyy";
			return false;
		}
}
function validate_date(objDATE){
	if ((objDATE.value!="") && (objDATE.value!="mm/dd/yyyy")){
		if (!isDate(objDATE.value)){
			objDATE.focus();
		}
	}
}
// ******************************************************************
//Popup Window
// ******************************************************************
function popupWindow(url,width, height, top, left) {
	window.open(url,'','toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,copyhistory=no,width=' + width + ',height=' + height + ',screenX=50,screenY=50,top=' + top + ',left=' + left);
}

function getSelect()
{
	var txt = '';
	if (window.getSelection)
	{
		txt = window.getSelection();
	}
	else if (document.getSelection)
	{
		txt = document.getSelection();
	}
	else if (document.selection)
	{
		txt = document.selection.createRange().text;
	}
	else return;
	return txt;
}

function setBold(){
	document.selection.createRange().text = '<b>'+getSelect()+'</b>';
}
function setIlatic(){
	document.selection.createRange().text = '<i>'+getSelect()+'</i>';
}
function setSub(){
	document.selection.createRange().text = '<sup>'+getSelect()+'</sup>';
}
function setFontSize(size){
	document.selection.createRange().text = '<font size="'+size+'">'+getSelect()+'</font>';
}
function setFontColor(color){
	document.selection.createRange().text = '<font color="'+color+'">'+getSelect()+'</font>';
}

// Shortterm
function check_payment_option(ob){
	ob.status=true;
}
function st_singlePaymentStartDateChange(targetForm, startDateControl, notSelectFirst){
	var index = startDateControl.selectedIndex;
	var endDateControl = targetForm.elements["last_day_cover"];
	var endDate = endDateControl.options[endDateControl.selectedIndex].value;

	var dayRangeStart = st_getSinglePaymentDayRangeStart();
	var dayRangeEnd = st_getSinglePaymentDayRangeEnd(targetForm);

	st_genSinglePaymentEndDates(startDateControl.options[index].text, endDateControl, dayRangeStart, dayRangeEnd);
	if(!notSelectFirst)
		endDateControl.options[0].selected = true;
	else
		st_selecteSinglePaymentEndDate(endDateControl, endDate);
}

function st_selecteSinglePaymentEndDate(endDateControl, targetDate){
	for(i=0;i<	endDateControl.options.length;i++){
		if(endDateControl.options[i].value==targetDate){
			endDateControl.options[i].selected = true;
		}
	}

}

function st_getDateYear(date){
	var year = date.getYear();
	if(year < 1900){
		return year+1900;
	}
	return year;
}

function st_dateToString(date){
	var month = date.getMonth()+1;
	if(month < 10)month = '0' + month;
	var day = date.getDate();
	if(day < 10)day = '0' + day;
	return month+"/"+ day +"/"+st_getDateYear(date);
}

function st_genSinglePaymentEndDates(dateString, endDateControl, dayRangeStart, dayRangeEnd){
	var spEndLength = dayRangeEnd - dayRangeStart + 1;//156; //range of single payment end dates
	var date = new Date(dateString);
	date.setDate(date.getDate() + dayRangeStart);
	endDateControl.options.length = spEndLength;
	for(i=0;i<spEndLength;i++){
		endDateControl.options[i].text = st_dateToString(date);
		endDateControl.options[i].value = endDateControl.options[i].text;
		date.setDate(date.getDate()+1);
	}
}

function st_getSinglePaymentDayRangeStart(){
	return 30;
}

function st_getSinglePaymentDayRangeEnd(targetForm){
	//targetForm.elements['mcei.appl.Save.ZIP'].value;    // the zip value
	return 365;
}
function FormatNumber(num, format, shortformat)
{
	if(format==null)
	{
		format = "(###) ###-#### ";
	}
	if(shortformat==null)
	{
		var shortformat = "";
	}

	var validchars = "0123456789";
	var tempstring = "";
	var returnstring = "";
	var extension = "";
	var tempstringpointer = 0;
	var returnstringpointer = 0;
	count = 0;

	var length = num.value.length;



	if (length > format.length)
	{
		length = format.length;
	};


	for (var x=0; x<length; x++)
	{
		if (validchars.indexOf(num.value.charAt(x))!=-1)
		{
		tempstring = tempstring + num.value.charAt(x);
		};
	};

	if (num.value.length > format.length)
	{
		length = format.length;
		extension = num.value.substr(format.length, (num.value.length-format.length));
	};


	for (x=0; x<shortformat.length;x++)
	{
		if (shortformat.substr(x, 1)=="#")
		{
			count++;
		};
	}
	if (tempstring.length <= count)
	{
		format = shortformat;
	};



	for (x=0; x<format.length;x++)
	{
		if (tempstringpointer <= tempstring.length)
		{
			if (format.substr(x, 1)=="#")
			{
				returnstring = returnstring + tempstring.substr(tempstringpointer, 1);
				tempstringpointer++;
			}else{
				returnstring = returnstring + format.substr(x, 1);
			}
		}

	}


		returnstring = returnstring + extension;


	num.value = returnstring;
}
// ******************************************************************
//Change gender : Male <-> Female
// ******************************************************************
function doApplicantGenderChange(this_form) {
	if (this_form.spouse_sex){
	if (this_form.app_sex.selectedIndex == 0) {
		this_form.spouse_sex.selectedIndex = 1;
	}
	else {
		this_form.spouse_sex.selectedIndex = 0;
	}
	}
}
function doSpouseGenderChange(this_form) {
	if (this_form.spouse_sex.selectedIndex == 0) {
		this_form.app_sex.selectedIndex = 1;
	}
	else {
		this_form.app_sex.selectedIndex = 0;
	}
	return true;
}

function popupWindow(url) {
  popup_window = window.open(url,'popupWindow','toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=no,copyhistory=no,width=490,height=350,screenX=0,screenY=0,top=0,left=0')
	popup_window.focus();
	if (!popup_window.opener) popup_window.opener=self;
}
function popup_window_full(page){
	window.open(page, '_blank', 'toolbar=yes,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,copyhistory=no,width=640,height=800,screenX=0,screenY=0,top=0,left=0');
}
// ******************************************************************
//Chuyen tat ca cac gia tri trong form thanh chuoi GET
// ******************************************************************
function buildPOST(theFormName) {
    theForm = document.forms[theFormName];
    var qs = ''
    for (e=0;e<theForm.elements.length;e++) {
        if (theForm.elements[e].name!='') {
            if((theForm.elements[e].type == "radio") && (!theForm.elements[e].checked)) {
            	continue;
            }
            if((theForm.elements[e].type == "checkbox") && (!theForm.elements[e].checked)) {
            	continue;
            }
            var name = theForm.elements[e].name;
            qs+=(qs=='')?'':'&'
            qs+= name+'='+escape(theForm.elements[e].value);
        }
    }
    qs+="\n";
    return qs
}

function highlight_div(checkbox_node){
    label_node = checkbox_node.parentNode;
    if (checkbox_node.checked)
	{
		label_node.style.backgroundColor='#0a246a';
		label_node.style.color='#fff';
	}
	else
	{
		label_node.style.backgroundColor='#fff';
		label_node.style.color='#000';
	}
}

function popupwindow(url)
{
	var w = 800, h = 600, popW = 560, popH = 420;

	if (document.all || document.layers) {
  		w = screen.availWidth;
  		h = screen.availHeight;
	}
	popW = w * 0.6;
	popH = h * 0.5;
	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=1,resizable=1,width=" + popW + ",height=" + popH + ",top=" + topPos + ",left=" + leftPos);
	link.focus();
}

function popupSummary(url){
	var link = window.open(url, "link", "toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=1,width=100,height=100,top=0,left=0");
	link.focus();
}

function preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.p) d.p=new Array();
    var i,j=d.p.length,a=preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.p[j]=new Image; d.p[j++].src=a[i];}}
}

function focusMe(OnTop)
{
	if (OnTop == true) setTimeout("self.focus()",250);
}

function getCookie(NameOfCookie){
    if (document.cookie.length > 0) {
    begin = document.cookie.indexOf(NameOfCookie+"=");
    if (begin != -1) {
      begin += NameOfCookie.length+1;
      end = document.cookie.indexOf(";", begin);
      if (end == -1) end = document.cookie.length;
        return unescape(document.cookie.substring(begin, end));
    }
  }
  return null;
}

function setCookie(NameOfCookie, value, expiredays) {
var ExpireDate = new Date ();
ExpireDate.setTime(ExpireDate.getTime() + (expiredays * 24 * 3600 * 1000));

  document.cookie = NameOfCookie + "=" + escape(value) +
  ((expiredays == null) ? "" : "; expires=" + ExpireDate.toGMTString());
}

function delCookie (NameOfCookie) {
  if (getCookie(NameOfCookie)) {
    document.cookie = NameOfCookie + "=" + "; expires=Thu, 01-Jan-70 00:00:01 GMT";
  }
}

function Set_Cookie( name, value, expires, path, domain, secure ) {
	// set time, it's in milliseconds
	var today = new Date();
	today.setTime( today.getTime() );
	// if the expires variable is set, make the correct expires time, the
	// current script below will set it for x number of days, to make it
	// for hours, delete * 24, for minutes, delete * 60 * 24
	if ( expires )
	{
		expires = expires * 1000 * 60 * 60 * 24;
	}
	//alert( 'today ' + today.toGMTString() );// this is for testing purpose only
	var expires_date = new Date( today.getTime() + (expires) );
	//alert('expires ' + expires_date.toGMTString());// this is for testing purposes only

	document.cookie = name + "=" +escape( value ) +
		( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + //expires.toGMTString()
		( ( path ) ? ";path=" + path : "" ) + 
		( ( domain ) ? ";domain=" + domain : "" ) +
		( ( secure ) ? ";secure" : "" );
}