

var UserIDStamp_Checkbox;
var UserIDStamp_FormID='';
var UserIDStamp_mousex=0;
var UserIDStamp_mousey=0;
var TurnCustomPageScrollBarOn=true;

// ===================================================================
// Form calculated field functions
// ===================================================================

// Find all sum fields.  
//For each sum field if there is a formula then evaluate and set the field's text to the formula ouput value
if (!Array.prototype.indexOf)
{
  Array.prototype.indexOf = function(elt /*, from*/)
  {
    var len = this.length;

    var from = Number(arguments[1]) || 0;
    from = (from < 0)
         ? Math.ceil(from)
         : Math.floor(from);
    if (from < 0)
      from += len;

    for (; from < len; from++)
    {
      if (from in this &&
          this[from] === elt)
        return from;
    }
    return -1;
  };
}

/*
ctrlFDFormview___FormConditionLookupURL
Array.prototype.search = function(s,q){
  var len = this.length;
  for(var i=0; i<len; i++){
    if(this[i].constructor == Array){
      if(this[i].search(s,q)){
        return i;
        break;
      }
     } else {
       if(q){
         if(this[i].indexOf(s) != -1){
           return i;
           break;
         }
      } else {
        if(this[i]==s){
          return i;
          break;
        }
      }
    }
  }
  return -1;
}
*/


var AllVVFields = new Array();
var SumsCalculated = null;

//find all sum fields and evaluate their formulas
function evaluateSumFields(){
	var result=0;	

	//setup circular reference catcher
	SumsCalculated = new Array();
	
	//create array of only named VVFields if empty
	if (AllVVFields.length == 0) {
		var AllInputs = document.getElementsByTagName('input');
	  
		for (var i=0;i<AllInputs.length;i++){
			if (AllInputs[i].getAttribute('VVFieldName')!=null){
				AllVVFields.push(AllInputs[i]);
			}
		}	
	}
 
	for(var j=0;j<AllVVFields.length;j++){
		//for each VVField determine if a Sum Field
		if (AllVVFields[j].getAttribute('VVFieldType')!=null){
			if(AllVVFields[j].getAttribute('VVFieldType')=='sumfield'){
				evaluateSumField(AllVVFields[j]);
			}
		} 
	}
}

function evaluateSumField(sumField){
	var result=0;	

	var formula=sumField.getAttribute('formula');
	if (formula != null) {	
		if (formula.length>0){
			//replace field tokens with values
			formula = parseFormula(formula);
			
			//try to evaluate the formula
			try{
				result=eval(formula);
			} catch(e) {
				result=0;
			}
			
			//round result to two decimal points
			if (result == parseFloat(result))
			{
				result=Math.round(result*100)/100; 
			} else {
				result=0;
			}
			
			if (!isFinite(result)) result=0;
			
			//enter the result into the sum field
			document.getElementById(sumField.id).value = result;
			//sumField.value=result;
		}
	}
}

//test a formula entered in a textbox
function testFormula(){

	var el = document.getElementById('inputFormTextBoxFormulaID');
	
	if (el){	
		var tb = document.getElementById(el.value);
		var forumula;
		var result;

		if (tb){
			formula = tb.value;
			
			try{
				if (formula.length>0){
					formula = parseFormula(formula);
					
					result = eval(formula);
				}else{
					result = 'Formula contains no value';
				}
			}catch(e){
				result = e.message;
			}

			alert(result);
		}else{
			alert('No formula found');
		}	
	}else{
		alert('inputFormTextBoxFormulaID not found');
	}	
}

//parse a sum field's formula and replace tokens with values
function parseFormula(formula){
	
	var originalFormula = formula;
	
	//if the formula contains and line feeds we replace the line feeds with spaces
	formula = formula.replace('\n',' ');
	
	//find form field names contained within brackets[]
	var formFields = formula.split('[');
	var formField;
	
	if (formFields.length>0){
		for(var i=0;i<formFields.length;i++){
			//trim right brackets ']' and all characters following the bracket
			var end=formFields[i].indexOf(']');
			if (end != -1){
				var formField = formFields[i].substring(0,end);
				
				//now get the value of the form field
				//if form field not found return an error
				var fieldValue = getCellFieldValue(formField)
				
				//replace the field token with its value
				var fieldToken='[' + formField + ']';
				formula=formula.replace(fieldToken,fieldValue);				
			}
			
		}
	}	
	
	//We used to use {} as tokens for cell fields which was a mistake because we could not
	//support conditional logic (ie if statements).  For backwards compatibility if we do not have an IF 
	//statement in the formula and we do not have tokens which start with ## then we continue to look for tokens which start and end with {}.
	
	if (originalFormula.indexOf('if') != -1 || originalFormula.indexOf('#!') != -1){
		//find row \ column group name tokens where tokens start with #! and end with !#
		var cellGroups = formula.split('#!');
		var groupName;
		
		if (cellGroups.length>0){
			for(var i=0;i<cellGroups.length;i++){
				//trim right braces '!#' and all characters following the brace
				var end=cellGroups[i].indexOf('!#');
				if (end != -1){
					var groupName = cellGroups[i].substring(0,end);
					
					//now get the value of the row\column field
					//if field not found return an error
					var groupValue = getGroupNameValue(groupName)
					
					//replace the field token with its value
					var fieldToken='#!' + groupName + '!#';
					formula=formula.replace(fieldToken,groupValue);					
				}				
			}
		}	
	}else{	
		//find row \ column group names contained in braces{}
		var cellGroups = formula.split('{');
		var groupName;
		
		if (cellGroups.length>0){
			for(var i=0;i<cellGroups.length;i++){
				//trim right braces '}' and all characters following the brace
				var end=cellGroups[i].indexOf('}');
				if (end != -1){
					var groupName = cellGroups[i].substring(0,end);
					
					//now get the value of the row\column field
					//if field not found return an error
					var groupValue = getGroupNameValue(groupName)
					
					//replace the field token with its value
					var fieldToken='{' + groupName + '}';
					formula=formula.replace(fieldToken,groupValue);					
				}	
			}
		}	
	}
		
	return formula;
}

/*
//search for a VV Form cell field and return its value as float
//if field not found or if field does not contain a numeric value then return 0
function getCellFieldValue(fieldName){
	//var inputs = document.getElementsByTagName('input');
	var returnVal=0;
 
	//look through all cell fields for the given fieldName
	for(var i=0;i<AllVVFields.length;i++){
                 
     if(AllVVFields[i].getAttribute('VVFieldName')!=null){
		 if(AllVVFields[i].getAttribute('VVFieldName')==fieldName){
			//found matching field		
			var cellValue=AllVVFields[i].value;
			if (cellValue == parseFloat(cellValue)) returnVal=parseFloat(cellValue); //check for numeric	
			return returnVal; //stop searching			
		}
     } 
   }
  
  //if no cell field found the try textbox and labeltextbox
  var cellValue=getFieldValue(fieldName,'textbox');
  if (cellValue == parseFloat(cellValue)) returnVal=parseFloat(cellValue); //check for numeric	
	
  //if returnVal is 0 then try dropdownlists
  var cellValue=getFieldValue(fieldName,'dropdownlist');
  if (cellValue == parseFloat(cellValue)) returnVal=parseFloat(cellValue); //check for numeric					
		
  return returnVal;	
}
*/


//search for a VV Form cell field and return its value as float
//if field not found or if field does not contain a numeric value then return 0
function getCellFieldValue(fieldName){
	//var inputs = document.getElementsByTagName('input');
	var returnVal=0;

	//look through all cell fields for the given fieldName
	for(var i=0;i<AllVVFields.length;i++){
		if(AllVVFields[i].getAttribute('VVFieldName')!=null){
			if(AllVVFields[i].getAttribute('VVFieldName')==fieldName){
				//found matching field
				
				//if SumField, have the SumField calculate its value first
				if(AllVVFields[i].getAttribute('VVFieldType')=='sumfield'){
					//if name not in SumsCalculated
					//add name and call eval
					if (SumsCalculated.indexOf(fieldName) == -1) {
						SumsCalculated.push(fieldName);
						evaluateSumField(AllVVFields[i]);
					}
				}			
				
				var cellValue = null;
				var el = document.getElementById(AllVVFields[i].id);
				if (el != null) {
					cellValue=el.value;
				} else {
					cellValue=AllVVFields[i].value;
				}
				
				if (cellValue == parseFloat(cellValue)) {
					returnVal=parseFloat(cellValue); //check for numeric
				}
				
				return returnVal; //stop searching			
			}
		}
	}
  
	//if no cell field found the try textbox and labeltextbox
	var cellValue=getFieldValue(fieldName,'textbox');
	if (cellValue == parseFloat(cellValue)) returnVal=parseFloat(cellValue); //check for numeric	

	//if returnVal is 0 then try dropdownlists
	var cellValue=getFieldValue(fieldName,'dropdownlist');
	if (cellValue == parseFloat(cellValue)) returnVal=parseFloat(cellValue); //check for numeric					
		
	return returnVal;	
}


//search for a VV Form field and return its value as a string
//if field not found return empty string
function getFieldValue(fieldName,fieldType){
	var returnVal='';
	
	switch(fieldType){
		case "textbox":
		case "labeltextbox":
			//look through all input fields for the given fieldName
			var inputs = document.getElementsByTagName('input');
			
			for(var i=0;i<inputs.length;i++){
                 
				if(inputs[i].getAttribute('VVFieldName')!=null){
					if(inputs[i].getAttribute('VVFieldName')==fieldName){
						//found matching field		
						returnVal=inputs[i].value;
						return returnVal; //stop searching							
					}
				} 
			}
			break;
		case "dropdownlist":
			//look through all select fields for the given fieldName
			var selects = document.getElementsByTagName('select');
			
			for(var i=0;i<selects.length;i++){
                 
				if(selects[i].getAttribute('VVFieldName')!=null){
					if(selects[i].getAttribute('VVFieldName')==fieldName){
						//found matching field		
						returnVal=selects[i].value;
						return returnVal; //stop searching							
					}
				} 
			}
			break;	
	}	
   
  return returnVal;	
}

//search for a VV row\column group name field and return its value
//if field not found or if field does not contain a numeric value then return 0
function getGroupNameValue(groupName){
	var inputs = document.getElementsByTagName('input'); //cell fields are inputs
	//var spans = document.getElementsByTagName('span'); //sum fields are spans (asp.net labels)
	var returnVal=0;
 
	//look through all cell and sum fields for the given groupName
	for(var i=0;i<inputs.length;i++){
                 
		if(inputs[i].getAttribute('VVRowName')!=null){ //look for matching row name
			if(inputs[i].getAttribute('VVRowName')==groupName){
				//found matching attribute		
				var cellValue=inputs[i].value;
				if (cellValue == parseFloat(cellValue)) returnVal+=parseFloat(cellValue); //check for numeric					
			}
		}
     
		if(inputs[i].getAttribute('VVColName')!=null){ //look for matching column name
			if(inputs[i].getAttribute('VVColName')==groupName){
				//found matching attribute		
				var cellValue=inputs[i].value;
				if (cellValue == parseFloat(cellValue)) returnVal+=parseFloat(cellValue); //check for numeric					
			}     
		}
    }  
   
   return returnVal;	
}


//FORM LOOKUP SUPPORT

function lookupFormData(formID,fieldID,fieldName,fieldType){

	try{
			//get the value of the form field being used for the lookup
				
			var fieldValue = getFieldValue(fieldName,fieldType);
			var responseText=''; //we expect to get back a string containing comma separated name\value pairs
			
			var inputFormDataLookupURL='';
			if (document.getElementById('inputFormDataLookupURL')) inputFormDataLookupURL=document.getElementById('inputFormDataLookupURL').value;
			
			//append the formId and fieldName to the querystring
						
			if (inputFormDataLookupURL.indexOf("?")!=-1){
				inputFormDataLookupURL += "formid=" + formID + "&fieldid=" + fieldID + "&fieldname=" + fieldName + "&value=" + fieldValue;
			}else{
			    inputFormDataLookupURL += "?formid=" + formID + "&fieldid=" + fieldID + "&fieldname=" + fieldName + "&value=" + fieldValue;
			}
	
			var xmlhttp = new GetXmlHttp();
	
			if (fieldValue.length>0 && inputFormDataLookupURL.length>0){
				//initiate callback to the server							
				
				//wait for response from server before continuing script processing;
								
				if (xmlhttp){				
					//send request to server
					xmlhttp.open("GET",inputFormDataLookupURL,false);
	   				xmlhttp.send(null);	
				}			
			}
			
			if (xmlhttp && xmlhttp.readyState==4){//we got something back..							
				//get response back from the server
				if (xmlhttp.status==200) responseText = xmlhttp.responseText;				
			}
			
			if (responseText.length>0) setFormFieldValues(responseText);
			
			//cell field values may have changed so re-evaluate any formulas
			evaluateSumFields();
				
		} catch(e) {
		  
		}
}


