/*
 * Copyright (C) Jonathan Turkanis and Lincoln Law Center LLC 2006
 * File: coderage/controls/_pub/controls.js
 * Date: 2006-12-22
 */
 
 

//------------------Code for form dependencies--------------------------------//

function activate_triggers(elt, val, dep, name)
{
	if (name) {
		repeating_group.activate_triggers(elt, val, dep, name);
		return;
	}
	for (var z = 0, n = dep[0].length; z < n; ++z) {
		var d = parse_dependency(dep[0][z]);
		show_element(d[0], test_condition(val, d[1]));
	}
	for (var z = 0, n = dep[1].length; z < n; ++z) {
		var d = parse_dependency(dep[1][z]);
		show_element(d[0], !test_condition(val, d[1]));
	}
}

function test_condition(val, cond)
{
    return cond == null ?
        /^yes|true|1$/i.test(val) :
        cond.test ?
            cond.test(val) :
            val == cond;
}

function show_element(id, show)
{
    var elt = document.getElementById(id);
    elt.style.display = show ? '' : 'none';
    if (!show) {
        var tip = document.getElementById(id + '_tooltip');
        if (tip)
            tooltip.hide(tip);
    }
}

// returns a pair (id, condition)
function parse_dependency(dep)
{
	var q = dep.indexOf("?");
	if (q != -1) {
	    if (dep.substr(0, 2) == '=~') {
	        var sep = dep.lastIndexOf('/');
	        var pattern = 
	            new RegExp( dep.substring(3, sep), 
	                        dep.substring(sep + 1, q) );
		    return [dep.substr(q + 1), pattern];
	    } else {
		    eval("var cond = " + dep.substr(1, q - 1));
		    //alert("dep = " + dep.substr(q + 1) + "; cond = " + cond);
		    return [dep.substr(q + 1), cond];
	    }
	} else {
		//alert("dep = " + dep + "; cond = null");
		return new Array(dep, null);
	}
}

//------------------Open windows----------------------------------------------//

function open_window(url, name, props)
{
    if (!window.open_windows)
        window.open_windows = new Object;
    if ( name.charAt(0) == '_' ||
         window.open_windows[name] == undefined ||
         window.open_windows[name].closed )
    {
        window.open_windows[name] = window.open(url, name, props);
    } else {
        window.open_windows[name].document.location.href = url;
    }
}

//------------------Code for form submission ---------------------------------//

function submit_form(name)
{
	if (name)
		document.forms[0].button_name.value = name;
	submit_if_valid();
	return false;
}

//------------------Code for advancing from field to field-------------------//

function is_tab(e)
{
	var src = e.srcElement;
	var c = window.event ? e.keyCode : e.charCode;
	return c == 9;
}

//------------------Code for radio control-----------------------------------//

function radio_group(name) 
{
    radio_group.groups[name] = this;
    this.name = name;
    this.ids = new Array();
}

radio_group.add = function(name, id)
{
    if (!radio_group.groups)
        radio_group.groups = new Array();
    if (radio_group.groups[name] == undefined)
        radio_group.groups[name] = new radio_group;
    radio_group.groups[name].ids.push(id);
}

radio_group.update = function(name, id)
{
    var ids = radio_group.groups[name].ids;
    for (var z in ids) {
        if (ids[z] == id)
            continue;
        document.forms[0][ids[z]].value = 0;
        get_private_field('_' + ids[z]).checked = false;
    }
}

//------------------Code for date control -----------------------------------//

function format_date(fmt, year, mon, day) 
{ 
	fmt = fmt.replace(/Y/, year);
	fmt = fmt.replace(/y/, year.substr(2, 2));
	fmt = fmt.replace(/m/, mon);
	fmt = fmt.replace(/d/, day);
	return fmt;
}

//------------------Code for state control -----------------------------------//

function is_state(s) { return s != ''; }

//------------------Code for SSN and phone number ----------------------------//

