
function validate( butn, fields, captions, blank_select_text )
{
        var form = butn.form;

	// This is an optional fourth argument: isOnSubmit True or False (default)
	var isOnSubmit = (arguments[4]) ? arguments[4] : false;

        // Check required fields
        for (var i = 0; i < fields.length; i++)
        {
			var field = form.elements[fields[i]];
			
			if (field == undefined)
				alert("Missing field: " + fields[i]);
			
			var is_present = 0;
			if (!field.nodeName && field.length)	// Maybe radio button?
			{
				for (var j = 0; j < field.length; ++j)
				{	if (field[j].checked)
					{	is_present = 1;
						break;
					}
				}
			}
			else if (field.nodeName.toLowerCase() == "select")
			{
				if (field[field.selectedIndex].text != blank_select_text )
					is_present = 1;
			}
			else if ((field.nodeName.toLowerCase() == "input") || (field.nodeName.toLowerCase() == "textarea" ))
			{
				if (!/^\s*$/.test(field.value))
					is_present = 1;
			}

			if (!is_present)
			{
				alert(captions[i]);
				if (field.select)
						field.select();
				if (field.focus)
						field.focus();
				return false;
			}
        }

	// Validate All email addresses
	if (!ValidateEmails (form))
		return false;

	// validate all phones
	if (!ValidatePhones (form))
		return false;

	if (!confirm_email( butn, 'Email', 'EmailVerify' ) )
		return false;


    if ( !isOnSubmit && form.onsubmit )
	{	// Call onsubmit if this function wasn't called from onsubmit
		if ( !form.onsubmit() )
			return false;
	}

	if( butn )
		butn.disabled = true;

	if (!isOnSubmit)	// Submit form if is function wasn't called from on submit
		form.submit();
	else
		return true;
}

function confirm_email( butn, main_field_name, confirm_field_name )
{
	var form = butn.form;

	var main_field = form.elements[main_field_name];
	var confirm_field = form.elements[confirm_field_name];

	if (( main_field == undefined ) || ( confirm_field == undefined ))
		return true;

	if ( main_field.value != confirm_field.value )
	{
		alert( "E-mail fields do not match" );
		return false;
	}

	return true;

}

function ValidateEmails (form)
{
	for (var i = 0; i < form.elements.length; ++i)
	{

		var field = form.elements[i];

		if ((field.name != undefined ) &&  (field.name.toLowerCase ().indexOf ("email") > -1) && (field.name.toLowerCase ().indexOf ("noemail") == -1) && (field.value.length > 0) )
		{
			if (!/[\w\_\-\.]+\@[\w\_\-]+\.\w{2,4}(\.\w{2,4})?/.test (field.value))
			{
				alert (field.value + " is not a valid email address");
					return false;
			}
		}
	}
	return true;
}

function ValidatePhones (form)
{
	for (var i = 0; i < form.elements.length; ++i)
	{
		var field = form.elements[i];

		var field_name;

		if (field.id.length)
		{
			field_name = field.id;
		}
		else if ( field.name != undefined )
		{
			field_name = field.name;
		}
		else
		{
			field_name = "";
		}

			
		if ((field_name != "") && (field_name.toLowerCase().indexOf ("areacode") > -1) )
		{
			var base_field = field_name.toLowerCase().substring (0, field_name.indexOf ("areacode"));

			if (!UpdatePhone (base_field))			
			{
				return false;
			}
		}
	}
	return true;
}


/**
 * Next two functions from:
 * Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
 */
function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}

function DaysArray (n){
	for (var i = 1; i <= n; i++)	{
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   }
   return this
}

function UpdateDate( base_field_name )
{
	var month_elem = document.getElementById( base_field_name + "_Month" );
	var day_elem = document.getElementById( base_field_name + "_Day" );
	var year_elem = document.getElementById( base_field_name + "_Year" );
	var hidden_elem = document.getElementById( base_field_name );

	var month = DropDownSelectedValue( month_elem );
	var day = DropDownSelectedValue( day_elem );
	var year = DropDownSelectedValue( year_elem );

	// This is so the hidden field will be empty if date is not complete
	var full_date = month + '/' + day + '/' + year;
	if (/\d+\/\d+\/\d+/.test (full_date))
	{	// Check data is valid
		var daysInMonth = DaysArray (12);
		if ((month == 2 && day > daysInFebruary (year)) || day > daysInMonth[month])
		{
			alert ("This is not a valid date!");
			month_elem.selectedIndex = 0;
			day_elem.selectedIndex = 0;
			year_elem.selectedIndex = 0;
			hidden_elem.value = "";
		}
		else
		{	// The date is valid
			hidden_elem.value = full_date;
		}
	}
	else
	{	// Date is incomplete
		hidden_elem.value = "";
	}
	
	return hidden_elem.value
}