function  setFormFieldValues(responseText){

	try{
		var fieldCollection = responseText.split(',');
		
		for(var i=0;i<fieldCollection.length;i++){
			var nameValue=fieldCollection[i].split('=');
			if (nameValue.length>0){
				var fieldName=nameValue[0];
				var fieldValue=nameValue[1];
				
				//we use @= and @- as an escape character if the field value contained an '=' or ',' (our split characters)
				//replace the escape characters
				
				fieldValue=fieldValue.replace( new RegExp( "@=", "g" ), "=" );
				fieldValue=fieldValue.replace( new RegExp( "@-", "g" ), "," );
				
				if (fieldName.length>0 && fieldValue.length>0) setFieldValue(fieldName,fieldValue);
			}			
		}	
	
	}catch(e){
	
	}
}

//search for a VV Form field and set its value

function setFieldValue(fieldName,fieldValue){
	var inputs = document.getElementsByTagName('input');
	var FoundField = false;
	 
	//look through all VV form text boxes for the given fieldName
	for(var i=0;i<inputs.length;i++){
                 
     if(inputs[i].getAttribute('VVFieldName')!=null){
		 if(inputs[i].getAttribute('VVFieldName')==fieldName){
			//found matching field		
			inputs[i].value=fieldValue;	
			FoundField = true;
			break;
		}
     } 
   }
   
   //if field not found look for textarea elements which have the given fieldName
   if (FoundField==false){
   
	var inputs = document.getElementsByTagName('textarea');
		 
		for(var i=0;i<inputs.length;i++){
	                 
		if(inputs[i].getAttribute('VVFieldName')!=null){
			if(inputs[i].getAttribute('VVFieldName')==fieldName){
				//found matching field		
				inputs[i].value=fieldValue;	
				break;
			}
		} 
	}
   }
}