function is_phone(s) { return /^\(\d{3}\)\d{3}-\d{4}(#\d{1,5})?$/.test(s); }
function is_two_digits(i) { return /^\d{2}$/.test(i); }
function is_three_digits(i) { return /^\d{3}$/.test(i); }
function is_four_digits(i) { return /^\d{4}$/.test(i); }
function is_seven_digits(i) { return /^\d{7}$/.test(i); }
function is_all_digits(i) { return /^\d+$/.test(i); }

//------------------Code for numeric text input-------------------------------//

function is_digit(e) 
{ 
	var src = e.srcElement;
	var c = window.event ? e.keyCode : e.charCode; 
	return c <= 20 || c >= 48 && c < 58;
}

function advance_cursor(elt, e)
{
	var last = e.keyCode - 48;
	var val = elt.value;
	var maxLength = elt.maxLength;
	if (val.length == maxLength && val.charAt(maxLength - 1) == last) {
		var inputs = document.getElementsByTagName('input');
		for (var z = 0, n = inputs.length - 1; z < n; ++z)
			if (inputs[z] == elt)
				inputs[z + 1].focus();
	}
}

function last_digit(e, val) 
{ 
	var c = window.event ? e.keyCode : e.charCode; 
	alert("c = " + c + "; val = " + val)
	return c - 48;
}

function ascii_value(val)
{
	return val + 48;
}
				
//------------------Code for money text input-------------------------------//

function is_money(e) 
{ 
	var src = e.srcElement;
	var c = window.event ? e.keyCode : e.charCode; 
	return c <= 20 || c >= 48 && c < 58 || c == 46;
}
	
//------------------Code for monetary text input------------------------------//
  
var isIE;
var isNS;

/*
Function to detect the Browser type.
*/
function detectBrowser()
{
			
	//browser detection
	var strUserAgent = navigator.userAgent.toLowerCase();
	isIE = strUserAgent.indexOf("msie") > -1;
	isNS = strUserAgent.indexOf("netscape") > -1;
	
}

/*
This function will fire when the control leaves the Text Box.
The function is responsible for formating the numbers to amount type.
*/
function FormatAmtControl(ctl){
//	alert ('inside FormatAmtControl: '+document.getElementById(ctl).value);
	var vMask ;
	var vDecimalAfterPeriod ;
	var ctlVal;
	var iPeriodPos;
	var sTemp;
	var iMaxLen 
	var ctlVal;
	var tempVal;
	ctlVal = document.getElementById(ctl).value;
	vDecimalAfterPeriod  = 2
	//iMaxLen  = ctl.maxLength;

	if (isNaN(ctlVal) || ctlVal == ' ' || ctlVal == '')
	{		
		if (ctlVal.length == 0) {
			document.getElementById(ctl).value="0.00"
			return;
		}
		
		for (var i = 0; i < ctlVal.length; ++i)
			if (isNaN(ctlVal.charAt(i)) && ctlVal.charAt(i) != '.') {
				document.getElementById(ctl).value="0.00"
				return;
			}			
		
	}
	
	
	//ctlVal =  ctl.value;
	iPeriodPos =ctlVal.indexOf(".");
	tempVal = ctlVal;
	if (iPeriodPos<0)
	{
		tempVal = tempVal + ".00"
	}
	else{
		if ((ctlVal.length - iPeriodPos -1)==1)
		tempVal = tempVal + "0"
		if ((ctlVal.length - iPeriodPos -1)==0)
		tempVal = tempVal + "00"
		if ((ctlVal.length - iPeriodPos -1)==2)
		tempVal = tempVal;
		if ((ctlVal.length - iPeriodPos -1)>2){
			tempVal = tempVal.substring(0,iPeriodPos+3);
		}
		if (iPeriodPos == 0) {
			tempVal = "0" + tempVal
		}


	}
	document.getElementById(ctl).value=tempVal;
}

/*
This function is responsible for filtering the keys pressed and the maintain the amount format of the 
value in the Text box
*/
function HandleAmountFiltering(ctl){
	var iKeyCode, objInput;
	var iMaxLen 
	var reValidChars = /[0-9.]/;
	var strKey;
	var sValue;
	var event = window.event || arguments.callee.caller.arguments[0];
	iMaxLen  = ctl.maxLength;
	sValue = ctl.value;
	detectBrowser();

	if (isIE) {
		iKeyCode = event.keyCode;
			objInput = event.srcElement;
	} else {
		iKeyCode = event.which;
		objInput = event.target;
	}

	strKey = String.fromCharCode(iKeyCode);

	if (reValidChars.test(strKey))
	{
		if(iKeyCode==46)
		{
			if(objInput.value.indexOf('.')!=-1)
				if (isIE)
					event.keyCode= 0;
				 else
				 {
				 	 if(event.which!=0 && event.which!=8)
					return false;
				 }
		}
		else
		{
			if(objInput.value.indexOf('.')==-1)
			{
				
				if (objInput.value.length>=(iMaxLen-3))
				{
					if (isIE)
						event.keyCode= 0;
					 else
					 {
					 	 if(event.which!=0 && event.which!=8)
						return false;
					 }
	
				}
			}
			if ((objInput.value.length==(iMaxLen-3)) && (objInput.value.indexOf('.')==-1))
			{
				objInput.value = objInput.value +'.';
			
			}

	
		}

	}
	else{
		if (isIE)
			event.keyCode= 0;
		 else
		 {
		 	 if(event.which!=0 && event.which!=8)
			 return false;
		 }
	}

}

// Validate birthday value

function validate_date(val) {
  return val.indexOf('null') == -1;
}

// Validate email address

function validate_email(val) {
	return (/^[a-zA-Z][\-a-zA-Z_0-9\.]*@[a-zA-Z0-9][\-a-zA-Z_0-9\.]+$/.test(val));
}

// Validate zip code
function validate_zip(val) {
	return (/^[0-9]{5}$/.test(val));
}
