var fd = formatDecimal;

function o(obj) 
{
	return document.getElementById(obj);
}

function multiply(obj1, obj2) {
	return formatDecimal(parseFloat(obj1.value) * parseFloat(obj2.value));
}

function multiply3(obj1, obj2, obj3) {
	return formatDecimal(parseFloat(obj1.value) * parseFloat(obj2.value) * parseFloat(obj3.value));
}

function scrub(element) {
	document.getElementsByAttribute('numeric', element).each(function(obj) {
		obj.value = removeChars(obj.value);
		if (obj.value == '') { obj.value = '0';}
	});
	document.getElementsByAttribute('money', element).each(function(obj) {
		obj.value = formatDecimal(removeChars(obj.value));
		if (obj.value == '') { obj.value = '0.00';}
	});
}

function ends_with(value, match) {
	if ( eval('/' + match + '$/.test(value)') ) { return true; }
	return false;
}

function starts_with(value, match) {
	if ( eval('/^' + match + '/.test(value)') ) { return true; }
	return false;
}

String.prototype.capitalize = function(){
    return this.replace(/\w+/g, function(a){
        return a.charAt(0).toUpperCase() + a.substr(1).toLowerCase();
    });
};

function f(value) {
	return parseFloat($(value).value);
}

function ov(field)
{
	try
	{
		return parseFloat(o(field).value) || 0.00;
	}
	catch ( e )
	{
		alert( e.description + ' : ' + field );
	}
}

// n is the span object
function stripMoney( n )
{
	return parseFloat( n.innerHTML.replace('$', '') );
}

function trim( s ) 
{
	if ( typeof(s) == "string" )
	{
		return s.replace( /(^\s+)([^\s]*)(\s+$)/, '$2' );		
	}
	return s;	
}

/*
function formatDecimal(n)
{
	if ( isNaN(n) ) { return '0.00'; }
	if ( /^\d+$/.test(n) ) { return n += '.00'; }
	
	var n = Math.round(n*100)/100;
	
	if ( n.toString().indexOf('.') == -1 )
	{
		n += '.00';
	}
	
	return n;
}
*/
function formatDecimal(num)
{
	num = num.toString().replace(/\$|\,/g,'');
	
	if(isNaN(num)) num = '0';
	
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	
	if(cents<10)
		cents = '0' + cents;

	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
		num = num.substring(0,num.length-(4*i+3)) + num.substring(num.length-(4*i+3));
	
	return (num + '.' + cents);
}

IsUndefined = function( obj )
{
	if ( typeof(obj) == "undefined" || typeof(obj) == "unknown" ) // || null
	{
		return true;
	}
	return false;	// not defined
};

IsDefined = function( obj )
{
	if ( obj == null )
	{
		return false;
	}
	return !IsUndefined( obj );
};

// add an onfocus event handler for every text field that needs to validate a numeric value
// also adds the help IFrame to every page
function SetOnFocusHandlers()
{
	var page = 	URLToFilename(window.location);
	
	// exclude from pages that dont need the functionality
	if ( page == 'default.asp' || page == 'main.asp' )
	{
			return;
	}
	var flds = document.getElementsByTagName("INPUT");

	for ( var i=0; i<flds.length; ++i )
	{
		var f = flds[i];
		var isOnBlur = false;
		
		try {var b = f.onblur.toString();isOnBlur = true;}
		catch(e) { isOnBlur = false; }
		
		//if ( f.getAttribute('type') == 'text' && IsDefined(f.onblur) )
		if ( f.getAttribute('type') == 'text' && isOnBlur )
		{
			// filter out phone number validation
			if ( f.onblur.toString().indexOf('formatPhone') == -1 )
			{
				f.onfocus = function() {lastActiveTextBox = this;};
			}
		}
	}
	
	try {	recalculate();} catch (e){}
	try {	init();} catch (e){}
	//try {MakeHelpFrame(); } catch(e){}
}

function URLToFilename( url )
{
		var s = new String(url);
		
		if ( s.length == 0 )
		{
				return 'Default.asp';
		}
		var spos = s.lastIndexOf( '/' );
		var epos = s.indexOf( '?' );
		
		epos = (epos == -1) ? s.length : epos;
		
		return s.substring( spos+1, epos ).toLowerCase();		
}

var lastActiveTextBox = null;

function FinalCheck()
{
	if ( lastActiveTextBox != null )
	{
		var b = new String(lastActiveTextBox.onblur.toString());
		
		var r = null;
	
		if ( b.indexOf('whole') >= 0 ) 		// integer
		{
			var r = new RegExp(/^\d+$/);
		}
		else if ( b.indexOf('txtblur') >= 0 ) // money
		{
			var r = new RegExp(/^\d+\.\d\d$/);
		}
		
		return (r.test(lastActiveTextBox.value)) ? 1 : 0;
	}
	return 1;
}
/*
function SetFocus( fieldName )
{
	//var field = document.getElementById(fieldName);
	var field = fieldName;
	field.focus();
	field.select();
}
*/
//s = s.replace( /[,]/g, '.' );
//s = s.replace( /[^\d\.]|[ ]/g, '' )
function txtblur( field, ignore, message )
{
	var v = trim( field.value );
	var r = false;

	// trim leading  zeroes
	if ( v != '0.00' )
	{
		v = v.replace( /^0+/, '' );
		field.value = v;
	}

	// if blank or a zero put in 0.00
	if ( v.length == 0 || v.value == '0' )
	{
		field.value = '0.00';
		r = true;
	}

	// if a valid whole number add a .00 to the end
	if ( /^\d+$/.test(v) )
	{
		v += '.00';
		field.value = v;
		r =  true;
	}
	
	// test for a valid money value with 2 decimal places
	if ( /^\d+\.\d\d$/.test(v) )
	{
		r = true;
	}

	if ( !r )
	{
		alert( message + ' is not a valid number.' );
		field.value = '0.00';
	}

	try
	{
		recalculate()
	}
	catch ( e ){	/*alert( e.description );*/}
	return r;
}