function DoLookupVisibilityCheck(formID,groups){
	// Uses two hidden input fields 
	// __ConditionGroup  -  stores the group, conditions and visible fields
	// __FormConditionLookupURL  -  stores the URL to POST the field values for evaluation to
	
	
	var v1 = new Array(); //All the Group Names for this Form
	var v2 = new Array(); //All the ConditionFields
	var v3 = new Array(); //All the Fields to be visible or invisible
	var v4 = new Array(); //All the outcome modes for each group
	
	var ndex = 0;
	var condgrp = '';
	var navBarDivList = '';

	//Used to control visibility of Save and Navigation bar
	var tempCtrl1 = document.getElementById('inputFormNavBarDivList');
	if (tempCtrl1 != null)
		navBarDivList = tempCtrl1.value;
		

	//debugger;
	
	// ***************************************************************************
	// Decypher hidden input field of groups and condition fields
	// ***************************************************************************

	// This will decrypt the hidden input field holding the list of groups, condition controls
	// and the controls that will either be visible or hidden after the evaluation is completed
	// The hidden input field is constructed as follows
	// groupname1=[field1,field2,field3],[field4,field5,field6];groupname2=[field7,field8,field9],[field10,field11,field12]
	// The output will be construct as follows
	// var v1 = new array('groupname1','groupname2','groupname3'); //All the Group Names for this Form
	// var v2 = new array('field1,field2,field3','field7,field8,field9','field13,field14,field15'); //All the ConditionFields
	// var v3 = new array('field4,field5,field6','field10,field11,field12','field16,field17,field18');  //All the Fields to be visible or invisible
	// var v4 = new array(0,0,1); //All the outcome modes for each group, 0 = Visible, 1 = Readonly
	
	if (document.getElementById('ctrlFDFormview___ConditionGroup')) {
		condgrp=document.getElementById('ctrlFDFormview___ConditionGroup').value;
	}else if (document.getElementById('ctrlPvRowview___ConditionGroup')){
		condgrp=document.getElementById('ctrlPvRowview___ConditionGroup').value;
	}else if (document.getElementById('ctrlPanelHolder_0_ctrlFDFormview___ConditionGroup')) {
		condgrp=document.getElementById('ctrlPanelHolder_0_ctrlFDFormview___ConditionGroup').value;
	}else{
		return;
	}
	
	if (condgrp.length > 0 ){

		while (ndex < condgrp.length) {
			var grp = '';
			var outcome = '';
			
			// extract the group name
			var grpndex = condgrp.indexOf('=', ndex);
			if (grpndex > -1) {
				grp = condgrp.substr(ndex, (grpndex - ndex));
				
				// extract the Outcome modes
				var leftbrkt = condgrp.indexOf(',', ndex);
				if (leftbrkt > -1){
					outcome = condgrp.substr(grpndex + 1, ((leftbrkt - 1) - grpndex));
				}
				
				ndex = grpndex;
			}
					
			var condleftndex = -1;
			var condrightndex = -1;
			var conditions = '';
			
			// extract the condition fields
			condleftndex = condgrp.indexOf('[', ndex);
			if (condleftndex > -1){
				condrightndex = condgrp.indexOf(']', condleftndex);
				if (condrightndex > -1){
					conditions = condgrp.substr(condleftndex + 1, (condrightndex - condleftndex) - 1);
					ndex = condrightndex;
				}
			}
			
			var visleftndex = -1;
			var visrightndex = -1;
			var visibles = '';
			
			// extract the visible fields
			visleftndex = condgrp.indexOf('[', ndex + 1);
			if (visleftndex > -1){
				visrightndex = condgrp.indexOf(']', visleftndex);
				if (visrightndex > -1){
					visibles = condgrp.substr(visleftndex + 1, (visrightndex - visleftndex) - 1);
					ndex = visrightndex;
				}
			}
		
			// push group onto v1 array
			v1.push(grp);
			grp = '';
			
			// push all of the condition fields onto v2 array
			v2.push(conditions);
			conditions = '';
			
			// push all of the visible fields onto v3 array
			v3.push(visibles);
			visibles = '';
			
			//push outcome mode onto the v4 array
			v4.push(outcome);
			outcome = '';


			ndex = condgrp.indexOf(';', ndex);
			
			if (ndex == -1)
				ndex = condgrp.length;
			else
				ndex++;
		
		} //while (ndex < condgrp.length) {
	 
	 } //if (condgrp.length > 0 ){
	

	var fields = new Array();

	//Add group list to postback string
	//var encodedData = '&cbvvClientID=' + clientID + '&cbvvEvent=' + cbEvent + '&cbControlUniqueIDToRender=' + serverControlToRender;
	var encodedData = "&groups=" + groups;

	//split groups into array
	var grps = groups.split(',');
	
	
	// ***************************************************************************
	// This will create a single array of all the fields that the conditions need
	
	//loop through groups
	for(var a=0;a<grps.length;a++){
		var grp = grps[a];
		var grphlder;
		
		//gather condition fields to get data from
		for(var b=0;b<v1.length;b++){
			if(v1[b] == grp) {
				var strFlds = v2[b];
				var temp = strFlds.split(',');
				
				//loop thru existing fields and if not already in array add it
				for(var c=0;c<temp.length;c++){
					var ndex=fields.indexOf(temp[c]);
					if (ndex == -1)
						fields.push(temp[c]);
				}
			} //if(v1[b] == grp) {
		} //for(var b=0;b<v1.length;b++){
	} //for(var i=0;i<grps.length;i++){
		

	// ***************************************************************************
	// This will create the encoded data stream that contains the values of all the fields
	// that are int the conditions to be evaluated.

	if (document.forms.length > 0) {

		var form = document.forms[0]; //use getElementById(FormID) if there is ever more than 1 form;
		for (var elementIndex = 0; elementIndex < form.length; ++elementIndex) {
			var element = form.elements[elementIndex];
			if (element.name) {
		
				//Get the Field Guid
				var vvFieldID = element.getAttribute("vvfieldvalueid");	
				if (vvFieldID != null) { //If element had a vvFieldID attribute
				
					//look in the field arrays
					var ndex=fields.indexOf(vvFieldID);
					
					//if control is in field array setup the name value pair
					if (ndex > -1) {
						var elementValue = null;
						
						if (element.nodeName == "INPUT") {
							var inputType = element.getAttribute("TYPE").toUpperCase();
							if (inputType == "TEXT" || inputType == "PASSWORD" || inputType == "HIDDEN") {
								elementValue = element.value;
							} else if (inputType == "CHECKBOX" || inputType == "RADIO") {
								if (element.checked) {
									elementValue = "true";
								} else {
									elementValue = "false";
								}
							}
						} else if (element.nodeName == "SELECT") {
							if (element.multiple) {
								elementValue = [];
								for (var i = 0; i < element.length; ++i) {
									if (element.options[i].selected) {
										elementValue.push(element.options[i].value);
									}
								}
							} else {
								elementValue = element.value;
							}
						} else if (element.nodeName == "TEXTAREA") {
							elementValue = element.value;
						}
						
						//-------------------------------------------------------------------------------
						
						if (elementValue instanceof Array) {
							for (var i = 0; i < elementValue.length; ++i) {
								encodedData += "&" + vvFieldID + "=" + encodeURIComponent(elementValue[i]);
							}
						} else if (elementValue) {
							encodedData += "&" + vvFieldID + "=" + encodeURIComponent(elementValue);
						}
						elementValue = null;

					} //if (ndex > -1) {
				} else { //if (vvFieldID != null) {
				
					// Look for the checkbox here
					if (element.nodeName == "INPUT") {
					
						// Checkboxes render inside a SPAN Tag, so check for embedded INPUT element
						var inputType = element.getAttribute("TYPE").toUpperCase();
						if (inputType == "CHECKBOX" || inputType == "RADIO") {
						
							// The parentnode of a checkbox is a span tag which is where the attributes are rendered
							var parentnode = element.parentNode;
							if (parentnode != null) {
							
								if (parentnode.nodeName == "SPAN") {
								
									var vvFieldID = parentnode.getAttribute("vvfieldvalueid");
									if (vvFieldID != null) {
										//look in the field arrays
										var ndex=fields.indexOf(vvFieldID);
								
										//if control is in field array setup the name value pair
										if (ndex > -1) {
												
											var inputs = parentnode.getElementsByTagName("input");
											if (inputs.length > 0) {
												for (var i = 0; i < inputs.length; ++i) {
												
													var element = inputs[i];
													if (element.name) {
													
														if (element.nodeName == "INPUT") {
															var inputType = element.getAttribute("TYPE").toUpperCase();
															
															if (inputType == "CHECKBOX" || inputType == "RADIO") {
																if (element.checked) {
																	elementValue = "true";
																} else {
																	elementValue = "false";
																}
															}
															
															//-------------------------------------------------------------------------------
										
															if (elementValue instanceof Array) {
																for (var i = 0; i < elementValue.length; ++i) {
																	encodedData += "&" + vvFieldID + "=" + encodeURIComponent(elementValue[i]);
																}
															} else if (elementValue) {
																encodedData += "&" + vvFieldID + "=" + encodeURIComponent(elementValue);
															}
															elementValue = null;
															
														} // if (element.nodeName == "INPUT") {
													
													
													} // if (element.name) {

												} // for (var i = 0; i < inputs.length; ++i) {
											} // if (inputs.length > 0) {
											
										} // if (ndex > -1) {
									} // if (vvFieldID != null) {
								
								} // if (parentnode.nodeName == "SPAN") {
							
							} // if (parentnode != null) {
						
						} // if (inputType == "CHECKBOX" || inputType == "RADIO") {
				
					} // if (element.nodeName == "INPUT") {
				
				} // if (vvFieldID != null) { //If element had a vvFieldID attribute
				
			} //if (element.name) {
		} //for (var elementIndex = 0; elementIndex < form.length; ++elementIndex) {
	} //if (document.forms.length > 0) {
		
	
	// ***************************************************************************
	// This will retrieve the URL from a hidden input field and make the callback
	//  to a special page that will evaluate the conditions

	
	//get the XmlHttpRequest object
	var xmlhttp = new GetXmlHttp();
	var responseText=''; //we expect to get back a string containing comma separated name\value pairs

	// retrieve the url from a hidden input field
	var url='';   
	//ctrlPvRowview___FormConditionLookupURL               
	if (document.getElementById('ctrlFDFormview___FormConditionLookupURL')){
		url=document.getElementById('ctrlFDFormview___FormConditionLookupURL').value;
	}else if (document.getElementById('ctrlPvRowview___FormConditionLookupURL')){
		url=document.getElementById('ctrlPvRowview___FormConditionLookupURL').value;
	}else if (document.getElementById('ctrlPanelHolder_0_ctrlFDFormview___FormConditionLookupURL')){
		url=document.getElementById('ctrlPanelHolder_0_ctrlFDFormview___FormConditionLookupURL').value;
	}else{
		return;
	}
	
	//append the formId to the querystring
	if (url.indexOf("?")!=-1)
		url += "formid=" + formID;
	else
		url += "?formid=" + formID;
	
	// send the data
	if (xmlhttp) {
		//debugger;
		xmlhttp.open("POST",url,false);
		//Prevent caching
		xmlhttp.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
		//make request appear as normal form post
		xmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded; charset=UTF-8');
		//encode the arguments and post to server	   
	   	xmlhttp.send(encodedData);
	}
		
	
	if (xmlhttp && xmlhttp.readyState==4){//we got something back..							
		//get response back from the server
		if (xmlhttp.status==200) 
			responseText = xmlhttp.responseText;				
	}
	
	//***************************************************************************
	
	//var fieldlist = new Array( new Array());
	var visiblefieldlist = new Array();
	var visiblesettinglist = new Array();
	
	var readonlyfieldlist = new Array();
	var readonlysettinglist = new Array();
	
	// response will be in the form of grp1=true,grp2=false
	if (responseText.length>0) {
		var respgrps = responseText.split(',');
		
		//gather group responses
		for(var a=0;a<respgrps.length;a++){
			var thegrouppairhldr = respgrps[a];
			var thegrouppair = thegrouppairhldr.split('=');
			
			if (thegrouppair.length == 2) {
				var thegroup = thegrouppair[0]; //get the group name
				var visibleReadonlyValue = thegrouppair[1]; //get the visiblity state
				
				var ndex=v1.indexOf(thegroup);
				if (ndex != -1){
					var outcomemode = v4[ndex]; // determine if this is a visibility group or readonly
					var strflds = v3[ndex];  // comma separated list of fields for this group
					var fields = strflds.split(',');
					
					//setup the two lists that will contain the fieldids 
					//of the elements to make visible or readonly
					if (outcomemode == '0') { // visibilty setting
						for(var b=0;b<fields.length;b++){
							var ndex1=visiblefieldlist.indexOf(fields[b]);
						
							// Add FieldID and visibility to lists
							if (ndex1 == -1) {
								visiblefieldlist.push(fields[b]);
								visiblesettinglist.push(visibleReadonlyValue);
							} // if (ndex1 == -1) {
						
						} // for(var b=0;b<respgrps.length;b++){					
					
					} else if (outcomemode == '1') { //readonly setting
						for(var b=0;b<fields.length;b++){
							var ndex1=readonlysettinglist.indexOf(fields[b]);
						
							// Add FieldID and visibility to lists
							if (ndex1 == -1) {
									readonlyfieldlist.push(fields[b]);
									readonlysettinglist.push(visibleReadonlyValue);
							} // if (ndex1 == -1) {
						} // for(var b=0;b<respgrps.length;b++){
					}

				} // if (ndex != -1){
	
			} // if (thegrouppair.length == 2) {
	
		} // for(var a=0;a<respgrps.length;a++){
		
	} // if (responseText.length>0) {
	
	// --------------------------------------------------------------------------

/*
	// All the controls to have their visibility controlled
	if (fieldlist.length > 0) {
		for (var fieldIndex = 0; fieldIndex < fieldlist.length; ++fieldIndex) {
			if(fieldlist[fieldIndex].constructor == Array){ //ensures this is a multidimension array
				vvFieldID = fieldlist[fieldIndex][0]
				var element = document.getElementsByName(vvFieldID)
				
				if (element != null) { //If element had a vvFieldID attribute
					if (element.length != 0) {
						if (fieldlist[fieldIndex][1].toLowerCase() == "true"){
							//element[0].style.visiblity = "visible";
							element[0].style.display = "inline";
						}else{
							//element[0].style.visiblity = "collapse";
							element[0].style.display = "none";
						}
					}
				} // if (element != null) { //If element had a vvFieldID attribute
			} // if(fieldlist[fieldIndex].constructor == Array){	
		} // for (var fieldIndex = 0; fieldIndex < fieldlist.length; ++fieldIndex) {
	} // if (fieldlist.length > 0) {
*/

	// ***************************************************************************
	var visiblefieldcount = 0;
	var readonlyfieldcount = 0;
	if (visiblefieldlist.length > 0 || readonlyfieldlist.length > 0) {
		var divs = document.getElementsByTagName("div");
		if (divs.length > 0) {
			for (var i = 0; i < divs.length; ++i) {
				var element = divs[i];
				
				//Get the Field Guid
				var vvFieldID = element.getAttribute("vvfieldid");
			
				if (vvFieldID != null) { //If element had a vvFieldID attribute
					var ndex = visiblefieldlist.indexOf(vvFieldID);

					//if control is in field array, set the visibility style
					if (ndex > -1) {
						visiblefieldcount++;
						if (visiblesettinglist[ndex].toLowerCase() == "true"){
							//element.style.visiblity = "visible";
							element.style.display = "inline";
						}else{
							//element.style.visiblity = "hidden";
							element.style.display = "none";
						}
						
						if (IsControlInNavBarList(navBarDivList, element) == true) {
							if (ShouldNavBarBeVisible() == false) {
								SetNavBarInvisible();
							} else {
								SetNavBarVisible();
							}
						}						
						
						
					} else {
						var ndex = readonlyfieldlist.indexOf(vvFieldID);
						if (ndex > -1) {
							readonlyfieldcount++;
							if (readonlysettinglist[ndex].toLowerCase() == "true"){
								//set to readonly
								SetAllElementsReadonlyAttribute(element, true);
							}else{
								//set to edittable
								SetAllElementsReadonlyAttribute(element, false);
							}
						}
					}
				} // if (vvFieldID != null) {
			} // for (var i = 0; i < divs.length; ++i) {
		} // if (divs.length > 0) {
	} // if (fieldlist.length > 0) {
	
	if (visiblefieldcount < visiblefieldlist.length || readonlyfieldcount < readonlyfieldlist.length) {
		// loop through all controls on the page
		if (document.forms.length > 0) {
			var form = document.forms[0];
			for (var elementIndex = 0; elementIndex < form.length; ++elementIndex) {
				var element = form.elements[elementIndex];
				if (element.name) {

					//Get the Field Guid
					var vvFieldID = element.getAttribute("vvfieldid");
					
					if (vvFieldID != null) { //If element had a vvFieldID attribute
					
						//if control is in field array, set the visibility style
						var ndex = visiblefieldlist.indexOf(vvFieldID);

						if (ndex > -1) {
							if (visiblesettinglist[ndex].toLowerCase() == "true"){
								//element.style.visiblity = "visible";
								element.style.display = "inline";
							}else{
								//element.style.visiblity = "hidden";
								element.style.display = "none";
							}
							
							if (IsControlInNavBarList(navBarDivList, element) == true) {
								if (ShouldNavBarBeVisible() == false) {
									SetNavBarInvisible();
								} else {
									SetNavBarVisible();
								}
							}
						} else {
							var ndex = readonlyfieldlist.indexOf(vvFieldID);
							if (ndex > -1) {
								readonlyfieldcount++;
								if (readonlysettinglist[ndex].toLowerCase() == "true"){
									//set to readonly
									SetAllElementsReadonlyAttribute(element, true);
								}else{
									//set to edittable
									SetAllElementsReadonlyAttribute(element, false);
								}
							}
						}					
					} // if (vvFieldID != null) { //If element had a vvFieldID attribute
				} // if (element.name) {
			} // for (var elementIndex = 0; elementIndex < form.length; ++elementIndex) {
		} // if (document.forms.length > 0) {
	} // if (fieldcount < fieldlist.length) {
	

	/*
	// All the controls to have their visibility controlled
	if (fieldlist.length > 0) {
	
		// loop through all controls on the page
		if (document.forms.length > 0) {

			var form = document.forms[0]; //use getElementById(FormID) if there is ever more than 1 form;
			for (var elementIndex = 0; elementIndex < form.length; ++elementIndex) {
				var element = form.elements[elementIndex];
				if (element.name) {
			
					//Get the Field Guid
					var vvFieldID = element.getAttribute("VVFieldID");
					
					if (vvFieldID != null) { //If element had a vvFieldID attribute

						var ndex = -1;
						var len = fieldlist.length;

						for(var i=0; i<len; i++){ //loop thru each element to search in the inside array
							if(fieldlist[i].constructor == Array){ //ensures this is a multidimension array
								if (fieldlist[i][0] == vvFieldID){
									ndex = i;
									break;
								}
							} else { // Not used, handles single dimension arrays
								if (fieldlist.indexOf(vvFieldID) > -1){
									ndex = i;
									break;
								}
							}
						} // for(var i=0; i<len; i++){
						
						//if control is in field array, set the visibility style
						if (ndex > -1) {
							if (fieldlist[ndex][1].toLowerCase() == "true"){
								element.style.visiblity = "visible";
								element.style.display = "block";
							}else{
								element.style.visiblity = "hidden";
								element.style.display = "none";
							}
						} //if (ndex > -1) {
						
					} // if (vvFieldID != null) {				
					
				} //if (element.name) {
			} //for (var elementIndex = 0; elementIndex < form.length; ++elementIndex) {
			
		} //if (document.forms.length > 0) {
	
	} // if (fieldlist.length>0) {
	*/
	
	
		
	// ***************************************************************************
	/*
	// response will be in the form of grp1='true',grp2='false'
	if (responseText.length>0) {
		var respgrps = responseText.split(',');
		
		//gather group responses
		for(var a=0;a<respgrps.length;a++){
			var thegrouppairhldr = respgrps[a];
			var thegrouppair = thegrouppairhldr.split('=');
			
			if (thegrouppair.length == 2) {
				var thegroup = thegrouppair[0]; //get the group name
				var visiblevalue = thegrouppair[1]; //get the visiblity state
				
				var ndex=v1.indexOf(thegroup);
				if (ndex != -1){
					var strflds = v3[ndex];
					var fields = strflds.split(',');
					
					// loop through all controls on the page
					if (document.forms.length > 0) {

						var form = document.forms[0]; //use getElementById(FormID) if there is ever more than 1 form;
						for (var elementIndex = 0; elementIndex < form.length; ++elementIndex) {
							var element = form.elements[elementIndex];
							if (element.name) {
						
								//Get the Field Guid
								var vvFieldID = element.getAttribute("VVFieldID");
																
								//look in the field arrays
								var ndex=fields.indexOf(vvFieldID);
								
								//if control is in field array, set the visibility style
								if (ndex > -1) {
									if (visiblevalue.toLowerCase() == "true"){
										element.style.visiblity = "visible";
										element.style.display = "block";
									}else{
										element.style.visiblity = "hidden";
										element.style.display = "none";
									}
									//var elementValue = null;
									//if (element.nodeName == "INPUT") {
									//	
									//} else if (element.nodeName == "SELECT") {
									//	
									//} else if (element.nodeName == "TEXTAREA") {
									//	
									//}
								} //if (ndex > -1) {							
								
							} //if (element.name) {
						} //for (var elementIndex = 0; elementIndex < form.length; ++elementIndex) {
						
					} //if (document.forms.length > 0) {
				
				} //if(ndex != -1){
			} //if thegrouppair.length = 2 {	
		} //for(var a=0;a<respgrps.length;a++){
	} //if (responseText.length>0) {
*/	
	
	
} //function DoLookupVisibilityCheck(formID,groups){