function UpdateSolDate( base_field_name )
{
	var sol = UpdateDate (base_field_name)
	if (sol != "")
	{	// Check the date is in the future
		var myDate = Date.parse (sol);
		if (myDate <= new Date ())
		{
			alert ("SOL date must be in the future!");
			var month_elem = document.getElementById( base_field_name + "_Month" );
			var day_elem = document.getElementById( base_field_name + "_Day" );
			var year_elem = document.getElementById( base_field_name + "_Year" );
			var hidden_elem = document.getElementById( base_field_name );
			month_elem.selectedIndex = 0;
			day_elem.selectedIndex = 0;
			year_elem.selectedIndex = 0;
			hidden_elem.value = "";
		}
	}
}


function UpdateDateRange( base_field_name )
{
	var date1 = UpdateDate (base_field_name + "_From");
	var date2 = UpdateDate (base_field_name + "_To");
	var hidden_elem = document.getElementById( base_field_name );
	if (date1 != "" && date2 != "")
	{
		var DateA = Date.parse (date1);
		var DateB = Date.parse (date2);
		if (DateB >= DateA)
		{	hidden_elem.value = date1 + " - " + date2 }
		else
		{ 	// Reset every thing
			alert ("From date must be before To date!");
			var month_elem = document.getElementById( base_field_name + "_From_Month" );
			var day_elem = document.getElementById( base_field_name + "_From_Day" );
			var year_elem = document.getElementById( base_field_name + "_From_Year" );
			month_elem.selectedIndex = 0;
			day_elem.selectedIndex = 0;
			year_elem.selectedIndex = 0;
			month_elem = document.getElementById( base_field_name + "_To_Month" );
			day_elem = document.getElementById( base_field_name + "_To_Day" );
			year_elem = document.getElementById( base_field_name + "_To_Year" );
			month_elem.selectedIndex = 0;
			day_elem.selectedIndex = 0;
			year_elem.selectedIndex = 0;
			hidden_elem.value = "";
		}

	}
}

function getElementByIdOrName(str) {

	for ( var i = 0; i < document.forms.length; ++i )
	{
		var form = document.forms[i]; 
		for (var j = 0; j < form.elements.length; ++j)
		{
			var field = form.elements[j];

			if ( (field.id) && (field.id.length) && (field.id.toLowerCase() == str.toLowerCase()))
			{
				return field;
			}
			else if  ( (field.name) && (field.name.length) && (field.name.toLowerCase() == str.toLowerCase()))
			{
				return field;
			}
		}
	}
	return null;

}


function UpdatePhone (base_field_name)
{
	var areacode = getElementByIdOrName (base_field_name + "areacode").value;
	var exchange = getElementByIdOrName (base_field_name + "exchange").value;
	var suffix = getElementByIdOrName (base_field_name + "suffix").value;
	var ext_elem = getElementByIdOrName (base_field_name + "extension");
	var extension;
	if ( ext_elem )
	{
		extension = ext_elem.value;
	}
	else
	{
		extension = "";
	}
	var hidden_elem = getElementByIdOrName (base_field_name);

	var full_phone = "(" + areacode + ") " + exchange + "-" + suffix;
	if (extension.length > 0)
		full_phone = full_phone + " ext. " + extension;

	if (/\(\d{3}\) \d{3}-\d{4}( ext. \d+)?$/.test (full_phone))
	{
		if (hidden_elem) hidden_elem.value = full_phone;
	}
	else
	{
		if (hidden_elem) hidden_elem.value = "";
		if (areacode.length > 0 && exchange.length > 0 && suffix.length > 0)
			alert ("Please enter your Phone Number in the correct (###) ###-#### format.");
		if (areacode.length > 0 || exchange.length > 0 || suffix.length > 0 ||
			extension.length > 0)
			return false;
	}
	return true;
}

