//
// Checkbox control
//

function setCheckboxValue(formName, fieldName, fieldObject)
{
    $(fieldName).value = (fieldObject.checked ? "y" : "n"); 
    
    //next string does not work well
	//eval('document.' + formName + '.' + fieldName + '.value = "' + (fieldObject.checked ? "y" : "n") + '"');
}

function enableCheckboxRelatedFields(formName, fieldNames)
{		
	var fieldNamesArray = fieldNames.split("|");
	
	for(var i = 0; i < fieldNamesArray.length; i++)
	{
		if ( eval('document.' + formName + '.' + fieldNamesArray[i] + '.disabled') == true )
		{
			eval('document.' + formName + '.' + fieldNamesArray[i] + '.disabled = false');
		}
		else
		{
			eval('document.' + formName + '.' + fieldNamesArray[i] + '.disabled = true');
		}
	}
}

//  All functions within this file are generic and can be used on all web applications
//  All functions should in the future be split out and placed into a specific folder based on operation

// disable backspace
function customKeyMapping ()
{
	// disable backspace
	if (typeof window.event == 'undefined')
	{
		document.onkeypress = function(e)
		{
			var test_var = e.target.nodeName.toUpperCase();
			
			if (e.target.type)
			{
				var test_type = e.target.type.toUpperCase();
			}

			if ((test_var == 'INPUT' && test_type == 'TEXT') || test_var == 'TEXTAREA')
			{
				// must check to see if the field is readonly if so eat the keypress
				// otherwise the browser will still default to going back one page
				if ((e.target.readOnly == true) || (e.target.disabled == true))
				{
					e.preventDefault();
				}
				
				return e.keyCode;
			}
			else if (e.keyCode == 8)
			{
				e.preventDefault();
			}
		}
	}
	else
	{
		document.onkeydown = function()
		{
			var test_var = event.srcElement.tagName.toUpperCase();
			
			if (event.srcElement.type)
			{
				var test_type = event.srcElement.type.toUpperCase();
			}

			if ((test_var == 'INPUT' && test_type == 'TEXT') || test_var == 'TEXTAREA')
			{
				// must check to see if the field is readonly if so eat the keypress
				// otherwise the browser will still default to going back one page
				if ((event.srcElement.readOnly == true) || (event.srcElement.disabled == true))
				{
					event.returnValue=false;
				}
				
				return event.keyCode;
			}
			else if (event.keyCode == 8)
			{
				event.returnValue=false;
			}
		}
	}
	// disable backspace
}

// Select all records in a multi select box
// Requires the NAME of the field
function selectAllInMultiSelect(field)
{
	var field = document.getElementById(field);
	
	for (var ctr = 0; ctr < field.options.length; ++ctr)
	{
		field.options[ctr].selected = true;
	}
}

// Clear all selections in a multi select box
// Requires the NAME of the field
function clearAllInMultiSelect(field)
{
	var field = document.getElementById(field);
	
	for (var ctr = 0; ctr < field.options.length; ++ctr)
	{
		field.options[ctr].selected = false;
	}
}

// Generic divlayer javascript
function showDropDownDiv(obj, code, id)
{
	div = document.getElementById(id);
	
	if (code == obj.value)
	{
		div.style.display = 'inline';
	}
	else
	{
		div.style.display = 'none';
	}
}

function displayMoney(field)
{
	var tmp = field.value.replace(",", "");
	
	field.value = formatMoney(roundMoney(tmp));

}

function formatAsMoney(value)
{
	value = value.toString().replace(/\$|\,/g, '');

	if(isNaN(value))
	{
		value = "0";
	}

	sign = (value == (value = Math.abs(value)));
	value = Math.floor(value * 100 + 0.50000000001);
	cents = value % 100;
	value = Math.floor(value / 100).toString();

	if(cents < 10)
	{
		cents = "0" + cents;
	}
	for (var i = 0; i < Math.floor((value.length - (1 + i )) / 3); i++)
	{
		value = value.substring(0, value.length - (4 * i + 3)) + ',' + value.substring(value.length - (4 * i + 3));
	}
	
	return (((sign) ? '': '-') + value + '.' + cents);
}                                           