function SetAllElementsReadonlyAttribute(el, isReadonly) {
	var childs = null;
	
	if (isReadonly ==  true) {
		SetElementToReadonly(el);
	}else {
		SetElementToWriteEnabled(el);
	}
	
	childs = el.getElementsByTagName("SPAN");
	for (var i = 0; i < childs.length; i++) { 
		var field = childs[i];
		
		if (isReadonly ==  true) {
			SetElementToReadonly(field);
		}else {
			SetElementToWriteEnabled(field);
		}
		
		var images = field.getElementsByTagName("IMG");
		for (var k = 0; k < images.length; k++) { 
			var img = images[k];

			var imgAttr = img.getAttribute("ctlTextbox");
			if (imgAttr != null) {
				if (imgAttr.length > 0) {
				
					if (isReadonly ==  true) {
							
						if (window.addEventListener){
							var value = img.getAttribute("onclick");
							if (value != null) {
								if (value.length > 0) {
									img.setAttribute("clickkey", value);
									img.removeAttribute("onclick");
								}
							}

						} else if (window.attachEvent){
							img.setAttribute("disabled", "true");
							//var txtbox = img.getAttribute("ctlTextbox");//ctlTextbox
							//var dateFormat = img.getAttribute("dateFormat");//dateFormat
							//var postBack = img.getAttribute("doPostBack");//doPostBack
							
							//img.detachEvent("onclick", new Function("CallPopUpCalendar('" + img.id + "', '" + txtbox + "', '" + dateFormat + "', '" + postBack + "')"));
					
						}
					} else {
						if (window.addEventListener){
							var value = img.getAttribute("clickkey");
							if (value != null) {
								if (value.length > 0) {
									//img.addEventListener('click', value, false);
									img.setAttribute("onclick", value);
									img.removeAttribute("clickkey");
								}
							}		
							
							
						} else if (window.attachEvent){
							img.removeAttribute("disabled");

							img.attachEvent("onclick", new Function("CallPopUpCalendar('" + img.id + "')"));
						}
								
					}
				}
			}
		}
	}
	
	childs = el.getElementsByTagName("INPUT");
	for (var i = 0; i < childs.length; i++) { 
		var field = childs[i];
		
		if (isReadonly ==  true) {
			SetElementToReadonly(field);
		}else {
			SetElementToWriteEnabled(field);
		}

	}
	
	childs = el.getElementsByTagName("SELECT");
	for (var i = 0; i < childs.length; i++) { 
		var field = childs[i];
		
		if (isReadonly ==  true) {
			SetElementToReadonly(field);
		}else {
			SetElementToWriteEnabled(field);
		}
	}
	
	childs = el.getElementsByTagName("TEXTAREA");
	for (var i = 0; i < childs.length; i++) { 
		var field = childs[i];

		if (isReadonly ==  true) {
			SetElementToReadonly(field);
		}else {
			SetElementToWriteEnabled(field);
		}
	}
}
function CallPopUpCalendar(imgId) {
	var ctlImg = document.getElementById(imgId);
	
	var disabledvalue = ctlImg.getAttribute("disabled");
	var txtBoxId = ctlImg.getAttribute("ctlTextbox");//ctlTextbox
	var dateFormat = ctlImg.getAttribute("dateFormat");//dateFormat
	var postBack = ctlImg.getAttribute("doPostBack");//doPostBack
	
	var ctlTextbox = document.getElementById(txtBoxId);
							
	if (disabledvalue != null) {
		if (disabledvalue.length > 0) {
			if (disabledvalue == "true") 
				return;
		}
	}
	//return popUpCalendar(this," & GetClientId() & ", '" & shortDateFormat.ToLower & "', '__doPostBack(\'" & GetClientId() & "\')')
	return popUpCalendar(ctlImg, ctlTextbox, dateFormat, postBack);
}

function SetElementToReadonly(el) {
	el.setAttribute("disabled", "disabled");
}

function SetElementToWriteEnabled(el) {
	el.removeAttribute("disabled");
	el.removeAttribute("readOnly");
}

function IsControlInNavBarList(navBarDivList,el) {	
	if (navBarDivList != null) {
		var divs = navBarDivList.split(";");
		if (navBarDivList.indexOf(el.id) != -1) {
			return true;
		} else {
			return false;
		}
	}
}

function ShouldNavBarBeVisible() {
	var barVisible = false;
	var ctrls = document.getElementById('inputFormNavBarDivList');
	if (ctrls != null) {
		var divs = ctrls.value.split(";");
		
		for(var a=0;a<divs.length;a++){
			var elId=divs[a];
			var el = document.getElementById(elId);
			if (el != null) {
				var isVisible = el.style.display;
				if (isVisible != "none") {
					barVisible = true;
				}
			
			}
			if (barVisible == true)
				break;
		}
	}
	return barVisible;
}
function SetNavBarVisible() {
	var inputNavBar = document.getElementById('inputFormNavBar');
	if (inputNavBar != null) {
		var navBar = document.getElementById(inputNavBar.value);
		if (navBar != null) {
			navBar.style.display = "inline";
		}
	}
}

function SetNavBarInvisible() {
	var inputNavBar = document.getElementById('inputFormNavBar');
	if (inputNavBar != null) {
		var navBar = document.getElementById(inputNavBar.value);
		if (navBar != null) {
			navBar.style.display = "none";
		}
	}
}

function IsNavBarVisible() {
	var barVisible = false;

	var inputNavBar = document.getElementById('inputFormNavBar');
	if (inputNavBar != null) {
		var navBar = document.getElementById(inputNavBar.value);
		if (navBar != null) {
			var isVisible = navBar.style.display;
			
			if (isVisible != "none") {
				barVisible = true;
			}			
		}
	}
	
	return barVisible;
}

function IsSaveButtonVisible() {
	var saveVisible = false;
	var inputSaveDivIDs = document.getElementById('inputFormSaveList').value;
	
	var SaveIDs = inputSaveDivIDs.split(";");
	if (SaveIDs.length > 0) {
		var SaveDivID = SaveIDs[0];
		var SaveButtonID = SaveIDs[1];
		
		if (IsElementVisible(SaveDivID)) {
			if (IsElementVisible(SaveButtonID)) {
				saveVisible = true;
			}
		}
	}

	return saveVisible;
}


function IsElementVisible(id) {
	var elementVisible = false;
	var el = document.getElementById(id);
	
	if (el != null) {
		var isVisible = el.style.display;
		
		if (isVisible != "none") {
			elementVisible = true;
		}			
	}
	
	return elementVisible;
}

function ClickSaveButton() {
	var inputSaveDivIDs = document.getElementById('inputFormSaveList').value;
	
	var SaveIDs = inputSaveDivIDs.split(";");
	if (SaveIDs.length > 0) {
		var SaveDivID = SaveIDs[0];
		var SaveButtonID = SaveIDs[1];
		
		var saveButton = document.getElementById(SaveButtonID)
		if (saveButton != null) {
		
			if( typeof( window.innerWidth ) == 'number' ) {
				//Non-IE
				var saveClick = saveButton.getAttribute("onClick");
				//javascript:vvCallbackFireEvent('ctrlPanelHolder:0:btnSave','divMain','divMain','ctrlPanelHolder_0_pnlFormViewer' ,'CenterTaskWindow();','' ,'','',event);setRefreshOpener();return false;
				
				var saveParts = saveClick.split(";");
				saveParts[1] = saveParts[1].replace("event", "''", "gi");
				
				var callString = saveParts[0] + ";" + saveParts[1] + ";" + saveParts[2];
				eval(callString);

			} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
				//IE 6+ in 'standards compliant mode'
				saveButton.click();
			} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
				//IE 4 compatible
				saveButton.click();
			}
		}
	}
}

function GetFormButtons() {
	var AllFormButtons = new Array;
	var AllInputs = document.getElementsByTagName('input');

	for (var i=0;i<AllInputs.length;i++){
		if (AllInputs[i].getAttribute('VVFieldType')!=null){
			if(AllInputs[i].getAttribute('VVFieldType')=='formbutton'){
				AllFormButtons.push(AllInputs[i]);
			}
		}
	}
	
	return AllFormButtons;
}








//*********************************************************
//       Simple UserIDStamp without Authentication
//*********************************************************

// Called from the Checkbox of a UserIDStamp
// Does not use password, performs simple UserID stamp
function CompleteUserIDStamp(formId,evt) {
	if (evt != null) {
		var el;
		
		if(typeof(evt.target)!='undefined'){
			el = evt.target;
		}else{
			if(typeof(evt.srcElement)!='undefined'){
				el = evt.srcElement;
			}
		}
		if (el != null) {
			// record click location
			UserIDStamp_mousex=LL_mousex;
			UserIDStamp_mousey=LL_mousey;
			
			// Attempt to sign signature stamp
			DoUserIDStamp(formId,el,'');
		}
	}
}

// Performs the simple UserIDStamp call back to VisualVault
// formID = ID of the form instance (GUID value) which holds the signature stamp
// chk = HTML Element iD of the check box which makes up part of the signature stamp form control
// responseText = Response from the server when we try to sign the signature stamp
function DoUserIDStamp(formId,chk,responseText) {
	var lblStamp;
	var result = '';
	var isAuthenticated = false; //holds the Authentication result as 'Authenticated' or 'Failed'
	var timeAuthenticated;
	var label;
	var pwd='';
	var fieldId='';
	var templateId='';
	var requiresAuthentication = false;
	var stampPrompt='';
	var errCode=0;
	var errMessage=''
	
	//if responseText is null then set to an empty string
	if (responseText == undefined){
		responseText = '';
	}
	
	if (chk==null) {
		return;
	} else {
		UserIDStamp_Checkbox = chk;
	}

	if (chk.parentNode.getAttribute('prompt')!=null) {
		if (chk.parentNode.getAttribute('prompt')!="") {
			stampPrompt=chk.parentNode.getAttribute('prompt');
		}
	}
	if (chk.parentNode.getAttribute('vvfieldvalueid')!=null) {
		if (chk.parentNode.getAttribute('vvfieldvalueid')!="") {
			fieldId=chk.parentNode.getAttribute('vvfieldvalueid');
		}
	}
	if (chk.parentNode.getAttribute('vvtemplateid')!=null) {
		if (chk.parentNode.getAttribute('vvtemplateid')!="") {
			templateId=chk.parentNode.getAttribute('vvtemplateid');
		}
	}

	if (chk.parentNode.previousSibling!=null) {
		lblStamp = chk.parentNode.previousSibling;
	} else if (chk.parentNode.nextSibling!=null) {
		lblStamp = chk.parentNode.nextSibling;
	}
	
	if (chk.checked == true && responseText.length == 0) {
	
		DoAuthenticateUserIDStamp(formId,fieldId,templateId,pwd,lblStamp,chk,'DoUserIDStamp');
		
	}else if (chk.checked == true){
	
		//response text comes back from the server after calling DoAuthenticateUserIDStamp
		//because  DoAuthenticateUserIDStamp makes an asynchronous call to the server, when the xmlHTTP call to the server
		//is complete then DoAuthenticateUserIDStamp calls this function again and passes in responseText
		
		var result = responseText;

		// response will be in the form of 'authentication'='True'~'time'='1/1/2000#09:00:00'~'label'='user.name 1/1/2000#09:00:00'
		if (result.length>0) {
			var respgrps = result.split('~');

			//gather responses
			for(var a=0;a<respgrps.length;a++){
				var thePairHldr=respgrps[a];
				var thePair=thePairHldr.split('=');
				
				if (thePair.length == 2) {
					var theName = thePair[0]; //holds 'Authentication'
					var theResult = thePair[1]; //holds the Authentication result as 'True' or 'False'
					
					if (theName.toLowerCase()=="authenticated") {
						if (theResult.toLowerCase()=="true") {
							isAuthenticated=true;
						}
					}else if (theName.toLowerCase()=="time") {
						timeAuthenticated=theResult;
					}else if (theName.toLowerCase()=="label") {
						label=theResult;
					}else if (theName.toLowerCase()=="errormess") {
						errMessage=theResult;
					}else if (theName.toLowerCase()=="errorcode") {
						errCode=theResult;
						//"1" - Stamp failed authentication
						//"2" - Workflow Task failed authentication
						//"3" - Not Workflow Task Member
						//"4" - Workflow Task failed to complete
						//"5" - Stamp associated with Workflow, form needs to be saved
						//"6" - Stamp would not complete
					}		
					
				}
			}
		}
		
		if (isAuthenticated == true && label.length > 0 && lblStamp!=null) {
			if (chk!=null) {
				chk.checked = true;
				lblStamp.innerHTML = label;
			}
		} else {
			if (chk!=null) {
				chk.checked = false;
			}		
			
			if (lblStamp!=null) {
				lblStamp.innerHTML = stampPrompt;
			}
			
			if (errCode==1 || errCode==2) {
				DisplayUserIDStampAuthManual(chk,formId);
			} else if (errCode==3 || errCode==4) {
				
				if (errMessage.length > 0) {
					DisplaySignErrorMessageText(errMessage);
				}
				
			} else if (errCode==5) {
				DisplaySignErrorMessage(chk);
			}
			
		}
	} else {
		// The check was unchecked
		
		DoUserStampUnchecked(formId,fieldId,templateId,pwd,lblStamp,chk);
		//if (chk!=null) {
		//		chk.checked = false;
		//}
		
		//lblStamp.innerHTML = stampPrompt;
	}	
}