function DropDownSelectedValue( element )
{
	return element.options[element.selectedIndex].value;
}


// List functions from http://www.mattkruse.com/javascript/selectbox/
// -------------------------------------------------------------------
// hasOptions(obj)
//  Utility function to determine if a select object has an options array
// -------------------------------------------------------------------
function hasOptions(obj) {
	if (obj!=null && obj.options!=null) { return true; }
	return false;
	}

// -------------------------------------------------------------------
// selectUnselectMatchingOptions(select_object,regex,select/unselect,true/false)
//  This is a general function used by the select functions below, to
//  avoid code duplication
// -------------------------------------------------------------------
function selectUnselectMatchingOptions(obj,regex,which,only) {
	if (window.RegExp) {
		if (which == "select") {
			var selected1=true;
			var selected2=false;
			}
		else if (which == "unselect") {
			var selected1=false;
			var selected2=true;
			}
		else {
			return;
			}
		var re = new RegExp(regex);
		if (!hasOptions(obj)) { return; }
		for (var i=0; i<obj.options.length; i++) {
			if (re.test(obj.options[i].text)) {
				obj.options[i].selected = selected1;
				}
			else {
				if (only == true) {
					obj.options[i].selected = selected2;
					}
				}
			}
		}
	}

// -------------------------------------------------------------------
// selectMatchingOptions(select_object,regex)
//  This function selects all options that match the regular expression
//  passed in. Currently-selected options will not be changed.
// -------------------------------------------------------------------
function selectMatchingOptions(obj,regex) {
	selectUnselectMatchingOptions(obj,regex,"select",false);
	}
// -------------------------------------------------------------------
// selectOnlyMatchingOptions(select_object,regex)
//  This function selects all options that match the regular expression
//  passed in. Selected options that don't match will be un-selected.
// -------------------------------------------------------------------
function selectOnlyMatchingOptions(obj,regex) {
	selectUnselectMatchingOptions(obj,regex,"select",true);
	}
// -------------------------------------------------------------------
// unSelectMatchingOptions(select_object,regex)
//  This function Unselects all options that match the regular expression
//  passed in.
// -------------------------------------------------------------------
function unSelectMatchingOptions(obj,regex) {
	selectUnselectMatchingOptions(obj,regex,"unselect",false);
	}

// -------------------------------------------------------------------
// sortSelect(select_object)
//   Pass this function a SELECT object and the options will be sorted
//   by their text (display) values
// -------------------------------------------------------------------
function sortSelect(obj) {
	var o = new Array();
	if (!hasOptions(obj)) { return; }
	for (var i=0; i<obj.options.length; i++) {
		o[o.length] = new Option( obj.options[i].text, obj.options[i].value, obj.options[i].defaultSelected, obj.options[i].selected) ;
		}
	if (o.length==0) { return; }
	o = o.sort(
		function(a,b) {
			if ((a.text.toLowerCase()) < (b.text.toLowerCase())) { return -1; }
			if ((a.text.toLowerCase()) > (b.text.toLowerCase())) { return 1; }
			return 0;
			}
		);

	for (var i=0; i<o.length; i++) {
		obj.options[i] = new Option(o[i].text, o[i].value, o[i].defaultSelected, o[i].selected);
		}
	}


// -------------------------------------------------------------------
// AddSelectionToOnSubmit(selection_control_name)
// -------------------------------------------------------------------
var control_names = new Array();

function AddSelectionToOnSubmit(control_name) {
	control_names[control_names.length] = control_name;
	return;
}

function MyOnSubmit ()
{
	for (i=0; i < control_names.length; i++)
	{	selectAllOptions(document.forms[0][control_names[i]]); }
	return true;
}

if (document.forms[0])
{	document.forms[0].onsubmit = MyOnSubmit; }

// -------------------------------------------------------------------
// selectAllOptions(select_object)
//  This function takes a select box and selects all options (in a
//  multiple select object). This is used when passing values between
//  two select boxes. Select all options in the right box before
//  submitting the form so the values will be sent to the server.
// -------------------------------------------------------------------
function selectAllOptions(obj) {
	if (!hasOptions(obj)) { return; }
	for (var i=0; i<obj.options.length; i++) {
		obj.options[i].selected = true;
	}
}