function textCounter(field, countfield, maxlimit)
{
	if (field.value.length > maxlimit)
	{
		field.value = field.value.substring(0, maxlimit);
	}
	else
	{
		countfield.value = maxlimit - field.value.length;
	}
}

function displayMessage(message)
{
	alert(message);
}

function confirmAction(question)
{
	var agree = confirm(question);

	if (agree)
	{
		return true ;
	}
	else
	{
		return false ;
	}
}

//
// Field access
//

function hasValue(id)
{
	return document.getElementById(id);
}

function getValue(id)
{
	return document.getElementById(id).value;
}

function hasInnerText(id)
{
	return document.getElementById(id);
}

function getInnerText(id)
{
	return document.getElementById(id).innerHTML;
}

function setValue(id, value)
{
	document.getElementById(id).value = value;
}

function setInnerText(id, value)
{
	document.getElementById(id).innerHTML = value;
}

//
// Money
//

function addMoney(total, plus)
{
	if (isNaN(total))
	{
		return total;
	}
	
	if (isNaN(plus))
	{
		return total;
	}

	return roundMoney(total + plus);
}

function roundMoney(money)
{
	var p = parseFloat(money);
	
	if (isNaN(p))
	{
		return money;
	}

	return Math.round(p*100)/100;
}

function formatMoney(money)
{
	if (isNaN(money))
	{
		return money;
	}
	
	if (money.length == 0)
	{
		return money;
	}
	
	money = "" + money;
	
	if (money.indexOf('.') < 0)
	{
		return money + ".00";
	}

	if (money.indexOf('.') == money.length - 2)
	{
		return money + "0";
	}

	return money;
}

function setMoneyValue(id, value)
{
	setValue(id, formatMoney(value));
}

function setMoneyInnerText(id, value)
{
	setInnerText(id, formatMoney(value));
}

//
// Dates
//

function getDateField( field, format )
{
	var date = getDateFromFormat( field.value, 'M/d/yy' );
	
	if ( ! date )
	{
		date = getDateFromFormat( field.value, 'M/d/yyyy' );
	}
	
	if ( ! date )
	{
		date = getDateFromFormat( field.value + '/' + new Date().getFullYear(), 'M/d/yyyy' );
	}

	if ( date )
	{
		date = new Date( date );
		field.value = formatDate( date, format );
	}
	else
	{
		date = new Date( field.value );
	}

	return date;
}

//
// Validator
//

var hasOnSubmit = false;

function Validator(frmname)
{
	this.formobj=document.forms[frmname];
	
	if(!this.formobj)
	{
		alert("BUG: couldnot get Form object "+frmname);
		return;
	}

	if(this.formobj.onsubmit)
	{
		this.formobj.old_onsubmit = this.formobj.onsubmit;
		this.formobj.onsubmit = null;
		hasOnSubmit = true;
	}
	else
	{
		this.formobj.old_onsubmit = null;
	}

	this.formobj.onsubmit=form_submit_handler;
	this.addValidation = add_validation;
	this.setAddnlValidationFunction=set_addnl_vfunction;
	this.clearAllValidations = clear_all_validations;
}

function set_addnl_vfunction(functionname)
{
	this.formobj.addnlvalidation = functionname;
}

function clear_all_validations()
{
	for(var itr=0;itr < this.formobj.elements.length;itr++)
	{
		this.formobj.elements[itr].validationset = null;
	}
}

function form_submit_handler()
{
    //alert("form_submit_handler");
    //alert(hasOnSubmit);
	for(var itr=0; itr < this.elements.length; itr++)
	{
		if(this.elements[itr].validationset && !this.elements[itr].validationset.validate())
		{
			return false;
		}
	}

	if(this.addnlvalidation)
	{
		str =" var ret = "+this.addnlvalidation+"()";
		eval(str);
		
		if(!ret)
		{
			return ret;
		}
	}

    if (hasOnSubmit)
	{
        return onSubmit();
    }
    else
	{
       	return true;
    }
}