function HideSecurityAuthForm() {
	if (document.getElementById('divSecurityAuthForm')!=null) {
		var div1 = document.getElementById('divSecurityAuthForm');
		div1.style.display="none";
			
		if (document.getElementById('AuthFormDescription')!=null) {
			var span = document.getElementById('AuthFormDescription');
			span.innerHTML="Enter your VisualVault password";
		}
		
		if (UserIDStamp_Checkbox!=null) {
			var chk=UserIDStamp_Checkbox;
			
			chk.checked=false;
		}
	}
}
function HideFormErrorMessage() {
	if (document.getElementById('divErrorMessageForm')!=null) {
		var div1 = document.getElementById('divErrorMessageForm');
		div1.style.display="none";
	}
}

function DisplaySignErrorMessage(chk) {
	if (document.getElementById('divErrorMessageForm')!=null) {
		var div1 = document.getElementById('divErrorMessageForm');
		
		if (document.getElementById('ErrorFormSubjectText')!=null) {
			document.getElementById('ErrorFormSubjectText').innerHTML = "Signature stamp is associated with a workflow task sequence."
		}
		
		if (document.getElementById('ErrorFormDescriptionText')!=null) {
			document.getElementById('ErrorFormDescriptionText').innerHTML = "Please Save your form before signing this signature stamp."	
		}
		
		SetSignErrorMessageLocation(div1);
		div1.style.display="block";
		UserIDStamp_Checkbox = null;
	}
}

function DisplaySignErrorMessageText(errMessage) {
	if (document.getElementById('divErrorMessageForm')!=null) {
		var div1 = document.getElementById('divErrorMessageForm');
		
		if (document.getElementById('ErrorFormSubjectText')!=null) {
			document.getElementById('ErrorFormSubjectText').innerHTML = "An error occurred signing signature stamp"
		}
		
		if (document.getElementById('ErrorFormDescriptionText')!=null) {
			document.getElementById('ErrorFormDescriptionText').innerHTML = errMessage	
		}
		
		SetSignErrorMessageLocation(div1);
		div1.style.display="block";
		UserIDStamp_Checkbox = null;
	}
}

function DisplayUserIDStampAuthManual(chk,formId) {
	if (document.getElementById('divSecurityAuthForm')!=null) {
		var div1 = document.getElementById('divSecurityAuthForm');
		div1.style.display="block";
		UserIDStamp_Checkbox = chk;
		UserIDStamp_FormID = formId;
	}
}

function SetSignErrorMessageLocation(div) {
	var Ver;
	var Hor;
	var mousex=UserIDStamp_mousex;
	var mousey=UserIDStamp_mousey;

	if (document.body) {
		//IE
		winW = document.body.clientWidth;
		winH = document.body.clientHeight;
	} else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
		winW = document.documentElement.clientWidth;
		winH = document.documentElement.clientHeight;
	} else if (self.innerWidth) {
		//Firefox
		winW = self.innerWidth;
		winH = self.innerHeight;
	}

	var divWidth=div.clientWidth;
	var divHeight=div.clientHeight;
	
	var r_avail = winW - mousex;
	if (r_avail > mousex) {
		Hor="right";
	}else {
		Hor="left";
	}
	
	var b_avail = winH - mousey;
	if (b_avail > mousey) {
		Ver="below";
	} else {
		Ver="above";
	}

	if (Hor=="right") {
		div.style.left = mousex + "px";
	} else {
		div.style.left = (mousex - 400) + "px";
	}
	
	if (Ver=="above") {
		div.style.top = (mousey - 200) + "px";
	} else {
		div.style.top = mousey + "px";
	}

}

function SetPopupWindowLocation(div,mousex,mousey) {
	var Ver;
	var Hor;
	
	UserIDStamp_mousex = mousex;
	UserIDStamp_mousey = mousey;

	if (document.body) {
		//IE
		winW = document.body.clientWidth;
		winH = document.body.clientHeight;
	} else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
		winW = document.documentElement.clientWidth;
		winH = document.documentElement.clientHeight;
	} else if (self.innerWidth) {
		//Firefox
		winW = self.innerWidth;
		winH = self.innerHeight;
	}


	var divWidth=div.clientWidth;
	var divHeight=div.clientHeight;
	
	
	var r_avail = winW - mousex;
	if (r_avail > mousex) {
		Hor="right";
	}else {
		Hor="left";
	}
	
	var b_avail = winH - mousey;
	if (b_avail > mousey) {
		Ver="below";
	} else {
		Ver="above";
	}

	if (Hor=="right") {
		div.style.left = mousex + "px";
	} else {
		div.style.left = (mousex - 400) + "px";
	}
	
	if (Ver=="above") {
		div.style.top = (mousey - 200) + "px";
	} else {
		div.style.top = mousey + "px";
	}

}


//*********************************************************
//			UserIDStamp with Authentication
//*********************************************************

// The checkbox checked event will call this when the UserIDStamp
// requires Authentication to complete, finds the hidden DIV Tag
// and sets its display attribute to block, showing the password textbox
function DisplayUserIDStampAuth(formId,evt) {
	if (evt != null) {
		var chk;
		
		if(typeof(evt.target)!='undefined'){
			chk = evt.target;
		}else{
			if(typeof(evt.srcElement)!='undefined'){
				chk = evt.srcElement;
			}
		}
		if (chk != null) {
			// record click location
			UserIDStamp_mousex=LL_mousex;
			UserIDStamp_mousey=LL_mousey;
			
			if (chk.checked==true) {
				if (document.getElementById('divSecurityAuthForm')!=null) {
					var div1 = document.getElementById('divSecurityAuthForm');
					
					SetPopupWindowLocation(div1,LL_mousex,LL_mousey);
					
					div1.style.display="block";
					UserIDStamp_Checkbox = chk;
					UserIDStamp_FormID = formId;
				}			
			} else {
				var stampPrompt='';
				if (chk.parentNode.getAttribute('prompt')!=null) {
					if (chk.parentNode.getAttribute('prompt')!="") {
						stampPrompt=chk.parentNode.getAttribute('prompt');
					}
				}
				
				var lblStamp;
				//Loop thru childnodes to find checkbox label that will hold stamp info
				
				if (chk.parentNode.previousSibling!=null) {
					lblStamp = chk.parentNode.previousSibling;
				} else if (chk.parentNode.nextSibling!=null) {
					lblStamp = chk.parentNode.nextSibling;
				}
				
				/*
				if (chk.parentNode.parentNode.nodeName.toLowerCase()=='td') {
					var sibling = chk.parentNode.parentNode.firstChild;
					
					do {
						if (sibling.nodeName.toLowerCase()!='span') {
							sibling=sibling.nextSibling;
						}else if (sibling.hasChildNodes()==true){
							if (sibling.firstChild.nodeName.toLowerCase()=='input'){
								//This is the span tag holding UserIDStamp checkbox
								sibling=sibling.nextSibling;
								
							}else if(sibling.firstChild.nodeType==3){
								//This is the span tag holding UserIDStamp label
								lblStamp = sibling;
								sibling=sibling.nextSibling;
							}else{
								sibling=sibling.nextSibling;
							}
						}else{
							sibling=sibling.nextSibling;
						}
					} while (sibling!=null);
				}
				*/
				
				chk.checked=false;
				if (lblStamp!=null) {
					lblStamp.innerHTML=stampPrompt;
				}				
			}
		}
	}
}

// The Submit button will call this event when clicked, gathers the password
// and calls the VisualVault page to have the user Authenticated. If
// successfull the label will be updated, the checkbox will be checked, password cleared
// from the textbox and the DIV Tag will be hidden
function CompleteUserIDStampAuth(evt) {
	if (evt != null) {
		var el;
		
		if(typeof(evt.target)!='undefined'){
			el = evt.target;
		}else{
			if(typeof(evt.srcElement)!='undefined'){
				el = evt.srcElement;
			}
		}
		if (el != null) {
			DoUserIDStampAuth(el);
		}
	}
}

// responseText = Response from the server when we try to sign the signature stamp
function DoUserIDStampAuth(btn,responseText) {
	var lblStamp;
	var chk;
	var div1;
	var txtPasswd;
	var result='';
	var isAuthenticated=false; //holds the Authentication result as 'Authenticated' or 'Failed'
	var timeAuthenticated='';
	var label='';
	var pwd='';
	var fieldId='';
	var formId='';
	var templateId='';
	var stampPrompt='';
	var errCode='0';
	var errMessage=''
	
	//if responseText is null then set to an empty string
	if (responseText == undefined){
		responseText = '';
	}
	
	if (document.getElementById('divAuthForm_Row2')!=null) {
		var divRow2=document.getElementById('divAuthForm_Row2');
		if (divRow2.childNodes.length > 0) {
			var i=0;
			var found=false;
			
			do {
				var child = divRow2.childNodes[i];
				if (child.nodeName.toLowerCase() == 'input') {
					txtPasswd = child;
					pwd=txtPasswd.value;
					found=true;
				}	
				i++;
			} while (i<divRow2.childNodes.length && found==false);		
		}
	}
	
	
	if (UserIDStamp_Checkbox!=null) {
		chk=UserIDStamp_Checkbox;
		formId = UserIDStamp_FormID;
		
		
		if (chk.parentNode.getAttribute('prompt')!=null) {
			if (chk.parentNode.getAttribute('prompt')!="") {
				stampPrompt=chk.parentNode.getAttribute('prompt');
			}
		}
		
		if (chk.parentNode.getAttribute('vvfieldvalueid')!=null) {
			if (chk.parentNode.getAttribute('vvfieldvalueid')!="") {
				fieldId=chk.parentNode.getAttribute('vvfieldvalueid');
			}
		}
				
		if (chk.parentNode.getAttribute('vvtemplateid')!=null) {
			if (chk.parentNode.getAttribute('vvtemplateid')!="") {
				templateId=chk.parentNode.getAttribute('vvtemplateid');
			}
		}
		
		if (chk.parentNode.previousSibling!=null) {
			lblStamp = chk.parentNode.previousSibling;
		} else if (chk.parentNode.nextSibling!=null) {
			lblStamp = chk.parentNode.nextSibling;
		}

		/*
		//Loop thru childnodes to find checkbox label that will hold stamp info
		if (chk.parentNode.parentNode.nodeName.toLowerCase()=='td') {
			var sibling = chk.parentNode.parentNode.firstChild;
			
			do {
				if (sibling.nodeName.toLowerCase()!='span') {
					sibling=sibling.nextSibling;
				}else if (sibling.hasChildNodes()==true){
					if (sibling.firstChild.nodeName.toLowerCase()=='input'){
						//This is the span tag holding UserIDStamp checkbox
						//chk=sibling.firstChild;
						sibling=sibling.nextSibling;
						
					}else if(sibling.firstChild.nodeType==3){
						//This is the span tag holding UserIDStamp label
						lblStamp = sibling;
						sibling=sibling.nextSibling;
					}else{
						sibling=sibling.nextSibling;
					}
				}else{
					sibling=sibling.nextSibling;
				}
			} while (sibling!=null);
		}
		*/
	}
	
	//*******************************************************************

	if (responseText.length == 0){
		DoAuthenticateUserIDStamp(formId,fieldId,templateId,pwd,lblStamp,btn,'DoUserIDStampAuth');
	}
	
	//response text comes back from the server after calling DoAuthenticateUserIDStamp
	//because  DoAuthenticateUserIDStamp makes an asynchronous call to the server, when the xmlHTTP call to the server
	//is complete then DoAuthenticateUserIDStamp calls this function again and passes in responseText
	
	var result = responseText;
	
	
	// response will be in the form of 'authenticated'='True'~'time'='1/1/2000#09:00:00'~'label'='user.name 1/1/2000#09:00:00'
	if (result.length>0) {
		var respgrps = result.split('~');

		//gather responses
		for(var a=0;a<respgrps.length;a++){
			var thePairHldr = respgrps[a];
			var thePair = thePairHldr.split('=');

			if (thePair.length == 2) {
				var theName = thePair[0]; //holds 'Authentication'
				var theResult = thePair[1]; //holds the Authentication result as 'True' or 'False'
				
				if (theName.toLowerCase()=="authenticated") {
					if (theResult.toLowerCase()=="true") {
						isAuthenticated=true;
					}
				}else if (theName.toLowerCase()=="time") {
					timeAuthenticated=theResult;
				}else if (theName.toLowerCase()=="label") {
					label=theResult;
				}else if (theName.toLowerCase()=="errormess") {
					errMessage=theResult;
				}else if (theName.toLowerCase()=="errorcode") {
					errCode=theResult;
					//"1" - Stamp failed authentication
					//"2" - Workflow Task failed authentication
					//"3" - Not Workflow Task Member
					//"4" - Workflow Task failed to complete
					//"5" - Stamp associated with Workflow, form needs to be saved
					//"6" - Stamp would not complete
				}					
			}
		}
	}
	
	//********************************************************************
	if (txtPasswd!=null) {
		txtPasswd.value = "";
	}
	
	
	if (isAuthenticated == true && label.length > 0) {

		
		if (chk!=null) {
			chk.checked = true;
			chk.parentNode.parentNode.setAttribute('stamp',label);
		}
		
		if (lblStamp!=null) {
			lblStamp.innerHTML = label;
		}
		
		if (document.getElementById('AuthFormDescription')!=null) {
			var span = document.getElementById('AuthFormDescription');
			span.innerHTML="Enter your VisualVault password";
		}
		
		if (document.getElementById('divSecurityAuthForm')!=null) {
			var div1 = document.getElementById('divSecurityAuthForm');
			div1.style.display="none";
		}

	} else {		
		if (chk!=null) {
			chk.checked = false;
		}
		
		if (lblStamp!=null) {
			lblStamp.innerHTML = stampPrompt;
		}
		
		if (errCode=='1' || errCode=='2') {
			if (document.getElementById('AuthFormDescription')!=null) {
				var span = document.getElementById('AuthFormDescription');
				span.innerHTML="Authentication Failed, please enter your password.";
			}
		}else if (errCode==3 || errCode==4) {
			if (document.getElementById('divSecurityAuthForm')!=null) {
				var div1 = document.getElementById('divSecurityAuthForm');
				div1.style.display="none";
			}
			DisplaySignErrorMessageText(errMessage);
		} else if (errCode=='5') {
			if (document.getElementById('divSecurityAuthForm')!=null) {
				var div1 = document.getElementById('divSecurityAuthForm');
				div1.style.display="none";
			}
			DisplaySignErrorMessage(chk);
		}
	}
}