function txtblurwhole( field, ignore, message )
{
	var v = trim( field.value );
	var r = false;
	
	// trim leading  zeroes
	v = v.replace( /^0+/, '' );

	// if blank put in 0
	if ( v.length == 0 )
	{
		field.value = '0';
		r = true;
	}
	
	// if a valid whole number
	if ( /^\d+$/.test(v) )
	{
		field.value = v;
		r = true;
	}

	if ( !r )
	{
		alert( message + ' is not a valid number.' );
		field.value = '0';
	}
	
	try
	{
		recalculate();
	}
	catch ( e ){	/*alert( e.description );*/}
	return r;
}

function removeChars (txt)
{
	// strip anything that is NOT a number, NOT a period or IS whitespace
	return txt.replace( /[^\d\.]|[ ]/g, '' );
}

function show_popup(url, title, width, height) 
{
	if ( FinalCheck() == 1 )
	{
		vWinCal = window.open(url, title, "width=" + (parseInt(width) + 20) + ",height=" + height + ",status=no,resizable=no,scrollbars=yes,top=200,left=200");
		vWinCal.opener = self;
	}
}

function setnextpage() 
{
	o('nextpage').value = o('nextpagefile').value;
}

function formatPhone(num, allowBlank) 
{
	var tmp = '';
	var txt;
	
	txt = trim(num.value.toString());
	
	// the function was originally returning false for a phone number that it had already formatted
	// added this line to remove extra whitespace
	tmp =  txt.replace( /[^\d]|[ ]/g, '' );

	if (tmp.length == 10) 
	{
		num.value = '(' + tmp.substring(0, 3) + ') ' + tmp.substring(3, 6) + '-' + tmp.substring(6, 10);
		return true;
	} 
	else 
	{
		// check for the allowBlank argument
		if ( arguments.length == 2 && arguments[1] == true && tmp.length == 0 )
		{
			//num.value = tmp;
			num.value = '';
			return true;
		}
		else
		{
			alert('Please enter your full 10 digit Phone/Fax number e.g. (416) 351-1361. ' );//+ tmp);
			//num.value = tmp;
			num.value = '';
			return false;
		}
	}
}

function testEmail( addressField )
{
	// grabbed these off of the internet, may need a bit more testing...
	//var r = /^[a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$/;
	var r = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
	var a = trim(addressField.value);

	if ( !r.test(a) )
	{
		alert( 'Please re-enter your email address.' );
		addressField.value = '';
		return false;
	}
	addressField.value = a;
	return true;
}

function testPostalCode( pc )
{
	// from the internet again....
	// Canadian postal codes alternate between letter and number such as L0S 1E0. 
	// Some choose not to put in the space. And not every letter is used as the first letter which designates region. 
	// The regions are (from east to west, then north): A,B,C,E,G,H,J,K,L,M,N,P,R,S,T,V,X,Y. 
	var r = /^[a-ceghj-npr-tvxy]\d[a-z](\s)?\d[a-z]\d$/i;
	var c = trim(pc.value);

	if ( !r.test(c) )
	{
		alert( 'Please re-enter your postal code.' );
		pc.value = '';
		return false;
	}
	pc.value = c.toUpperCase();
	return true;
}

function viewPDF() 
{
	  newwindow = window.open('', 'PDF', 'width=800;height=600;');
	  newwindow.location.href = 'PDF/' +  o('applicationtype').options[o('applicationtype').selectedIndex].title + '_Eligibility.pdf';
}

function toggleHelp( divId )
{
	var o = document.getElementById(divId);
	o.className = (o.className == 'open') ? 'closed' : 'open';

	var img = document.getElementById('milk2');
	img.src = (o.className == 'open') ? 'images/Hide-Button.gif' : 'images/Show-Button.gif';
}

function MakeHelpFrame()
{/*
		var body = document.getElementsByTagName('body')[0];
		var frame = document.createElement( 'IFRAME' );

		frame.setAttribute( 'name', 'helpFrame' );
		frame.setAttribute( 'id', 'helpFrame' );
		frame.setAttribute( 'src', 'popHelp.asp' );
		frame.className = 'helpIFrame';
		frame.frameBorder = 0;
		body.appendChild( frame );		
	*/
}

function setTipState()
{
	// access the hidden IFRAME
	var iframe = document.getElementById( 'helpFrame' );
	//var d = (document.all) ? iframe.document : iframe.contentDocument;
	var d = null;
	
	if ( document.all )
	{
		d = document.frames('helpFrame').document;
	}
	else
	{
		d = iframe.contentDocument;
	}
	
	// set the tipState field to 1
	var cb= (o('showTips').checked) ? 1 : 0;
	d.forms[0].elements[1].value = 1;
	d.forms[0].elements[0].value = cb;
	d.forms[0].submit();
	//alert( d.forms[0].elements[1].name + ' : ' + d.forms[0].elements[0].name );
}