function add_validation(itemname, descriptor, errstr)
{
	if(!this.formobj)
	{
		alert("BUG: the form object is not set properly");
		return;
	}
	
	var itemobj = this.formobj[itemname];
	
	if(!itemobj)
	{
		alert("BUG: Couldnot get the input object named: "+itemname);
		return;
	}

	if(!itemobj.validationset)
	{
		itemobj.validationset = new ValidationSet(itemobj);
	}

	itemobj.validationset.add(descriptor, errstr);
}

function ValidationDesc(inputitem, desc, error)
{
	this.desc=desc;
	this.error=error;
	this.itemobj = inputitem;
	this.validate=vdesc_validate;
}

function vdesc_validate()
{
	if(!V2validateData(this.desc, this.itemobj, this.error))
	{
		this.itemobj.focus();
		return false;
	}
 
	return true;
}

function ValidationSet(inputitem)
{
    this.vSet = new Array();
	this.add = add_validationdesc;
	this.validate = vset_validate;
	this.itemobj = inputitem;
}

function add_validationdesc(desc, error)
{
	this.vSet[this.vSet.length] = new ValidationDesc(this.itemobj, desc, error);
}

function vset_validate()
{
	for(var itr=0; itr<this.vSet.length; itr++)
	{
		if(!this.vSet[itr].validate())
		{
			return false;
		}
	}
	
	return true;
}

function validateEmailv2(email)
{
	// a very simple email validation checking.
	// you can add more complex email checking if it helps
    if(email.length <= 0)
	{
		return true;
	}
    
	var splitted = email.match("^(.+)@(.+)$");
    
	if(splitted == null)
	{
		return false;
	}
    
	if(splitted[1] != null )
    {
		var regexp_user=/^\"?[\w-_\.]*\"?$/;
		
		if(splitted[1].match(regexp_user) == null)
		{
			return false;
		}
    }

    if(splitted[2] != null)
    {
		var regexp_domain=/^[\w-\.]*\.[A-Za-z]{2,4}$/;
		
		if(splitted[2].match(regexp_domain) == null)
		{
			var regexp_ip =/^\[\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\]$/;
			
			if(splitted[2].match(regexp_ip) == null)
			{
				return false;
			}
		}
		
		return true;
    }

	return false;
}