// Determines if user is able to sign a form signature stamp
//
// formID = ID of the form instance (GUID value) which holds the signature stamp
// fieldID = HTML Element ID of the form field (span tag)
// templateID = ID of the form instance's template (GUID)
// pwd = password user supplied for signing the signature stamp
// chk = HTML Element iD of the check box which makes up part of the signature stamp form control
// lblStamp HTML element which holds the form signature stamp
// element = HTML element we need to pass back to the calling function
// callerName = name of function which called DoAuthenticateUserIDStamp

function DoAuthenticateUserIDStamp(formId,fieldId,templateId,pwd,lblStamp,element,callerName) {
	var responseText=''; //we expect to get back a string containing comma separated name\value pairs
	var encodedData='';

	
	if (document.getElementById('__UserIDAuthentication') != null) {
		var pageURL = document.getElementById('__UserIDAuthentication').value;
		
		//append the formId to the querystring
		if (pageURL.indexOf("?")!=-1)
			pageURL += "formid=" + formId;
		else
			pageURL += "?formid=" + formId;
		
		//get the XmlHttpRequest object
		var xmlhttp = new GetXmlHttp();
		
		encodedData = "&userpw=" + pwd + "&fieldid=" + fieldId + "&templateid=" + templateId + "&ischecked=true";
		
		// send the data
		if (xmlhttp) {	
		
			xmlhttp.onreadystatechange = function (){
						
				if (xmlhttp && xmlhttp.readyState==1){
					//request sent to server..
				
					//display loading message...
					if (lblStamp)
					{					
						lblStamp.innerHTML = "Loading...<img src='./images/spinner.gif' border='0'>";			
					}
				} else if (xmlhttp && xmlhttp.readyState==4){
					//we got something back..	
					
					//clear loading message...
					if (lblStamp)
					{					
						lblStamp.innerHTML = "";			
					}						
					
					//get response from the server
					if (xmlhttp.status==200) {			
						responseText = xmlhttp.responseText;
						
						if (responseText.length > 0){
						
							//go back to the function that called this function 
							//when the response is received from the server
							if (callerName == 'DoUserIDStamp'){
								DoUserIDStamp(formId,element,responseText);
								return;
							}else{
								DoUserIDStampAuth(element,responseText);
								return;
							}
						}								
					}
					
					DoRecoverFromBadUserIDStampCall(element);
					
				}			
			}
			
			xmlhttp.open("POST",pageURL,true);
			//Prevent caching
			xmlhttp.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
			//make request appear as normal form post
			xmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded; charset=UTF-8');
			//encode the arguments and post to server	   
	   		xmlhttp.send(encodedData);
		}	

	}	
			
}

function DoUserStampUnchecked(formId,fieldId,templateId,pwd,lblStamp,element) {
	var responseText=''; //we expect to get back a string containing comma separated name\value pairs
	var encodedData='';

	
	if (document.getElementById('__UserIDAuthentication') != null) {
		var pageURL = document.getElementById('__UserIDAuthentication').value;
		
		//append the formId to the querystring
		if (pageURL.indexOf("?")!=-1)
			pageURL += "formid=" + formId;
		else
			pageURL += "?formid=" + formId;
		
		//get the XmlHttpRequest object
		var xmlhttp = new GetXmlHttp();
		
		encodedData = "&userpw=" + pwd + "&fieldid=" + fieldId + "&templateid=" + templateId + "&ischecked=false";
		
		// send the data
		if (xmlhttp) {	
		
			xmlhttp.onreadystatechange = function (){
						
				if (xmlhttp && xmlhttp.readyState==1){
					//request sent to server..
				
					//display loading message...
					if (lblStamp)
					{					
						lblStamp.innerHTML = "Loading...<img src='./images/spinner.gif' border='0'>";			
					}
				} else if (xmlhttp && xmlhttp.readyState==4){
					//we got something back..	
					
					//clear loading message...
					if (lblStamp)
					{					
						lblStamp.innerHTML = "";			
					}						
					

					if (UserIDStamp_Checkbox!=null) {
						chk = UserIDStamp_Checkbox;
						
						if (chk.parentNode.getAttribute('prompt')!=null) {
							if (chk.parentNode.getAttribute('prompt')!="") {
								stampPrompt=chk.parentNode.getAttribute('prompt');
							}
						}
						
						if (chk.parentNode.previousSibling!=null) {
							lblStamp = chk.parentNode.previousSibling;
						} else if (chk.parentNode.nextSibling!=null) {
							lblStamp = chk.parentNode.nextSibling;
						}
					}

					if (chk!=null) {
						chk.checked = false;
					}
					
					if (lblStamp!=null && stampPrompt.length > 0) {
						lblStamp.innerHTML = stampPrompt;
					}
				}			
			}
			
			xmlhttp.open("POST",pageURL,true);
			//Prevent caching
			xmlhttp.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
			//make request appear as normal form post
			xmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded; charset=UTF-8');
			//encode the arguments and post to server	   
	   		xmlhttp.send(encodedData);
		}	

	}	
			
}


function DoRecoverFromBadUserIDStampCall(element) {
	var stampPrompt = "";
	var	chk = null;
	var lblStamp = null;
	
	if (UserIDStamp_Checkbox!=null) {
		chk = UserIDStamp_Checkbox;
		
		if (chk.parentNode.getAttribute('prompt')!=null) {
			if (chk.parentNode.getAttribute('prompt')!="") {
				stampPrompt=chk.parentNode.getAttribute('prompt');
			}
		}
		
		if (chk.parentNode.previousSibling!=null) {
			lblStamp = chk.parentNode.previousSibling;
		} else if (chk.parentNode.nextSibling!=null) {
			lblStamp = chk.parentNode.nextSibling;
		}
	
		
	}

	if (chk!=null) {
		chk.checked = false;
	}
	
	if (lblStamp!=null && stampPrompt.length > 0) {
		lblStamp.innerHTML = stampPrompt;
	}
	
	DisplaySignErrorMessageText("A communication error has occurred, please try again");
}


function CheckForBackSpace(evt){
	if (evt != null) {
		var el;
		
		if(typeof(evt.target)!='undefined'){
			el = evt.target;
		}else{
			if(typeof(evt.srcElement)!='undefined'){
				el = evt.srcElement;
			}
		}
		if (el != null) {
			if (el.value == '') {
				el.value = ' ';
			}
		}
	}
}







//Dashboard resize variables
var FDResizeTimerID = 0;
var FDResizeTStart  = null;
var FDResizeStarted = false;



//Continue Dashboard resize timer
function UpdateFDResizeTimer(formClientID) {
	if (FDResizeStarted==true) {
		setFDResizeWidths(formClientID);
		FDResizeTimerID = setTimeout("UpdateFDResizeTimer('" + formClientID + "')", 500);  
   } else {
		FDResizeTimerID=null;
		UpdateCheckResizeDivTimer(formClientID);
   }	
}

//Determine if Dashboard timer needs to continue
function UpdateCheckResizeDivTimer(formClientID) {
	if (document.getElementById('__UltraWebGridMain')) 
	{ 
		var uwGridMain = document.getElementById('__UltraWebGridMain_' + formClientID).value;
		
		if (document.getElementById(uwGridMain)) {
			FDResizeStarted=true;
			FDResizeTimerID = setTimeout("UpdateFDResizeTimer('" + formClientID + "')", 500);  
		} else {
			FDResizeStarted=false;
			FDResizeDivTimerID = setTimeout("UpdateCheckResizeDivTimer('" + formClientID + "')", 500);  
		}		
	} else {
		FDResizeStarted=false;
		FDResizeDivTimerID = setTimeout("UpdateCheckResizeDivTimer('" + formClientID + "')", 500);  
	}		
}


//Start Dashboard resize timer
function StartFDResizeTimer(formClientID) {
   FDResizeStarted = true;
   FDResizeTimerID  = setTimeout("UpdateFDResizeTimer('" + formClientID +  "')", 500);
   setFDResizeWidths(formClientID);
}

//Determines when to run the routine that actually sets the height and width of the grid
function setFDResizeWidths(formClientID) {	
	var browser=getBrowser();
	if (browser.toLowerCase()=="ie") {
		//If IE go ahead and run sizing routine
		SetHeightOnUltraWebGrid(formClientID);
		
		//if (igtbl_getGridById != null) {
		//	var uwGrid = document.getElementById('__UltraWebGridIDClientID').value;
		//	var grid=igtbl_getGridById(uwGrid);
		//	if (grid != null) {
		//		grid.alignStatMargins();
		//	}
		//}
		//var grid=igtbl_getGridById(document.getElementById('__UltraWebGridIDClientID').value;);
		//grid.alignStatMargins();

	} else {
		//When in Firefox we set a mark on the grid on first iteration and set sizes on second iteration
		var uwGridMain = document.getElementById('__UltraWebGridMain_' + formClientID).value;
		
		if (document.getElementById(uwGridMain) != null) 
		{
			var grid=document.getElementById(uwGridMain);
			var hset=grid.getAttribute("heightset");
			if (hset==null) {
				grid.setAttribute("heightset","0");
			} else {
				var cnt = parseInt(hset);
				if (!isNaN(cnt)) 
				{
					if (cnt==0) 
					{	
						//Tell grid to resize itself so that grid will reset itself after postback in Firefox
						igtbl_onBodyResize();
						
						cnt = 1;
						grid.setAttribute("heightset",cnt);
					} else if (cnt==1)
					{
						//Run grid resizing
						SetHeightOnUltraWebGrid(formClientID);
						//igtbl_onBodyResize();
						
					}
				}
			}		
		} else {
			//This is the clue to whether the FormDashboard is hosted on a custom page
			var IsMenuVisible = false;
			if (document.getElementById('pnlMenu')) {
				IsMenuVisible = true;
			}
			
			var IsTabVisible = false;
			if (document.getElementById('pnlTabControl')) {
				IsTabVisible = true;
			}
			
			if (IsMenuVisible == true && IsTabVisible == true && TurnCustomPageScrollBarOn == true) {
				if (document.body) {
					document.body.style.overflow = "auto";
				}	
			}

		}
		
	}
	//Add onContextMenu attribute to all the rows of the grid
	AddContextMenuToUltraWebGrid(formClientID);
} 