// -------------------------------------------------------------------
// moveSelectedOptions(select_object,select_object[,autosort(true/false)[,regex]])
//  This function moves options between select boxes. Works best with
//  multi-select boxes to create the common Windows control effect.
//  Passes all selected values from the first object to the second
//  object and re-sorts each box.
//  If a third argument of 'false' is passed, then the lists are not
//  sorted after the move.
//  If a fourth string argument is passed, this will function as a
//  Regular Expression to match against the TEXT or the options. If
//  the text of an option matches the pattern, it will NOT be moved.
//  It will be treated as an unmoveable option.
//  You can also put this into the <SELECT> object as follows:
//    onDblClick="moveSelectedOptions(this,this.form.target)
//  This way, when the user double-clicks on a value in one box, it
//  will be transferred to the other (in browsers that support the
//  onDblClick() event handler).
// -------------------------------------------------------------------
function moveSelectedOptions(from,to) {
	// Unselect matching options, if required
	if (arguments.length>3) {
		var regex = arguments[3];
		if (regex != "") {
			unSelectMatchingOptions(from,regex);
			}
		}
	// Move them over
	if (!hasOptions(from)) { return; }
	for (var i=0; i<from.options.length; i++) {
		var o = from.options[i];
		if (o.selected) {
			if (!hasOptions(to)) { var index = 0; } else { var index=to.options.length; }
			to.options[index] = new Option( o.text, o.value, false, false);
			}
		}
	// Delete them from original
	for (var i=(from.options.length-1); i>=0; i--) {
		var o = from.options[i];
		if (o.selected) {
			from.options[i] = null;
			}
		}
	if ((arguments.length<3) || (arguments[2]==true)) {
		sortSelect(from);
		sortSelect(to);
		}
	from.selectedIndex = -1;
	to.selectedIndex = -1;
	}

// -------------------------------------------------------------------
// copySelectedOptions(select_object,select_object[,autosort(true/false)])
//  This function copies options between select boxes instead of
//  moving items. Duplicates in the target list are not allowed.
// -------------------------------------------------------------------
function copySelectedOptions(from,to) {
	var options = new Object();
	if (hasOptions(to)) {
		for (var i=0; i<to.options.length; i++) {
			options[to.options[i].value] = to.options[i].text;
			}
		}
	if (!hasOptions(from)) { return; }
	for (var i=0; i<from.options.length; i++) {
		var o = from.options[i];
		if (o.selected) {
			if (options[o.value] == null || options[o.value] == "undefined" || options[o.value]!=o.id) {
				if (!hasOptions(to)) { var index = 0; } else { var index=to.options.length; }
				to.options[index] = new Option( o.id, o.value, false, false);
				}
			}
		}
	if ((arguments.length<3) || (arguments[2]==true)) {
		sortSelect(to);
		}
	from.selectedIndex = -1;
	to.selectedIndex = -1;
	}

// -------------------------------------------------------------------
// moveAllOptions(select_object,select_object[,autosort(true/false)[,regex]])
//  Move all options from one select box to another.
// -------------------------------------------------------------------
function moveAllOptions(from,to) {
	selectAllOptions(from);
	if (arguments.length==2) {
		moveSelectedOptions(from,to);
		}
	else if (arguments.length==3) {
		moveSelectedOptions(from,to,arguments[2]);
		}
	else if (arguments.length==4) {
		moveSelectedOptions(from,to,arguments[2],arguments[3]);
		}
	}

// -------------------------------------------------------------------
// copyAllOptions(select_object,select_object[,autosort(true/false)])
//  Copy all options from one select box to another, instead of
//  removing items. Duplicates in the target list are not allowed.
// -------------------------------------------------------------------
function copyAllOptions(from,to) {
	selectAllOptions(from);
	if (arguments.length==2) {
		copySelectedOptions(from,to);
		}
	else if (arguments.length==3) {
		copySelectedOptions(from,to,arguments[2]);
		}
	}