function V2validateData(strValidateStr, objValue, strError)
{
    var epos = strValidateStr.search("=");
    var command  = "";
    var cmdvalue = "";
    
	if(epos >= 0)
    {
		command  = strValidateStr.substring(0, epos);
		cmdvalue = strValidateStr.substr(epos+1);
    }
    else
    {
		command = strValidateStr;
    }
    
	switch(command)
    {
		case "req":
        case "required":
        {
			if(eval(objValue.value.length) == 0)
			{
				if(!strError || strError.length ==0)
				{
					strError = objValue.name + " : Required Field";
				}
              
				alert(strError);
				
				return false;
			}
           
			break;
        }
        case "maxlength":
        case "maxlen":
		{
			if(eval(objValue.value.length) >  eval(cmdvalue))
            {
				if(!strError || strError.length ==0)
				{
					strError = objValue.name + " : "+cmdvalue+" characters maximum ";
				}
               
				alert(strError + "\n[Current length = " + objValue.value.length + " ]");
				
				return false;
			}
            
			break;
		}
        case "minlength":
        case "minlen":
        {
			if(eval(objValue.value.length) <  eval(cmdvalue))
            {
				if(!strError || strError.length ==0)
				{
					strError = objValue.name + " : " + cmdvalue + " characters minimum  ";
				}
				
				alert(strError + "\n[Current length = " + objValue.value.length + " ]");
				
				return false;
             }
             
			 break;
		}
        case "alnum":
        case "alphanumeric":
		{
			var charpos = objValue.value.search("[^A-Za-z0-9]");
			
			if(objValue.value.length > 0 &&  charpos >= 0)
			{
				if(!strError || strError.length ==0)
				{
					strError = objValue.name+": Only alpha-numeric characters allowed ";
                }
                
				alert(strError + "\n [Error character position " + eval(charpos+1)+"]");
                
				return false;
			}
            
			break;
		}
        case "num":
        case "numeric":
        {
			var charpos = objValue.value.search("[^0-9]");
            
			if(objValue.value.length > 0 &&  charpos >= 0)
            {
				if(!strError || strError.length ==0)
                {
					strError = objValue.name+": Only digits allowed ";
                }
                
				alert(strError + "\n [Error character position " + eval(charpos+1)+"]");
                
				return false;
			}
            
			break;
		}
        case "alphabetic":
        case "alpha":
        {
			var charpos = objValue.value.search("[^A-Za-z]");
            
			if(objValue.value.length > 0 &&  charpos >= 0)
            {
				if(!strError || strError.length ==0)
                {
					strError = objValue.name+": Only alphabetic characters allowed ";
                }
                
				alert(strError + "\n [Error character position " + eval(charpos+1)+"]");
                
				return false;
			}

			break;
        }
		case "alnumhyphen":
		{
			var charpos = objValue.value.search("[^A-Za-z0-9\-_.]");
            
			if(objValue.value.length > 0 &&  charpos >= 0)
            {
				if(!strError || strError.length ==0)
                {
					strError = objValue.name+": characters allowed are A-Z,a-z,0-9,- and _";
                }
                
				alert(strError + "\n [Error character position " + eval(charpos+1)+"]");
                
				return false;
			}
			
			break;
		}
        case "email":
        {
			if(!validateEmailv2(objValue.value))
            {
				if(!strError || strError.length ==0)
                {
					strError = objValue.name+": Enter a valid Email address ";
                }

                alert(strError);
                
				return false;
			}

			break;
		}
        case "lt":
        case "lessthan":
		{
			if(isNaN(objValue.value))
            {
				alert(objValue.name+": Should be a number ");
				
				return false;
            }

            if(eval(objValue.value) >=  eval(cmdvalue))
            {
				if(!strError || strError.length ==0)
				{
					strError = objValue.name + " : value should be less than "+ cmdvalue;
				}
				
				alert(strError);
				
				return false;
			}
            
			break;
		}
        case "gt":
        case "greaterthan":
        {
			if(isNaN(objValue.value))
            {
				alert(objValue.name+": Should be a number ");
				
				return false;
            }
             
			if(eval(objValue.value) <=  eval(cmdvalue))
            {
				if(!strError || strError.length ==0)
				{
					strError = objValue.name + " : value should be greater than "+ cmdvalue;
				}
               
				alert(strError);
				
				return false;
			}
            
			break;
        }
        case "regexp":
        {
			if(objValue.value.length > 0)
			{
				if(!objValue.value.match(cmdvalue))
	            {
					if(!strError || strError.length ==0)
					{
						strError = objValue.name+": Invalid characters found ";
					}
	              
					alert(strError);
					
					return false;
				}
			}
			
			break;
        }
        case "dontselect":
        {
			if(objValue.selectedIndex == null)
            {
				alert("BUG: dontselect command for non-select Item");
				
				return false;
            }
            
			if(objValue.selectedIndex == eval(cmdvalue))
            {
				if(!strError || strError.length ==0)
				{
					strError = objValue.name+": Please Select one option ";
				}
              
				alert(strError);
				
				return false;
             }
             
			 break;
		}
		case "selectBoxEmpty":
        {
			if(objValue.selectedIndex == null)
            {
				alert("BUG: dontselect command for non-select Item");
				
				return false;
            }
            
			if(objValue.length == 0)
            {
				if(!strError || strError.length ==0)
				{
					strError = objValue.name+": Please Select one option ";
				}
				
				alert(strError);

				return false;
            }
             
			break;
		}
    }
    
	return true;
}

function openPopupWindow( url, width, height )
{
	openPopupFocus( url, '_blank', width, height, 'width=' + width + ',height=' + height + ',resizable=yes,toolbar=no,status=no,scrollbars=yes,menubar=no,directories=no,location=no,dependant=yes', true, true );
}