/*
**************************************************************************
******	There are five hidden textfields on the page that hold the names of
******	the UltrawebGrids internal Div and Table names
******
******	__UltraWebGridIDClientID - The ClientID of the UltraWegGrid
******	__UltraWebGridIDUniqueID - The UniqueID of the UltraWegGrid
******	__UltraWebGridMain - Outer table of entire grid
******	__UltraWebGridDiv - Div tag surrounding entire body of grid
******	__UltraWebGridHDiv - Div tag surrounding entire header of grid
******	__UltraWebGridMc - Table cell surround entire body of grid
******	__UltraWebGridTableBodyID - Table surrounding rows of grid
******	
**************************************************************************
*/
function SetHeightOnUltraWebGrid(formClientID) 
{
	

	var uwInnerTableWidth = 10000;
		
	if (document.getElementById('__UltraWebGridTableBodyID_' + formClientID) != null) {
		
		var uwGridBody = document.getElementById('__UltraWebGridTableBodyID_' + formClientID).value;
			
		var gridBody = document.getElementById(uwGridBody);
		if (gridBody != null) {
			if (!isNaN(parseInt(gridBody.style.width))) {
				uwInnerTableWidth = parseInt(gridBody.style.width);
			}			
		}

			
		var uwGridMain = document.getElementById('__UltraWebGridMain_' + formClientID).value;
		

		var uwGridDiv = document.getElementById('__UltraWebGridDiv_' + formClientID).value;
		var uwGridMc = document.getElementById('__UltraWebGridMc_' + formClientID).value;
		var portalElement = document.getElementById('__PortalColumnCount');
		
		if (portalElement != null) {
			portalCount = document.getElementById('__PortalColumnCount').value;
		} else {
			portalCount = null;
		}

		if (document.getElementById(uwGridMain) != null && document.getElementById(uwGridDiv) != null && document.getElementById(uwGridMc) != null) {
			var SetHeight=0;
			var browser=getBrowser();
	
			//Get current window demensions based on browser type
			if (browser.toLowerCase()=="firefox") {
				winW = self.innerWidth - 5;
				winH = self.innerHeight;
			} else {
				if (document.body) {
					//IE
					winW = document.body.clientWidth;
					winH = document.body.clientHeight;
				} else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
					winW = document.documentElement.clientWidth;
					winH = document.documentElement.clientHeight;
				} else if (self.innerWidth) {
					//Firefox
					winW = self.innerWidth;
					winH = self.innerHeight;
				}				
			}
			
			//This is the clue to whether the FormDashboard is hosted on a custom page
			var IsMenuVisible = false;
			if (document.getElementById('pnlMenu'))
				IsMenuVisible = true;
				
			var IsTabVisible = false;
			if (document.getElementById('pnlTabControl'))
				IsTabVisible = true;		
				
			//compute width of grid
			if (portalCount != null) {
			
				if (parseInt(portalCount) == 1) {
					totalWidth = parseInt(winW - 35);
				} else if (parseInt(portalCount) == 2) {
					totalWidth = parseInt(winW * .45);
					//totalWidth = parseInt(totalWidth - 35);
				} else if (parseInt(portalCount) == 3) {
					totalWidth = parseInt(winW * .33);
					//totalWidth = parseInt(totalWidth - 35);
				}
						
			} else {
				totalWidth = parseInt(winW - 35);			
			}
			
			if (IsMenuVisible == true && IsTabVisible == true && TurnCustomPageScrollBarOn == true) {
				totalWidth = totalWidth - 15;
				if (document.body) {
					document.body.style.overflow = "auto";
				}	
			}

			
			//set outer table widths where the vertical scroll bar will be
			document.getElementById(uwGridMain).style.width=totalWidth + 17;
			document.getElementById(uwGridMc).style.width=totalWidth + 17;
		
			//set the internal table width that will expand the columns to the screen width, if necessary
			setFDGridWidths(totalWidth, formClientID);
			
			


			if (portalCount == null) {
				//set the height of the grid
				//computer the height of the grid
				if (document.getElementById('divMenuHeader') != null) {
					menuHeaderHeight = document.getElementById('divMenuHeader').offsetHeight;
					if (menuHeaderHeight == null) {
						menuHeaderHeight = 0;
					}
				} else {
					menuHeaderHeight = 30;
				}
				
				if (document.getElementById('divMeasure') != null) {
					measureHeight = document.getElementById('divMeasure').offsetHeight;
					if (measureHeight == null) {
						measureHeight = 0;
					}
				} else {
					measureHeight = 0;
				}
				

				
				//compute final grid height
				SetHeight=winH - menuHeaderHeight - measureHeight - 110;
				
				if (IsMenuVisible == true && IsTabVisible == true)
					SetHeight = SetHeight - 40;

				if (SetHeight < 100)
					SetHeight=100;
				
				var gridbody = document.getElementById(uwGridBody);//.style.height = "0px";
				if (gridbody != null) {
					gridbody.style.height = "0%";				
				}				
					
				document.getElementById(uwGridMain).style.height = SetHeight;
				document.getElementById(uwGridDiv).style.height = SetHeight;
			} else {
				document.getElementById(uwGridMain).style.height = "";
				document.getElementById(uwGridDiv).style.height = "";
			}
		} 
	}
}


//Sets the grids internal table to the screen width if necessary
function setFDGridWidths(gridWidth, formClientID)
{
	var uwGridHDiv = document.getElementById('__UltraWebGridHDiv_' + formClientID).value;
	if (document.getElementById(uwGridHDiv) != null)
	{
		if (document.getElementById(uwGridHDiv).firstChild != null)
		{
			if (document.getElementById(uwGridHDiv).firstChild.firstChild != null)
			{
				//set scope attribute on all columns
				setColumnAttribute(uwGridHDiv);
				
				//computes the size of all the columns to determine if necessary to expand table
				var childWidths = getChildWidths(document.getElementById(uwGridHDiv).firstChild.firstChild);
				
				if (!isNaN(parseInt(document.getElementById(uwGridHDiv).firstChild.style.width))) 
				{
					//gets the current table width
					var uwTableWidth = parseInt(document.getElementById(uwGridHDiv).firstChild.style.width);
					
					//If current column widths is less then the screen width then expand table
					if (childWidths<gridWidth)
					{
						//only set table width if not already set to avoid flash
						if (uwTableWidth!=gridWidth)
						{
							document.getElementById(uwGridHDiv).firstChild.style.width=gridWidth;
							
							var browser=getBrowser();
							if (browser.toLowerCase()=="ie") {
								var foundElement = false;
								var colHeader = document.getElementById(uwGridHDiv).firstChild.firstChild;
								if (colHeader.nextSibling != null) {
									var el = colHeader.nextSibling;
									if (el.nodeName.toLowerCase() != "thead") {
										do {
											if (el.nodeName.toLowerCase() == "thead") {
												foundElement = true;
											} else {
												el = el.nextSibling;
											}											
										}while (el != null && foundElement == false);									
									} 
									if (el != null) {
										if (el.nodeName.toLowerCase() == "thead") {
											var cols = el.getElementsByTagName("th");
											for (var i = 0; i < cols.length; i++) { 
												cols[i].width = "";
												if (!cols[i].getAttribute("scope")) {
													cols[i].setAttribute("scope","col");
												}
											}
										}
									}
								}
							
							}
							//if(typeof(igtbl_getGridById)!="undefined"){
							//	var uwGrid = document.getElementById('__UltraWebGridIDClientID').value;
							//	var grid=igtbl_getGridById(uwGrid);
							//	if (grid != null) {
							//		grid.alignStatMargins();
							//	}
							//}

							
							//tell grid to expand columns to width of table
							igtbl_onBodyResize();
						}

					}
				}
			}
		}
	}
}

//Calculates the total width of all the columns
function getChildWidths(parent)
{
	var totalWidths = 0;

	for (var i=0;i<parent.childNodes.length;i++) 
	{
		var child = parent.childNodes[i];
		
		if (child.nodeName.toLowerCase() == 'col')
		{
			if (child.getAttribute("width")!=null) 
			{
				if (!isNaN(parseInt(child.getAttribute("width")))) 
				{
					totalWidths+=parseInt(child.getAttribute("width"));
				}
			}
		}
	}
	
	return totalWidths;
}

//set scope attribute on all columns
function setColumnAttribute(uwGridHDiv) {

	var colHeader = document.getElementById(uwGridHDiv).firstChild.firstChild;
	if (colHeader.nextSibling != null) {
		var el = colHeader.nextSibling;
		if (el.nodeName.toLowerCase() != "thead") {
			do {
				if (el.nodeName.toLowerCase() == "thead") {
					foundElement = true;
				} else {
					el = el.nextSibling;
				}											
			}while (el != null && foundElement == false);									
		} 
		if (el != null) {
			if (el.nodeName.toLowerCase() == "thead") {
				var cols = el.getElementsByTagName("th");
				for (var i = 0; i < cols.length; i++) { 
					if (!cols[i].getAttribute("scope")) {
						cols[i].setAttribute("scope","col");
					}
				}
			}
		}
	}


}

//Adds the onContextMenu attribute to all the rows in the grid
function AddContextMenuToUltraWebGrid(formClientID) 
{
	var uwgClientID = '';
	var uwgTableID = '';

	if (document.getElementById("__UltraWebGridIDClientID_" + formClientID)) {
		uwgClientID = document.getElementById("__UltraWebGridIDClientID_" + formClientID).value;
		
		if (document.getElementById("__UltraWebGridTableBodyID_" + formClientID)) {
			uwgTableID = document.getElementById("__UltraWebGridTableBodyID_" + formClientID).value;
			
			if (document.getElementById(uwgTableID)) {
				var uwgTable = document.getElementById(uwgTableID);
				
				if (uwgTable.lastChild) {
					var tbody = uwgTable.lastChild;

					if (tbody.nodeName=="TBODY") {
						if (tbody.hasChildNodes()) {
							var rows = tbody.childNodes;
							
							//Loop through all the rows of the grid
							for (var i = 0; i < rows.length; i++){
							
								var row = rows[i];
								var rowid = row.id;
								if (!row.getAttribute("oncontextmenu")) {
									row.setAttribute("oncontextmenu","UltraWebGrid1_MouseDownHandler('" + uwgClientID + "', '" + rowid + "', '2', '" + formClientID + "'); return false;");
								}
								
								setRowScopeAttribute(row);
							}
						}
					}
				}
			}
		}
	}
}


function setRowScopeAttribute(rowElement) {
	var cells = rowElement.childNodes;
	
	//Loop through the cells of the row looking for the first visible cell
	for (var i = 0; i < cells.length; i++) {
		var cell = cells[i];
		
		//test for being visible
		if (cell.style.display != "none") {
			if (!cell.getAttribute("scope")) {
				cell.setAttribute("scope","row");
			}
			
			break;
		}
	}
}


//Runs before conextmenu is drawn to retrieve datakey from row of grid
function UltraWebGrid1_MouseDownHandler(gridName, id, button, formClientID){
	var keyid = '';
	var uwgClientID = '';
	var uwgUniqueID = '';

	document.oncontextmenu = function () {return false;};
	if (button==2) {

		if (document.getElementById("__UltraWebGridIDClientID_" + formClientID)) {
			
			uwgClientID = document.getElementById("__UltraWebGridIDClientID_" + formClientID).value;
			if (document.getElementById("__UltraWebGridIDUniqueID_" + formClientID)) {
				
				uwgUniqueID = document.getElementById("__UltraWebGridIDUniqueID_" + formClientID).value;
				
				var parts = id.split("_");
				if (parts.length>=3) {
					var row1 = igtbl_getRowById(id);
					if (row1) {
						if (row1.DataKey) {
						
							keyid=row1.DataKey;
							loadTheFormContextMenu(keyid,null,uwgClientID,uwgUniqueID,'divScroll','false','true');
							event.returnValue=false;
						}
					}
				}
			}
		}
	}
}