// -------------------------------------------------------------------
// swapOptions(select_object,option1,option2)
//  Swap positions of two options in a select list
// -------------------------------------------------------------------
function swapOptions(obj,i,j) {
	var o = obj.options;
	var i_selected = o[i].selected;
	var j_selected = o[j].selected;
	var temp = new Option(o[i].text, o[i].value, o[i].defaultSelected, o[i].selected);
	var temp2= new Option(o[j].text, o[j].value, o[j].defaultSelected, o[j].selected);
	o[i] = temp2;
	o[j] = temp;
	o[i].selected = j_selected;
	o[j].selected = i_selected;
	}

// -------------------------------------------------------------------
// moveOptionUp(select_object)
//  Move selected option in a select list up one
// -------------------------------------------------------------------
function moveOptionUp(obj) {
	if (!hasOptions(obj)) { return; }
	for (i=0; i<obj.options.length; i++) {
		if (obj.options[i].selected) {
			if (i != 0 && !obj.options[i-1].selected) {
				swapOptions(obj,i,i-1);
				obj.options[i-1].selected = true;
				}
			}
		}
	}

// -------------------------------------------------------------------
// moveOptionDown(select_object)
//  Move selected option in a select list down one
// -------------------------------------------------------------------
function moveOptionDown(obj) {
	if (!hasOptions(obj)) { return; }
	for (i=obj.options.length-1; i>=0; i--) {
		if (obj.options[i].selected) {
			if (i != (obj.options.length-1) && ! obj.options[i+1].selected) {
				swapOptions(obj,i,i+1);
				obj.options[i+1].selected = true;
				}
			}
		}
	}

// -------------------------------------------------------------------
// removeSelectedOptions(select_object)
//  Remove all selected options from a list
//  (Thanks to Gene Ninestein)
// -------------------------------------------------------------------
function removeSelectedOptions(from) {
	if (!hasOptions(from)) { return; }
	if (from.type=="select-one") {
		from.options[from.selectedIndex] = null;
		}
	else {
		for (var i=(from.options.length-1); i>=0; i--) {
			var o=from.options[i];
			if (o.selected) {
				from.options[i] = null;
				}
			}
		}
	from.selectedIndex = -1;
	}

// -------------------------------------------------------------------
// removeAllOptions(select_object)
//  Remove all options from a list
// -------------------------------------------------------------------
function removeAllOptions(from) {
	if (!hasOptions(from)) { return; }
	for (var i=(from.options.length-1); i>=0; i--) {
		from.options[i] = null;
		}
	from.selectedIndex = -1;
	}

// -------------------------------------------------------------------
// addOption(select_object,display_text,value,selected)
//  Add an option to a list
// -------------------------------------------------------------------
function addOption(obj,text,value,selected) {
	if (obj!=null && obj.options!=null) {
		obj.options[obj.options.length] = new Option(text, value, false, selected);
		}
	}

function issuePopup( id )
{
	var url = "/PickIssue.aspx?id=" + id;

	// if legalwebmedia
	if( location.href.match( "^https?://(www\.)?legalwebmedia" ) )
	{
		url = "/lv" + url;
	}


	// Open new window
	var issueWindow = window.open(url, 'videoWindow', 'scrollbars=yes,resizable=yes,width=555,height=400');
	issueWindow.focus();
	return false
}

function IssueFilePopup( id )
{

	var url = "/legalwebmedia/admin/AttorneyCaseEvaluation/FileManagerPicker.asp?mode=Picker&SourceID=" + id;
	
	// Open new window
	var issueWindow = window.open(url, 'file_window', 'scrollbars=yes,resizable=yes,width=550,height=510');
	issueWindow.focus ();	// If the window is already open, it will reload and get the focus
	return false;
}

function SetNone( source_id )
{
	var hidden_upload_field = document.getElementById( source_id + "_hidden")
   	var visible_upload_field = document.getElementById( source_id + "_visible" )

	visible_upload_field.innerHTML = '[None]';
	hidden_upload_field.value = '';

}

function SetExternalFileUploadID( upload_id, file_name, source_id )
{
	var hidden_upload_field = opener.document.getElementById( source_id + "_hidden")
   	var visible_upload_field = opener.document.getElementById( source_id + "_visible" )
      
	visible_upload_field.innerHTML = file_name;
	hidden_upload_field.value = upload_id;
	
	self.close();
}