function openPopupWindowAdv( url, width, height, x, y )
{
	window.open(url,'popup','left='+x+',top='+y+',width='+width+',height='+height+',resizable=yes,toolbar=no,status=no,scrollbars=yes,menubar=no,directories=no,location=no,dependant=yes');
}

function openPopupWindowCursor( event, url, width, height)
{
	// BUG:: IE HATES EVENTS FIX THIS
	try
	{
		x = event.clientX;
		y = event.clientY;
		
		openPopupWindowAdv( url, width, height, x, y);
	}
	catch (e)
	{
	
	}
}

function createWindow(winURL, winName, winFeatures, w, h)
{
	winFeatures += ',width=' + w;
	winFeatures += ',height=' + h;
	
	if ( window.screenX )
	{
		winFeatures += ',screenX=' + (window.screenX + (window.outerWidth - w) / 2);
	}
	else
	{
		winFeatures += ',left=' + (window.screenLeft + (document.documentElement.offsetWidth - w) / 2);
	}

	if ( window.screenY )
	{
		winFeatures += ',screenY=' + (window.screenY + (window.outerHeight - h) / 2);
	}
	else
	{
		winFeatures += ',top=' + (window.screenTop + (document.documentElement.offsetHeight - h) / 2);
	}
	
	var win = window.open(winURL, winName, winFeatures);
}

function formatPhone(fieldObject)
{
	fieldObject.value = trim(fieldObject.value);
	
	var ov = fieldObject.value;
	var v = "";
	var x = -1;

	// is this phone number 'escaped' by a leading plus?
	if (0 < ov.length && '+' != ov.charAt(0))
	{
		// count number of digits
		var n = 0;
		
		if ('1' == ov.charAt(0))
		{
			ov = ov.substring(1, ov.length);
		}

		for (i = 0; i < ov.length; i++)
		{
			var ch = ov.charAt(i);

			// build up formatted number
			if (ch >= '0' && ch <= '9')
			{
				if (n == 0)
				{
					v += "(";
				}
				else if (n == 3)
				{
					v += ") ";
				}
				else if (n == 6)
				{	
					v += "-";
				}
				
				v += ch;
				n++;
			}
			
			// check for extension type section;
			// are spaces, dots, dashes and parentheses the only valid non-digits in a phone number?
			if (! (ch >= '0' && ch <= '9') && ch != ' ' && ch != '-' && ch != '.' && ch != '(' && ch != ')')
			{
				x = i;
				break;
			}
		}
		
		// add the extension
		if (x >= 0)
		{
			v += " " + ov.substring(x, ov.length);
		}

		// if we recognize the number, then format it
		if (n == 10 && v.length <= 40)
		{
			fieldObject.value = v;
		}
	}
	
	return true;
}

// removes the leading and trailing spaces from a string,
// similar to the java.lang.String.trim() function
// added by lturetsky, taken from http://www.voy.com/1888/58.html
function trim(st) 
{
	var len = st.length
	var begin = 0, end = len - 1;

	while (st.charAt(begin) == " " && begin < len) 
	{
		begin++;
	}
	
	while (st.charAt(end) == " " && begin < end) 
	{
		end--;
	}

	return st.substring(begin, end+1);
}

//
// Checkbox control
//

function _cb_onCheckboxClick(chk, field, prefix)
{
	var isChecked = 'n';

	if (chk.checked)
	{
		isChecked = 'y';
	}
	if (!prefix)
	{
		prefix = 'db_';
	}
	$(prefix + field).value = isChecked;
}

var curPopupWindow = null;
var lastMouseX;
var lastMouseY;