//Runs before the contextmenu is drawn in IE to retrieve the datakey of the row in the grid
function UltraWebGrid1_MouseDownHandler1(gridName, id, button){
	var keyid = '';
	var uwgClientID = '';
	var uwgUniqueID = '';
	
	
	formClientId = gridName.replace(/x/g,'_');
	//alert(formClientId);
	document.oncontextmenu = function () {return false;};
		
	if (button==2) {
		
		if (document.getElementById("__UltraWebGridIDClientID_" + formClientId)) {
			
			uwgClientID = document.getElementById("__UltraWebGridIDClientID_" + formClientId).value;
			if (document.getElementById("__UltraWebGridIDUniqueID_" + formClientId)) {
				
				uwgUniqueID = document.getElementById("__UltraWebGridIDUniqueID_" + formClientId).value;
				
				var parts = id.split("_");
				if (parts.length>=3) {
					var row1 = igtbl_getRowById(id);
					if (row1) {
						if (row1.DataKey) {
							keyid=row1.DataKey;
							loadTheFormContextMenu(keyid,null,uwgClientID,uwgUniqueID,'divScroll','false','true');							
							event.returnValue=false;
							//event.cancelBubble=true;
						}
					}
				}				
			}
		}
	}
	else{
		
	}
}


//Determines the mouse coordinates then calls routine to draw ContextMenu
function loadTheFormContextMenu(item,evt,clientID,uniqueID,loadingID,bPopupAnother,bShowAllItems)
{	
	clientIDToUpdate = clientID;
	uniqueIDToRender = uniqueID;
	clientIDLoadingMsg = loadingID;	

	try{
		var folderID = '';
		
		contextMenuSelectedItem = null; //reset selected item
		contextMenuType = 'form'; 
					
		if (document.getElementById('__selectedDocID')){
			document.getElementById('__selectedDocID').value=item;				
		}
		
		contextMenuData = 'form,' + item + ',' + bPopupAnother + ',' + bShowAllItems; // + ',' + folderID;
	
		if (LL_mousex!=null){
			contextMenuX = LL_mousex;
		} else {
			//evt = (evt == null) ? window.event : evt;
			//contextMenuX = evt.pageX ? evt.pageX : evt.x;
			contextMenuX = 100;		
		}
		
		if (LL_mousey!=null){
			contextMenuY = LL_mousey;
		} else {
			//contextMenuY = evt.pageY ? evt.pageY : evt.y;
			contextMenuY = 100;
		}

		_ctl0_contextMenuCallBack.DomElement.style.left = contextMenuX + 'px'; 
		_ctl0_contextMenuCallBack.DomElement.style.top = (contextMenuY - _ctl0_contextMenuCallBack.DomElement.offsetHeight) + 'px'; 
		_ctl0_contextMenuCallBack.Callback(contextMenuData); 
 
		return false; 	
		
		}
	catch(e){
		alert(e);
	}	
}

function CheckDeleteColumn() {
 try {
	var form = document.forms[0];
 	var args;
 	var argLength;
 	
 	for (var i=0;i<form.elements.length;i++) {
		var e = form.elements[i];
		
		if (e.type=='checkbox') {
			if (e.id != null) { 
				cbName = e.id;
				
				if (cbName.indexOf('cbDelete') > -1) {
					e.checked = document.getElementById('cbDeleteCheckAll').checked;
				}
			}
		}
	}

 }
 catch(e) {
 }
}

function CheckStamps(StampCheckboxID,GroupName) {
 try {
	var realGroupName = GroupName.substr(13);
	var form = document.forms[0];
 	var args;
 	var argLength;
 	
 	for (var i=0;i<form.elements.length;i++) {
		var e = form.elements[i];
		
		if (e.type=='checkbox') {
			if (e.getAttribute("Name") != null) { 
				cbName = e.getAttribute("Name");
				args = cbName.split(':');
				argLength=args.length;
				
				if (args[argLength - 1].indexOf('cbUserIDStamp') != -1) {
					if (e.parentNode.nodeName.toLowerCase() == "span") {
						var parent = e.parentNode;
						var stampid = parent.getAttribute("stampid");
						stampid = stampid.replace(" ", "");
						if (stampid == realGroupName) {
							e.checked = document.getElementById(StampCheckboxID).checked;
						}
					}
				}
			}
		}
	}
 }
 catch(e) {
 }
}

function HideFormHTMLMessage(id) {
	var el = document.getElementById(id);
	if (el != null)
		el.style.display = "none";
}

function SetWaitToCenterOfScreen(el) {
	CenterDialogWindow(el);
}

function DisplayWait() {
	var wait = document.getElementById("divDisplayWait");

	//display loading message...
	if (wait != null)
	{
		wait.style.display = "block";	
		var innerDiv = document.getElementById("divDisplayWaitContent");	
		innerDiv.innerHTML = "Loading...<img src='./images/spinner.gif' border='0'>";			
		SetWaitToCenterOfScreen(wait);	
	}
}

function CenterDialogWindow(dialog) {
	var divDialog = null;
	
	if (typeof dialog == "string") {
		divDialog = document.getElementById(dialog);
	} else {
		divDialog = dialog;
	}
	
	if (divDialog != null) {
		var scrollX = 0;
		var scrollY = 0;

		if (document.all)
		{
			if (!document.documentElement.scrollLeft)
				scrollX = document.body.scrollLeft;
			else
				scrollX = document.documentElement.scrollLeft;
				
			if (!document.documentElement.scrollTop)
				scrollY = document.body.scrollTop;
			else
				scrollY = document.documentElement.scrollTop;
		}   
		else
		{
			scrollX = window.pageXOffset;
			scrollY = window.pageYOffset;
		}
		
		
		var winW = 0;
		var winH = 0;

		
		if( typeof( window.innerWidth ) == 'number' ) {
			//Non-IE
			winW = window.innerWidth;
			winH = window.innerHeight;
			
			var H = winH / 2;
			var W = winW / 2;
			
			var HalfDialog_H = divDialog.offsetHeight;
			var HalfDialog_W = divDialog.offsetWidth / 2;
			
			
		} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
			//IE 6+ in 'standards compliant mode'
			winW = document.documentElement.clientWidth;
			winH = document.documentElement.clientHeight;
			
			var H = winH / 2;
			var W = winW / 2;
			
			var HalfDialog_H = divDialog.offsetHeight / 2;
			var HalfDialog_W = divDialog.offsetWidth / 2;
			

		} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
			//IE 4 compatible
			winW = document.body.clientWidth;
			winH = document.body.clientHeight;
			
			var H = winH / 2;
			var W = winW / 2;
			
			var HalfDialog_H = divDialog.offsetHeight / 2;
			var HalfDialog_W = divDialog.offsetWidth / 2;
			
		}
	
		divDialog.style.top = (H - HalfDialog_H) + scrollY;
		divDialog.style.left = (W - HalfDialog_W) + scrollX;
	

	}
}


function DoCenterTaskWindow(elName) {

	setTimeout("CenterDialogWindow('Form_HTMLMessage_divHTMLMessageForm')", 250);
	
	var divTask = document.getElementById(elName);
	if (divTask != null) {
	
		var scrollX = 0;
		var scrollY = 0;

		if (document.all)
		{
			if (!document.documentElement.scrollLeft)
				scrollX = document.body.scrollLeft;
			else
				scrollX = document.documentElement.scrollLeft;
				
			if (!document.documentElement.scrollTop)
				scrollY = document.body.scrollTop;
			else
				scrollY = document.documentElement.scrollTop;
		}   
		else
		{
			scrollX = window.pageXOffset;
			scrollY = window.pageYOffset;
		}
		
		
		var winW = 0;
		var winH = 0;

		if( typeof( window.innerWidth ) == 'number' ) {
			//Non-IE
			winW = window.innerWidth;
			winH = window.innerHeight;
		} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
			//IE 6+ in 'standards compliant mode'
			winW = document.documentElement.clientWidth;
			winH = document.documentElement.clientHeight;
		} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
			//IE 4 compatible
			winW = document.body.clientWidth;
			winH = document.body.clientHeight;
		}
		var H = winH / 2;
		var W = winW / 2;
		
		divTask.style.display = "block";
		divTask.style.top = (H - (divTask.offsetHeight / 2)) + scrollY;
		divTask.style.left = (W - (divTask.offsetWidth / 2)) + scrollX;
		
		//window.status="H=" + H + " W=" + W + " scrollY=" + scrollY + " scrollX=" + scrollX + " Width=" + divTask.offsetWidth + " Height=" + divTask.offsetHeight;

	}

}


function DoCheckForEnterKey(e) {	
	if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
		var ButtonFound = false;
			
		//Determine if save button is available
		if (IsNavBarVisible()) {
			if (IsSaveButtonVisible()) {
				ButtonFound = true;
				ClickSaveButton();
			}
		} 
		
		if (ButtonFound == false) {
			//Get FormButtons collection
			var AllFormButtons = GetFormButtons();
			
			//If any are marked as doing a save then click that button
			for(var i=0;i<AllFormButtons.length;i++){
				if (AllFormButtons[i].getAttribute('save') == 'true') {
					ButtonFound = true;
					var formButton = AllFormButtons[i];
					formButton.click();
					break;
				}
			}
		}
		e.returnValue = false;
		return false;
	} else {
		return true;
	}
}

function DoSomeAlert(value) {
	alert(value);
}

function SelectedOperator() {
		var value = "";
		var OperatorID = document.getElementById('OperatorId').value;
		var elOperator = document.getElementById(OperatorID);
				
		if (elOperator != null) {
			var op = elOperator.value;
			
			switch (op) {
				case "1":
					value = "= ";
					break;
				case "2":
					value = "<> ";
					break;
				case "3":
					value = "> ";
					break;
				case "4":
					value = ">= ";
					break;
				case "5":
					value = "< ";
					break;
				case "6":
					value = "<= ";
					break;
				case "7":
					value = "like 'CRITERIA' + '%' ";
					break;
				case "8":
					value = "not like 'CRITERIA' + '%' ";
					break;
				case "9":
					value = "like '%' + 'CRITERIA' ";
					break;
				case "10":
					value = "not like '%' + 'CRITERIA' ";
					break;
				case "11":
					value = "like '%' + 'CRITERIA' + '%' ";
					break;
				case "12":
					value = "not like '%' + 'CRITERIA' + '%' " ;
					break;
			}
			if (value != "") {
				//alert(value);
				InsertText(value);
			}
		}
		
		elOperator.value = '0';
	}

	function InsertField() {
		var SourceTypeId = document.getElementById('SourceTypeId').value;
		var elSourceType = document.getElementById(SourceTypeId);
		var FieldSelectorId = document.getElementById('FieldSelectorId').value;
		var elFieldSelector = document.getElementById(FieldSelectorId);
		
		
		if (elSourceType != null && elFieldSelector != null) {
			var sourcetype = elSourceType.value;
			var fieldname = elFieldSelector.value;
			//var source = "";
			
			switch (sourcetype) {
				case "0":
					//source = "Form";
					InsertText("{" + fieldname + "} ");
					break;
				case "1":
					//source = "Dashboard";
					InsertText("[" + fieldname + "] ");
					break;
			}
			
			//InsertText(" [" + source + "." + fieldname + "] ");
		}	
    }


	function InsertText(value) {
		var TextAreaID = document.getElementById('TextAreaId').value;
		var elTextArea = document.getElementById(TextAreaID);
		
		if (elTextArea != null) {
		
			if (typeof(document.selection) != 'undefined') {
				//IE support 
				elTextArea.focus(); 

				var sel = document.selection.createRange(); 
				sel.text = value; 
			
			} else {
				//Mozilla/Firefox/Netscape 7+ support 
				if (elTextArea.value.length == 0) {
					elTextArea.value += value;
				
				} else {
				
					var startPos = elTextArea.selectionStart; 
					var endPos = elTextArea.selectionEnd; 
					elTextArea.value = elTextArea.value.substring(0, startPos) + value + elTextArea.value.substring(endPos, elTextArea.value.length); 
	 			
				}
			}
		}
	}
	
	function ValidateFormDataFilter() {
		var TextAreaID = document.getElementById('TextAreaId').value;
		var elTextArea = document.getElementById(TextAreaID);
		
		if (elTextArea.value.indexOf("'CRITERIA'") != -1) {
			alert("One or more 'CRITERIA' phrases has not been supplied. Replace the phrase 'CRITERIA' with a value, like 'example'");
		} else {
			form.submit();
		}	
	}