/**
* Handles popup windows.
* If snapToLastMousePosition is true, then the popup will open up near the mouse click.
* If closeOnLoseFocus is true, then it will close when the user clicks back into the browser window that opened it.
*/
function openPopupFocus(url, name, pWidth, pHeight, features, snapToLastMousePosition, closeOnLoseFocus, closeOnParentUnload) {
	closePopup();

	if (snapToLastMousePosition) {
		if (lastMouseX - pWidth < 0) {
			lastMouseX = pWidth;
		}
		if (lastMouseY + pHeight > screen.height) {
			lastMouseY -= (lastMouseY + pHeight + 50) - screen.height;
		}
		lastMouseX -= pWidth;
		lastMouseY += 10;
		features += ",screenX=" + lastMouseX + ",left=" + lastMouseX + ",screenY=" + lastMouseY + ",top=" + lastMouseY;
	}

	if (closeOnLoseFocus) {
		curPopupWindow = window.open(url, name, features, false);
		curPopupWindow.focus();
	} else {
		// assign the open window to a dummy var so when closePopup() is called it won't be assigned to curPopupWindow
		win = window.open(url, name, features, false);
		win.focus();
	}

	if (closeOnParentUnload) {
		closeOnParentUnloadWindow = win;
	}
}

function closePopup() {
	if (curPopupWindow != null) {

		if (!curPopupWindow.closed) {
			curPopupWindow.close();
		}
		curPopupWindow = null;
	}
}


// Set the Due Date to Today
function setDueDateToday(field)
{
	var d = new Date();
	var month = d.getMonth() + 1;
	document.getElementById(field).value = month + "/" + d.getDate() + "/" + d.getFullYear();
}

// Set the Due Date to Tomorrow
function setDueDateTomorrow(field, increment)
{
	if (!increment)
	{
		var increment = 1;
	}
	var d = new Date();
	d.setDate(d.getDate() + increment);
	var month = d.getMonth() + 1;
	var day = d.getDate();
	var year = d.getFullYear();
	document.getElementById(field).value = month + "/" + day + "/" + year;
}

// Function to check if value is numeric
function IsNumeric(sText)
{
	var ValidChars = "0123456789.";
	var IsNumber=true;
	var Char;
	
	for (i = 0; i < sText.length && IsNumber == true; i++) 
	{ 
		Char = sText.charAt(i); 
		if (ValidChars.indexOf(Char) == -1) 
		{
			IsNumber = false;
		}
	}
	return IsNumber;
}

// Reformat numeric entry in 'field' to no commas with 'decimals' places.
function formatNumber(field, decimals)
{
	var value = eval(field.value.replace(",",""));
	field.value = value.toFixed(decimals);
}

// Clear a given form field
function clearField(field)
{
	document.getElementById(field).value = '';
}

// Capitalize the first character of a string
String.prototype.ucfirst = function()
{
   // Split the string into words if string contains multiple words.
   var x = this.split(/\s+/g);
   for(var i = 0; i < x.length; i++)
   {
      // Splits the word into two parts. One part being the first letter,
      // second being the rest of the word.
      var parts = x[i].match(/(\w)(\w*)/);
 
      // Put it back together but uppercase the first letter and lowercase the rest of thw word.
      x[i] = parts[1].toUpperCase() + parts[2].toLowerCase();
   }
 
   // Rejoin the string and return.
   return x.join(' ');
};

// Get the size of the window
// Old browsers return 640 x 480
function getWindowSize()
{
	var width = 640;
	var height = 480;
	
	if (parseInt(navigator.appVersion)>3)
	{
		if (navigator.appName=="Netscape") 
		{
			width = window.innerWidth;
			height = window.innerHeight;
		}
	}
	
	if (navigator.appName.indexOf("Microsoft")!=-1)
	{
		width = document.body.offsetWidth;
		height = document.body.offsetHeight;
	}
	
	return [width,height];	
}

// Toggle label/redbox class to change colors from grey to red
function toggleClassRedbox(elementID)
{
	// If it already has the redbox class
	if ( $(elementID).hasClassName('redbox') )
	{
		// Remove the redbox class
		$(elementID).removeClassName('redbox');
		
		// Add the label class
		$(elementID).addClassName('label');
	}
	else
	{
		// Remove the label class
		$(elementID).removeClassName('label');
		
		// Add the redbox class
		$(elementID).addClassName('redbox');
	}
}
