var isIE;
var isGecko;
var isSafari;
var isKonqueror;
var isOpera;
var isMozilla;
var webkitVersion;
function initBrowser(){
    var ua = navigator.userAgent.toLowerCase();
	isIE = ((ua.indexOf("msie") != -1) && (ua.indexOf("opera") == -1) && (ua.indexOf("webtv") == -1)); 
	isGecko = (ua.indexOf("gecko") != -1);
	isOpera= (ua.indexOf("opera") != -1);
    isSafari = (ua.indexOf("safari") != -1);
    isKonqueror = (ua.indexOf("konqueror") != -1);
	isMozilla = (ua.indexOf("firefox") != -1);
    
	//TO findout Safari webkit version
	 webkitVersion = get_webkit_version();
	if (webkitVersion) {
	webkitVersion = webkitVersion["major"];
	} else {
	webkitVersion = null;
	}
}

function get_webkit_version() {
	try {
		var regex = new RegExp("\\(.*\\) AppleWebKit/(.*) \\((.*)");
		var matches = regex.exec(navigator.userAgent);
		if (matches) {
			var webkit_version = parse_webkit_version(matches[1]);    
		} 
		return {major: webkit_version['major'], minor: webkit_version['minor'], is_nightly: webkit_version['is_nightly']};
	} catch (e) {

	}
}

// webkit.org webkit detection scripts
function parse_webkit_version(version) {
	try {
		var bits = version.split(".");
		var is_nightly = (version[version.length - 1] == "+");
		if (is_nightly) {
			var minor = "+";
		} else {
			var minor = parseInt(bits[1]);
			// If minor is Not a Number (NaN) return an empty string
			if (isNaN(minor)) {
				minor = "";
			}
		}
		return {major: parseInt(bits[0]), minor: minor, is_nightly: is_nightly};
	} catch (e) {

	}
}



// VARIABLE DECLARATIONS

var digits = "0123456789";

// whitespace characters
var whitespace = " \t\n\r";

// decimal point character differs by language and culture
var decimalPointDelimiter = "."

// non-digit characters which are allowed in phone numbers
var phoneNumberDelimiters = "()- ";

// U.S. phone numbers have 10 digits. They are formatted as 123 456 7890 or (123) 456-7890.
var digitsInUSPhoneNumber = 10;

// non-digit characters which are allowed in ZIP Codes
var ZIPCodeDelimiters = "-";

// U.S. ZIP codes have 5 or 9 digits. They are formatted as 12345 or 12345-6789.
var digitsInZIPCode1 = 5
var digitsInZIPCode2 = 9

// CONSTANT STRING DECLARATIONS
// (grouped for ease of translation and localization)
// m is an abbreviation for "missing"
var mPrefix = "You did not enter a value into the "
var mSuffix = " field. This is a required field. Please enter it now."

// i is an abbreviation for "invalid"
var iZIPCode = " field must be a 5 or 9 digit U.S. ZIP Code (like 94043). Please reenter it now."
var iUSPhone = " field must be a 10 digit U.S. phone number (like 415 555 1212). Please reenter it now."
var iWorldPhone = " field must be a valid international phone number. Please reenter it now."
var iEmail = " field must be a valid email address (like foo@bar.com). Please reenter it now."
var iDateFormat = "The date field must be of proper format(like mm-dd-yyyy).  Please reenter it now."
var iInteger = " field must be a valid number.  Please reenter it now."
var iAlphabet = " field must be a valid word/sentence.  Please reenter it now."
var iAlphaNumeric = " field must contain valid alphaNumeric characters.  Please reenter it now."

// p is an abbreviation for "prompt"
var pEntryPrompt = "Please enter a "

// Global variable defaultEmptyOK defines default return value
// for many functions when they are passed the empty string.
// By default, they will return defaultEmptyOK.
//
// defaultEmptyOK is false, which means that by default,
// these functions will do "strict" validation.  Function
// isInteger, for example, will only return true if it is
// passed a string containing an integer; if it is passed
// the empty string, it will return false.
//
// You can change this default behavior globally (for all
// functions which use defaultEmptyOK) by changing the value
// of defaultEmptyOK.
//
// Most of these functions have an optional argument emptyOK
// which allows you to override the default behavior for
// the duration of a function call.
//
// This functionality is useful because it is possible to
// say "if the user puts anything in this field, it must
// be an integer (or a phone number, or a string, etc.),
// but it's OK to leave the field empty too."
// This is the case for fields which are optional but which
// must have a certain kind of content if filled in.
var defaultEmptyOK = false

// Check whether string s is empty.
function isEmpty(s)
{
   return ((s == null) || (s.length == 0))
}


// Returns true if string s is empty or
// whitespace characters only.
function isWhitespace (s)
{
   var i;

    // Is s empty?
    if (isEmpty(s)) return true;

    // Search through string's characters one by one
    // until we find a non-whitespace character.
    // When we do, return false; if we don't, return true.
    for (i = 0; i < s.length; i++)
    {
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (whitespace.indexOf(c) == -1) return false;
    }

    // All characters are whitespace.
    return true;
}

// Returns true if character c is a digit (0 .. 9).
function isDigit (c)
{
   return ((c >= "0") && (c <= "9"))
}


// isInteger (STRING s [, BOOLEAN emptyOK])
//
// Returns true if all characters in string s are numbers.
//
// Accepts non-signed integers only. Does not accept floating
// point, exponential notation, etc.
//
// We don't use parseInt because that would accept a string
// with trailing non-numeric characters.
//
// By default, returns defaultEmptyOK if s is empty.
// There is an optional second argument called emptyOK.
// emptyOK is used to override for a single function call
//      the default behavior which is specified globally by
//      defaultEmptyOK.
// If emptyOK is false (or any value other than true),
//      the function will return false if s is empty.
// If emptyOK is true, the function will return true if s is empty.
//
// EXAMPLE FUNCTION CALL:     RESULT:
// isInteger ("5")            true
// isInteger ("")             defaultEmptyOK
// isInteger ("-5")           false
// isInteger ("", true)       true
// isInteger ("", false)      false
// isInteger ("5", false)     true

function isInteger (s)
{
   var i;
    if (isEmpty(s))
       if (isInteger.arguments.length == 1) return defaultEmptyOK;
       else return (isInteger.arguments[1] == true);

    // Search through string's characters one by one
    // until we find a non-numeric character.
    // When we do, return false; if we don't, return true.
    for (i = 0; i < s.length; i++)
    {
        // Check that current character is number.
        var c = s.charAt(i);
        if (!isDigit(c)) return false;
    }

    // All characters are numbers.
    return true;
}

// isSignedInteger (STRING s [, BOOLEAN emptyOK])
//
// Returns true if all characters are numbers;
// first character is allowed to be + or - as well.
//
// Does not accept floating point, exponential notation, etc.
//
// We don't use parseInt because that would accept a string
// with trailing non-numeric characters.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.
//
// EXAMPLE FUNCTION CALL:          RESULT:
// isSignedInteger ("5")           true
// isSignedInteger ("")            defaultEmptyOK
// isSignedInteger ("-5")          true
// isSignedInteger ("+5")          true
// isSignedInteger ("", false)     false
// isSignedInteger ("", true)      true

function isSignedInteger (s)
{
   if (isEmpty(s))
       if (isSignedInteger.arguments.length == 1) return defaultEmptyOK;
       else return (isSignedInteger.arguments[1] == true);

    else {
        var startPos = 0;
        var secondArg = defaultEmptyOK;

        if (isSignedInteger.arguments.length > 1)
            secondArg = isSignedInteger.arguments[1];

        // skip leading + or -
        if ( (s.charAt(0) == "-") || (s.charAt(0) == "+") )
           startPos = 1;
        return (isInteger(s.substring(startPos, s.length), secondArg))
    }
}





// isEmail (STRING s [, BOOLEAN emptyOK])
//
// Email address must be of form a@b.c -- in other words:
// * there must be at least one character before the @
// * there must be at least one character before and after the .
// * the characters @ and . are both required
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function isEmail (s)
{   if (isEmpty(s))
       if (isEmail.arguments.length == 1) return defaultEmptyOK;
       else return (isEmail.arguments[1] == true);

    // is s whitespace?
    if (isWhitespace(s)) return false;

    // there must be >= 1 character before @, so we
    // start looking at character position 1
    // (i.e. second character)
    var i = 1;
    var sLength = s.length;

    // look for @
    while ((i < sLength) && (s.charAt(i) != "@"))
    { i++
    }

    if ((i >= sLength) || (s.charAt(i) != "@")) return false;
    else i += 2;

    // look for .
    while ((i < sLength) && (s.charAt(i) != "."))
    { i++
    }

    // there must be at least one character after the .
    if ((i >= sLength - 1) || (s.charAt(i) != ".")) return false;
    else return true;
}


// Notify user that contents of field theField are invalid.
// String s describes expected contents of theField.value.
// Put select theField, pu focus in it, and return false.

function warnInvalid (theField, fieldName, s)
{   theField.focus()
    theField.select()
    alert(fieldName+s)
    return false
}

// checkEmail (TEXTFIELD theField [, BOOLEAN emptyOK==false])
//
// Check that string theField.value is a valid Email.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function checkEmail (theField, fieldName, emptyOK)
{   if (checkEmail.arguments.length == 2) emptyOK = defaultEmptyOK;
    if ((emptyOK == true) && (isEmpty(theField.value))) return true;
    else if (!isEmail(theField.value, false))
       return warnInvalid (theField, fieldName, iEmail);
    else return true;
}

//Finds if the year is leap year
function isLeapYear(year) {

//   if (year % 4 == 0 && year % 100 != 0)
   if ( ( year % 4 == 0 && year % 100 != 0 ) || ( year % 4 == 0 && year % 100 == 0 && year % 400 == 0 ) ) {
    return true;
   }
   else {
    return false;
  }
}

// FORM VALIDATION ROUTINES using OO approach

/**
 * JavaScript Object representing a form field
 */
function FormField(field, label, focusField) {
    this.field = field;
    this.label = label;
    if (focusField != null) {
        this.focusField = focusField;
    } else {
        this.focusField = field;
    }
}

/**
*Fuction to validate the special characters
* Created By Sikkandar
*/
function validatespecialCharacters(data)
{
 
 var enemy="<a>a";
 var parts=enemy.split("a")
 
 for (k=0;k<data.length;k++)
 {  
/*  if(data.charAt(k)=='"')
  {	
   return true;
  } */
  for (l=0;l<parts.length;l++)
  {
  if (data.charAt(k)==parts[l])
   {
	
    return false;
   }
  }
 }
 return true;
}


/**
 * Function to validate the fields in a form. Internally,
 * calls the validateXyz methods.
 */
function validate(fields) {
    var bValid = true;
	//alert(fields);
    bValid = bValid && validateRequired(fields);	
    bValid = bValid && validateMaxLength(fields);
    bValid = bValid && validateIsInteger(fields);
    bValid = bValid && validateIsFloat(fields);
    return bValid;
}

/**
 * Function to validate the required fields in a form.
 * Borrowed and enhanced from the Struts validator file.
 * TODO: does not handle radio buttons correctly?
 */
function validateRequired(fields) {
    var bValid = true;
    var focusField = null;
	var val = null;
    var msg = validationMessages.required + '\n\n';
	var rad =false;
	var chk =false;
    var radfocus=null;
	var rdd =false;
    var rddfocus=null;
    var chkfocus=null;
	var isRadFocus=false;
	var isCheckFocus=false;
	var isRddFocus=false;
    var reorder= true;
	 var cValid=true;
	 var Criteria=validationMessages.Criteria;
	 var RowName=validationMessages.RowName;
	 var ColumnName=validationMessages.ColumnName;
	 var Choices=validationMessages.Choices;
	 var Files=validationMessages.Files;
	 var DisplayType=validationMessages.DisplayType;
    for (x in fields) {
        var formField = fields[x];
		//alert(" RE :"+formField.required +"  FEILD : "+formField.field +" : "+formField.label+" : "+formField.isEmailType);
        var field = formField.field;
		var mess =validationMessages.inValid;
		var messnum =validationMessages.inValidNumber;
		var yearofbirth =validationMessages.YearOfBirth;
		var EmailAddress = validationMessages.PrimaryEmailField;
		var AlternateEmailAddress = validationMessages.AlternateEmailField;
		var inValidPrimaryEmail = validationMessages.inValidPrimaryEmail;
		var inValidAlternateEmail= validationMessages.inValidAlternateEmail;
		//alert("formField.label"+formField.label);
		if(field !=null && field.type == 'text'){
			//alert("field.type"+field.type);	
		if((formField.label == EmailAddress || formField.label == AlternateEmailAddress || formField.label == "Email Address" || formField.label == "Alternate Email Address")&& field.value!=null && Trim(field.value) != '' ){
		//alert(formField.label+"Ename"+EmailAddress+"Aname"+AlternateEmailAddress);
		if(!isValidSingleEmail(field.value)){
			if(formField.label == EmailAddress || formField.label == "Email Address"){//for unAssingedcanditate Internationalize not working..
			alert(inValidPrimaryEmail);	
			}else if(formField.label == AlternateEmailAddress || formField.label == "Alternate Email Address"){//for unAssingedcanditate Internationalize not working..
			alert(inValidAlternateEmail);
			}else{
				alert(mess);	
			}
				//field.value='';
		formField.focusField.focus();
		return false;
		}
		}
		}
		
		if(field !=null && field.type == 'text'){
		if(formField.label == yearofbirth && field.value!=null && Trim(field.value) != '' ){
		if(!isInteger(field.value)){
		alert(messnum);	
		formField.focusField.focus();
		return false;
		}
		}
		}
        if (formField.required == null || !formField.required || !formField.field)
            continue;
        var value = null;
				
	//	alert("field"+field.label);
        if (field.type == 'text' ||
            field.type == 'textarea' ||
            field.type == 'file' ||
            field.type == 'password') {
            
            value = field.value;
						
// ------------trim ( ltrim,rtrim) the value-------------------------------------          
			while (value.substring(0,1) == ' '){

			//	alert(value.substring(1, value.length));
				value = value.substring(1, value.length);
									

				while (value.substring(value.length-1, value.length) == ' '){
					//alert("inside"+value.substring(0,value.length-1));

					value = value.substring(0,value.length-1);
								

				}
			}

		}//---------------- not accepting space in RichText Editor(allavudeen) and accepting image without text------------------------
			 else if(field.type == 'hidden')
		 {
			value =field.value;
    		value = value.replace(/&nbsp;/gi,'');
			if((value.toLowerCase()).match(/<img[^>]+/)){
			value=value;
			}
			else{
			value=value.replace(/(<([^>]+)>)/ig,"");
			value = value.replace(/^\s*/,'');
			}
			
		
	 } //end code (allavudeen)
//--------------------------------------------------------------------------------
         else if (field.type == 'select-one') {

            var si = field.selectedIndex;
            if (si >= 0) {
                value = field.options[si].value;
				if(value!=null && value!=''){
					for(i=0;i<value.length;i++)
					{
						var aa = 'q'+value+'.other';
						val = document.getElementById(aa);
						if(val!=null)
						{
							if(val.value=='' && val.value==""){
								value = '';
								break;
							}
						}
					}
				}
            }
        } else if (field.type == 'select-multiple') {

            value = getListBoxValue(field);
				if(value!=null && value!=''){
					for(i=0;i<value.length;i++)
					{
						var aa = 'q'+value[i]+'.other';
						val = document.getElementById(aa);
						if(val!=null)
						{
							if(val.value=='' && val.value==""){
								value = '';
								break;
							}
						}
					}
				}
        } else if (field.type == 'radio') {

			if(field.checked){
				value =field.value;
			}else{
			value ='';
			}

        } else if (field.type == 'checkbox') {

			if(field.checked){
				value =field.value;
			}else{
			value ='';
			}

		}else if (field.length != null) {

        	if (field[0].type == 'radio') {
					rad=false;	
					isRadFocus=true;
					for(i=0;i<field.length;i++)
					{	
						if(field[i].checked) rad=true;
					}

					if(!rad)
					 {
						
						field[0].focus();
						radfocus=field[0];
						value = '';
					 }
				
        		value = getRadioButtonValue(field);
				if(value!=null && value!=''){
					for(i=0;i<value.length;i++)
					{

						var aa = 'q'+value+'.other';
						val = document.getElementById(aa);
						if(val!=null)
						{

							if(val.value=='' && val.value==""){
								value = '';
								break;
							}
						}
				
					}
				}
        	}
			else if (field[0].type == 'checkbox') {
				chk=false;
				isCheckFocus=true;
				for(i=0;i<field.length;i++)
					{

						if(field[i].checked) chk=true;
					}

					if(!chk)
					 {	

						field[0].focus();
						chkfocus=field[0];
						value = '';
					 }
        		value = getCheckBoxValue(field);
				if(value!=null && value!=''){

					for(i=0;i<value.length;i++)
					{
						var aa = 'q'+value[i]+'.other';
						val = document.getElementById(aa);
						if(val!=null)
						{
							if(val.value=='' && val.value==""){
								value = '';
								break;
							}
						}
					}
				}
        	}
			else if (field[0].type == 'hidden') {
				rdd=false;	
				isRddFocus=true;
				var textObj = null;

				for(i=0;i<field.length;i++)
					{

						if(field[i] !=null && field[i].name!=null && field[i].name.substring(0,6)=='Matrix' && field[i].value!=null){
							 textObj = document.getElementById(field[i].value);
						 	 if(textObj!=null && textObj.value!=null && Trim(textObj.value) != ''){
								 value=textObj.value;
								 rdd=true;
								 }
						}

					}
					if(!rdd)
					 {	
						var txtObj = document.getElementById(field[0].value);
						//txtObj.focus();
						rddfocus=txtObj;
						value = '';
					 }

			}
        }
        if (value == null || value == '') {
						//alert("first "+formField.label);

				if(formField.label==DisplayType){
	 				 reorder=true;
					}
						if(reorder && formField.label!=ColumnName){
						//alert("inside reorder"+formField.label);

			//alert("if"+formField.label +"1:"+Criteria+"|Choices:"+Choices+"|Files"+Files);
			if(formField.label==Criteria || formField.label==Choices || formField.label==Files || formField.label==RowName){//...code start to validate Criteria field in BSW Question and choice in Multiplechoices and Files in Download files.
			reorder=false;
			cValid=false;
			//alert("cValid:"+cValid);
			}else{  //end
			 bValid = false;
			// alert("inside else");
			}
			         
            if (focusField == null 
                    && formField.focusField != null
                    && formField.focusField.focus != null) {
									
                focusField = formField.focusField;
									

            }else if(focusField == null 
                    && !rad && isRadFocus)
			{	
              focusField = radfocus;
			}
			else if(focusField == null 
                    && !chk && isCheckFocus)
			{
					

              focusField = chkfocus;
			}
			else if(focusField == null 
                    && !rdd && isRddFocus)
			{
					

              focusField = rddfocus;
			}

			//alert("last"+formField.label);
			msg += ' - '+formField.label+'\n';
				//alert("se"+msg);

		}
        }else{//..start
		if(formField.label=='Place' ||formField.label=='Lable' || formField.label==Criteria || formField.label==Choices || formField.label==Files || formField.label==RowName){
			msg = msg.replace("- "+Criteria+"\n","");
			msg = msg.replace("- "+Choices+"\n","");
			msg = msg.replace("- "+Files+"\n","");
			msg = msg.replace("- "+RowName+"\n","");
			 cValid = true;
			 reorder=false;
			//alert("cValid:"+cValid);
			}//end
		}
    }

// Following code is to Check required Column Name in Simple Matrix Question type in Survey
var Cempty = true;
var cValid1 = true;

	for (x in fields) {
        var formField = fields[x];
        var field = formField.field;
		if(formField !=null && formField.label==ColumnName){
			if (formField.required == null || !formField.required || !formField.field)
				continue;
		
			var value = null;
			if (field.type == 'text') {            
				value = field.value;
				while (value.substring(0,1) == ' '){
					value = value.substring(1, value.length);
					while (value.substring(value.length-1, value.length) == ' '){
						value = value.substring(0,value.length-1);
					}
				}
			}

			 if (value == null || value == '') {
				 if(Cempty){
			 		Cempty=false;
					cValid1=false;
					
					if(cValid && focusField != null && focusField.name != null){
						var focusName = focusField.name;
						var str =  focusName.substr( focusName.indexOf(".")+1,10);
						var Chtxt =  focusName.substr(0,7);
							if (str == "choiceText" && Chtxt =="choice["){
								focusField = formField.focusField;
							}
					}

					if (focusField == null 
					   && formField.focusField != null
							&& formField.focusField.focus != null) 									
						focusField = formField.focusField;

					 msg += ' - '+formField.label+'\n';
				 }

			  } else {
				    Cempty=false;
					cValid1 = true;
			  		msg = msg.replace("- "+ColumnName+"\n","");

			  }
		}
	}

if(cValid)cValid=cValid1;

      //alert("cValid:"+cValid+"bValid:"+bValid);
    if (!bValid || !cValid) {	
			msg=msg.replace('  -',' -');
			alert(msg);
		if(focusField!=null){	

			focusField.focus();
	        if (val!=null && val.value=='' &&chk &&rad) 
			{
				val.focus();
			}
		}
		return false;
	}

	
    return true;
}
/**
 * Function to validate the maxLength fields in a form.
 */
function validateMaxLength(fields) {
    var bValid = true;
    var focusField = null;
    var msg = validationMessages.maxLength + '\n\n';
    
    for (x in fields) {
        var formField = fields[x];
        if (formField.maxLength == null || !formField.field)
            continue;
            
        var field = formField.field;
        if (field.type == 'text' ||
            field.type == 'textarea' ||
            field.type == 'hidden' ||
            field.type == 'password') {
            
            var value = field.value;
            if (value != '' && value.length > formField.maxLength) {
                bValid = false;
                if (focusField == null 
                        && formField.focusField != null
                        && formField.focusField.focus != null) {
                    focusField = formField.focusField;
                }
                msg += ' - '+formField.label+' ('+formField.maxLength+')\n';
            }
        }
    }
    if (!bValid) {
        alert(msg);
        if (focusField != null) focusField.focus();
    }
    return bValid;
}

var reInteger = /^\d+$/
/**
 * Function to validate the integer fields in a form.
 */
function validateIsInteger(fields) {
    var bValid = true;
    var focusField = null;
    var msg = validationMessages.isInteger + '\n\n';
    
    for (x in fields) {
        var formField = fields[x];
        if (formField.isInteger == null || formField.isInteger == false || !formField.field)
            continue;
            
        var field = formField.field;
        if (field.type == 'text' && field.value != '') {
            if (!reInteger.test(field.value)) {
                bValid = false;
                if (focusField == null 
                        && formField.focusField != null
                        && formField.focusField.focus != null) {
                    focusField = formField.focusField;
                }
                msg += ' - '+formField.label+'\n';
            }
        }
    }
    if (!bValid) {
        alert(msg);
        if (focusField != null) focusField.focus();
    }
    return bValid;
}

var reFloat = /^\d*\.?\d+$/
/**
 * Function to validate the float fields in a form.
 */
function validateIsFloat(fields) {
    var bValid = true;
    var focusField = null;
    var msg = validationMessages.isFloat + '\n\n';
    
    for (x in fields) {
        var formField = fields[x];
        if (formField.isFloat == null || formField.isFloat == false || !formField.field)
            continue;
            
        var field = formField.field;
        if (field.type == 'text' && field.value != '') {
            if (!reFloat.test(field.value)) {
                bValid = false;
                if (focusField == null 
                        && formField.focusField != null
                        && formField.focusField.focus != null) {
                    focusField = formField.focusField;
                }
                msg += ' - '+formField.label+'\n';
            }
        }
    }
    if (!bValid) {
        alert(msg);
        if (focusField != null) focusField.focus();
    }
    return bValid;
}

/**
 * The selectAll function used by TreeView and TableView controls
 */
function selectAll(form) {
	    var flag = form.SelectAllBox.checked;
    var className = (flag) ?"tbl_selected_row" :"tbl_unselected_row";
    var len = form.elements.length;
    for (var i=0; i < len; i++) {
        obj = form.elements[i];
        if (obj.type == "checkbox" && obj.name == "selectedNodes") {
            obj.checked = flag;
            var tdNode = obj.parentNode;
            if (tdNode != null && tdNode.nodeName == 'TD') {
                var trNode = tdNode.parentNode;
                if (trNode != null && trNode.nodeName == 'TR') {
                    trNode.className = className;
                }
            }
        }
    }
    return true;
}

function getSingleChoiceValue( control ) {
    if (control.type && control.type == 'select-one') {
        return getDropDownValue(control);
    } else {
        return getRadioButtonValue(control);
    }
}
function getRadioButtonValue( radio ) {
   if (radio == null)
      return null;

   if (radio.length == null) {
      if (radio.checked)
         return radio.value;
      else
         return null;
   } else {
      for (var i = 0; i < radio.length; i++) {
         if (radio[i].checked) {
            return radio[i].value;
         }
      }
      return null;
   }
}
function getDropDownValue( dropdown ) {
    if (dropdown == null || dropdown.selectedIndex < 0) {
        return null;
    } else {
        return dropdown.options[dropdown.selectedIndex].value;
    }
}
function getMultipleChoiceValue( control ) {
    if (control.type && control.type == 'select-multiple') {
        return getListBoxValue(control);
    } else {
        return getCheckBoxValue(control);
    }
}
function getCheckBoxValue( checkbox ) {
    if (checkbox == null)
        return null;
        
    var sel = new Array();
    if (checkbox.length == null) {
        if (checkbox.checked)
            sel[sel.length] = checkbox.value;
    } else {
        for (var i=0; i < checkbox.length; i++) {
            if (checkbox[i].checked)
                sel[sel.length] = checkbox[i].value;
        }
    }
    if (sel.length == 0)
        return null;
    else 
        return sel;
}

function getUnCheckBoxValue(checkbox) {
    if (checkbox == null)
        return null;
        
    var unSel = new Array();
    if (checkbox.length == null) {
        if (!checkbox.checked)
            unSel[unSel.length] = checkbox.value;
    } else {
        for (var i=0; i < checkbox.length; i++) {
            if (!checkbox[i].checked)
                unSel[unSel.length] = checkbox[i].value;
        }
    }
    if (unSel.length == 0)
        return null;
    else 
        return unSel;
}

function getListBoxValue( listbox ) {
    if (listbox == null)
        return null;
        
    var sel = new Array();
    for (var i=0; i < listbox.options.length; i++) {
        if (listbox.options[i].selected)
            sel[sel.length] = listbox.options[i].value;
    }
    if (sel.length == 0)
        return null;
    else 
        return sel;
}


//password validation allavudeen added

function Check(smallchar,capitalchar,number,password)
	{
	smallCheck=false;
   UpperCheck=false;
   NumberCheck=false;
   splcharCheck=false;
   sucess = false;
   granted=false;
   var count=0;

   for(var i=0;i<password.length;i++)
	{  
	   allthree=false;	   
	if(((smallchar).indexOf(password.charAt(i))!= -1) || ((capitalchar).indexOf(password.charAt(i))!= -1) || ((number).indexOf(password.charAt(i))!= -1))	
		{
			allthree=true;
		}
		if(!allthree && !splcharCheck){
			splcharCheck=true;
    		count++;
	}if((!smallCheck)&&(smallchar).indexOf(password.charAt(i)) != -1)
		   {
			smallCheck=true;
			count++;
	}else if((!UpperCheck)&&(capitalchar).indexOf(password.charAt(i)) != -1)
		   {
			UpperCheck=true;
			count++;
	}else if((!NumberCheck)&&(number).indexOf(password.charAt(i)) != -1)
		   {
			NumberCheck=true;
			count++;
	        }
	if(count>2)
		   {
    	   granted=true;
		   return true;
		   break;
           }
	  
	}
	
  if(!granted)
	  {
	   return false;
	   } 
   }
//password end

// Manage element visibility
function toggleVisible(elemId) {
    var el = document.getElementById(elemId);
    var visible = (el.style == null || el.style.visibility == 'visible');
    setVisible(elemId, !visible);
}
function setVisible(elemId, flag) {
    var el = document.getElementById(elemId);
    if (el.style == null) {
        el.style = new Object();
    }
    if (flag) {
        el.style.visibility = 'visible';
    } else {
        el.style.visibility = 'hidden';
    }
}
function syncVisible(elemId, checkable) {
    setVisible(elemId, checkable.checked);
}

// Manage element display
function toggleDisplay(elemId) {
    var el = document.getElementById(elemId);
    var visible = (el.style == null || el.style.display == '');
    setDisplay(elemId, !visible);
}
function setDisplay(elemId, flag) {
    var el = document.getElementById(elemId);
	if(el!=null){
    if (el.style == null) {
        el.style = new Object();
    }
    if (flag) {
        el.style.display = '';
    } else {
        el.style.display = 'none';
    }
	}
}
/*function syncDisplay(elemId, checkable) {
    setDisplay(elemId, checkable.checked);
}*/

function removeElement(elementId) {
    var el = document.getElementById(elementId);
    if (el == null) return;
    el.parentNode.removeChild(el);
}
function moveUpElement(elemId) {
try{
    var el = document.getElementById(elemId);
    var sb = el.previousSibling;
    while (sb != null && sb.id == null)
    {
     sb = sb.previousSibling;
    }
    if (sb != null) {
  	  sb.parentNode.removeChild(el);
      sb.parentNode.insertBefore(el, sb);
    }

    }catch(e){}
}
function moveDownElement(elemId) {
try{
    var el = document.getElementById(elemId);
    var sb = el.nextSibling;
    while (sb != null && sb.id == null) 
    {
		sb = sb.nextSibling;
    }
    if (sb != null) {
        moveUpElement(sb.id);
    }
    }catch(e){}
}
function selectRow(ctrl, el){
	var row = document.getElementById(el);
    var ndx = el.indexOf('_');
    var last = eval(el.substring(0, ndx)+"_last");
    if (last == null) last = new Object();

    if (ctrl == null || row == null) return;

    if (ctrl.checked){
        if (ctrl.type == 'radio') {
            last.className = 'tbl_unselected_row';
            eval(el.substring(0, ndx)+"_last = row");
        }
        row.className = 'tbl_selected_row';
    } else {
        row.className = 'tbl_unselected_row';
    }
	if(document.forms[0].selectedNodes && ctrl.type!='radio' && document.forms[0].SelectAllBox!=null)document.forms[0].SelectAllBox.checked = false;
}
/* Cookie Management functions */
function setCookie(cookieName, cookieValue, expires, path, domain, secure) {
    document.cookie =
        escape(cookieName) + '=' + escape(cookieValue)
        + (expires ? '; expires=' + expires.toGMTString() : '')
        + (path ? '; path=' + path : '')
        + (domain ? '; domain=' + domain : '')
        + (secure ? '; secure' : '');
}
function getCookie(cookieName) {
    var cookieValue = '';
    var posName = document.cookie.indexOf(escape(cookieName) + '=');
    if (posName != -1) {
        var posValue = posName + (escape(cookieName) + '=').length;
        var endPos = document.cookie.indexOf(';', posValue);
        if (endPos != -1) cookieValue = unescape(document.cookie.substring(posValue, endPos));
        else cookieValue = unescape(document.cookie.substring(posValue));
    }
    return (cookieValue);
}
function removeCookie(name) {
    var now = new Date();
    var yesterday = new Date(now.getTime() - 1000 * 60 * 60 * 24);
    this.setCookie(name, 'cookieValue', yesterday);
}

/**
 * Moves item from source listbox (formname.fieldname)
 * to destination listbox.
 *
 *
 */
 
function moveItem(source, destination) {

   var sourceLength = source.options.length;

   for (var i=0;i < sourceLength;i++) {
      if (source.options[i].selected) {
         var ind = destination.options.length;
         var optionInt = new Option(source.options[i].text, source.options[i].value);
         destination.options[ind] = optionInt;
         optionInt = null;
         source.options[i] = null;
         i=-1;
      }
      sourceLength =  source.options.length;
   }

}

/*
 06-10 Arun
 Supports the above function sortBy( column, selectionBox )
*/
function User( lastName, firstName, company )
{
   this.lastName = lastName
   this.firstName = firstName
   this.company = company
}

function Trim(str)
{
	while(str.charAt(0) == (" ") )
  {  str = str.substring(1);
  }
  while(str.charAt(str.length-1) == " " )
  {  str = str.substring(0,str.length-1);
  }
  return str;
}



function submitReplyForum(text){


		var form = document.forms[0];
		form.action = '/DSCPostReplyAction.fms';
		form.submit();


	 frames[0].document.body.innerHTML+="<table border='0'><tr><td>&nbsp;</td><td>&nbsp;</td></tr><tr class='tbl_forum_row'><td>&nbsp;</td><td>Quote: </td></tr><tr><td>&nbsp;</td><td><table class='tbl_forum_quote'><tr><td>"+text+"</td></tr></table></td></tr></table>";
	if(isIE)
		window.document.frames[0].focus();
	else if(isMozilla|| isSafari)
		document.getElementById("message").contentWindow.focus();


	

}

function doPagination(text,count)
{
	
	var form = document.forms[0];
	var sel = getCheckBoxValue(form.selectedNodes);
	var unSel = getUnCheckBoxValue(form.selectedNodes);
	form.userId.value = sel;
	form.currentSelectedUsers.value = sel;
	form.unSelectedUsers.value = unSel;
	if(text ==  'first' || text == 'last' )
		form.value.value =count;
	else if(text == 'prev') 
		form.value.value =--count;
	else if(text == 'next') 
		form.value.value =++count;
	else if(text == 'numbers')
		form.value.value =count;

	form.submit();
}
function doPagination_1(text,count)
{
	
var form = document.forms[0];

	if(text ==  'first' || text == 'last' )
		form.value.value =count;
	else if(text == 'prev') 
		form.value.value =--count;
	else if(text == 'next') 
		form.value.value =++count;
	else if(text == 'numbers')
		form.value.value =count;

	form.submit();
}
function newwindowclose(newwin)
 {
   if(newwin!=null)newwin.close();
 }


function addRemoveUsers(allUsers)
	{
	var form = document.forms[0];
	var sel = getCheckBoxValue(form.selectedNodes);
	var unSel = getUnCheckBoxValue(form.selectedNodes);
     var allUser = allUsers.split(",");
		if(unSel != null){
		for(var i=0;i<unSel.length;i++)
		{
			for(var n=0;n<allUser.length;n++){
				if(unSel[i] == allUser[n])
				allUser.splice(n,1);
			}
		}
		}

		if(sel != null){
		for(var i=0;i<sel.length;i++)
		{
			var check = true;
			for(var n=0;n<allUser.length;n++){
				if(sel[i] == allUser[n])
				check=false;
			}
				if(check)
				allUser.splice(n,0,sel[i]);
			}
		}
		return allUser;
	}

function disableTitleBarButtons(){ // senthilm - created for disabling title bar buttons
	//var tt = document.getElementsByName('titleBarButtonName');
	//for(var j=0;j<tt.length;j++){
	//	tt[j].disabled=true;
	//}
if(document.getElementsByName('aboveSubmitTop')!=null){
var obj = document.getElementsByName('aboveSubmitTop'); 
if(obj != null) 
{ 
 
for(var j=0;j<obj.length;j++){
var onclick = obj[j].getAttribute('onclick');
if(onclick != null) 
{ 
obj[j].setAttribute('onclick', "void(0);"); 
obj[j].style.color="gray"; 
} 
}
}
}


if(document.getElementsByName('topSubmitTop')!=null){
var obj = document.getElementsByName('topSubmitTop'); 
if(obj != null) 
{ 
 
for(var j=0;j<obj.length;j++){
var onclick = obj[j].getAttribute('onclick');
if(onclick != null) 
{ 
obj[j].setAttribute('onclick', "void(0);"); 
obj[j].style.color="gray"; 
} 
}
}
}
if(document.getElementsByName('titleBarButtonName')!=null){
var obj = document.getElementsByName('titleBarButtonName'); 
if(obj != null) 
{ 
 
for(var j=0;j<obj.length;j++){
var onclick = obj[j].getAttribute('onclick');
if(onclick != null) 
{ 
obj[j].setAttribute('onclick', "void(0);"); 
obj[j].style.color="gray"; 
} 
}
}
} 

}
function disableContextBarButtons(){ // senthilm - created for disabling context bar buttons
	var obj = document.getElementsByName('contextBarButtonName'); 
if(obj != null) 
{ 
 
for(var j=0;j<obj.length;j++){
var onclick = obj[j].getAttribute('onclick');
if(onclick != null) 
{ 
obj[j].setAttribute('onclick', "void(0);"); 
obj[j].style.color="gray"; 
} 
}
 
} 

}
function isValidSingleEmail(x)// senthilm - for Single Email validation using pattern
{
	var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9_\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	
	if (isWhitespace(x)) return false;
	x=Trim(x);
	if(x.indexOf("..")!=-1 || x.indexOf(".")==-1 || x.indexOf(".")==0)
		return false;
	if(x.indexOf(".@")!=-1 || x.indexOf("@.")!=-1)
		return false;
	if (filter.test(x)) return true;
	else return false;
}

/*function isValidSingleEmail (s)
{ 
	if (isEmpty(s))
       if (isValidSingleEmail.arguments.length == 1) return defaultEmptyOK;
       else return (isEmail.arguments[1] == true);


	// is s whitespace?
    if (isWhitespace(s)) return false;

	s=Trim(s);
	var specialchars="\"\',;:?!()[]  <>{}^|&*~`$%#=\\+/";    
    var m=0;
    var atTrue=false;
	for(j=0;j<s.length;j++)
	{
		if(specialchars.indexOf(s.charAt(j))!=-1){
			return false;
		}
		if(s.charAt(j)=='@')
        {      
			atTrue=true;
			if(m>0)
				return false;
			m++;
		}
	}
	if(!atTrue)
		return false;
	if(s.indexOf("..")!=-1 || s.indexOf(".")==-1)
		return false;
	if(s.indexOf("@@")!=-1)
		return false;


	if(s.indexOf(".@")!=-1 || s.indexOf("@.")!=-1)
		return false;

	if (s.charAt(0)=='@' || s.charAt(0)=='.' || s.charAt(s.length-1)=='@' || s.charAt(s.length-1)=='.')
		return false;

return true;

}*/
function replaceAll(text, strA, strB) // Dhinesh
{
    while ( text.indexOf(strA) != -1)
    {
        text = text.replace(strA,strB);
    }
    return text;
}
function getXMLHttpRequest()
{
var xmlHttp;
try
  {
  // Firefox, Opera 8.0+, Safari
  xmlHttp=new XMLHttpRequest();
  }
catch (e)
  {
  // Internet Explorer
  try
    {
    xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
    }
  catch (e)
    {
    try
      {
      xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
    catch (e)
      {
      alert("Your browser does not support AJAX!");
      return false;
      }
    }
  }
  return xmlHttp;
  }


  //Activity Log,Advanced activity log ,wizard search activity log

   function removingFirstElement(id){
                  if(groupArray[id].length<2){
						var groupTableRem="groupTable"+id;
						var outerConditionRemove="outerCondition"+id;
						var outerConditionRemovePrefix="outerConditionPrefixBr"+id;
						var outerConditionRemoveSuffix="outerConditionSuffixBr"+id;
						if(document.getElementById(groupTableRem)!=null){
							document.getElementById(groupTableRem).style.display='none';
                           // removeElement(groupTableRem);
						}
						if(document.getElementById(outerConditionRemove)!=null){
                          
							for(m=0;m<=groupArrayFinal.length;m++){
								if(groupArrayFinal[m]==id){		
									removeElement(outerConditionRemove);
									removeElement(outerConditionRemovePrefix);
									removeElement(outerConditionRemoveSuffix);
									groupArrayFinal.splice(m,1);
									break;
								}
                                
							}

						}
						//cnt=id;
					}
 }

  function removingFirstGroupElement(str,id,a,totalcount){
       	var indexGrp=a;
		if(indexGrp==0)
		 {
          if(groupArray[id].length==1){
			for(m=0;m<=groupArrayFinal.length;m++){
					if(groupArrayFinal[m]==id){		
						//if(m==0){
                             var totID=id+1;
							 for(ab=0;ab<=cnt;ab++){
								 if(document.getElementById('outerCondition'+ab)!=null){
			                          removeElement('outerCondition'+ab);
									  removeElement('outerConditionPrefixBr'+ab);
									  removeElement('outerConditionSuffixBr'+ab);
									  groupArrayFinal.splice(m,1);
							          break;
								 }
							 							
							 }
						//}
						
						
					}
                                
			}
		  }
			
		
          for(h=1;h<totalcount+1;h++){
		  	 var innerCondtionid1=str+id+"_"+h;
				 if(document.getElementById(innerCondtionid1)!=null){
					  removeElement(innerCondtionid1);
		              groupArray[id].splice(a,1); 
		              break;
					}
		   }
		  }

	  else{
		   groupArray[id].splice(a,1); 
		  }
  }
  function cumulativeOffset(element) 
{
		var valueT = 0, valueL = 0;
		do {
			valueT += element.offsetTop  || 0;
			valueL += element.offsetLeft || 0;
			element = element.offsetParent;
		} while (element);
		return [valueL, valueT];
 }


 function questionToAnother()
 {
var array=new Array();
array.push("AF+/QTNSaveAutoFill");array.push("OL+/QTNSaveOrderedList");array.push("OPEN_TEXT+/QTNSaveOpenText");
array.push("OPEN_NO+/QTNSaveOpenNo");array.push("YN+/QTNSaveYesNo");array.push("SC+/QTNSaveSingleChoice");
array.push("MC+/QTNSaveMultipleChoice");array.push("NOTE+/QTNSaveNote");array.push("VS+/QTNSaveValueScale");
array.push("DL+/QTNSaveDownload");array.push("ATT+/QTNSaveUpload");array.push("BSW+/QTNSaveBetSamWor");
array.push("SM+/QTNSaveSimpleMatrix");array.push("IS+/QTNSaveImpSat");array.push("SMT+/QTNSaveSimpleMatrix");
array.push("SMC+/QTNSaveSimpleMatrix");
return array;
 }


function quesEle(option){

		var SC = titleVariables.SingleChoice;
		var MC = titleVariables.MultipleChoice;
		var OET = titleVariables.OpenEndedText;
		var VS = titleVariables.ValueScale;
		var SM = titleVariables.SingleMatrixSingleChoice;
		var SMC = titleVariables.SingleMatrixMultipleChoice;
		var SMT = titleVariables.SingleMatrixOpenEndedText;
		var OL = titleVariables.OrderedList;
		var AF = titleVariables.AutoFill;
		var DL = titleVariables.Download;
		var ATT = titleVariables.UploadAttachement;
		var BSW = titleVariables.BetterSameWorse;
		var IS = titleVariables.ImportantSatisfaction;
		var YN = titleVariables.YesNo;
		var OEN = titleVariables.OpenEndedNumber;
		var NOTE = titleVariables.NoteTitle;

			var openRow = document.getElementById('openRows');
			var openCol = document.getElementById('openColoumns');
			var OLRow = document.getElementById('olRow');
			var uploadRow = document.getElementById('upRow');
			var choiceRow = document.getElementById('choiceRows');
			var betterRow = document.getElementById('bswRow');
			var scaleRow = document.getElementById('scaleCntRow');
			var criterRow = document.getElementById('criteriaRow');
			var scaleMini = document.getElementById('scaleMin');
			var scaleMaxi = document.getElementById('scaleMax');
			var scaleCnt = document.getElementById('scaleCount');
			var scaleStrt = document.getElementById('scaleStart');
			var AfTitleRow = document.getElementById('afTitleRow');
			var AfQtionRow = document.getElementById('afQtionRow');
			var AfQuestionTableRow = document.getElementById('afQuestionTableRow');
			var AddButtonTableRow = document.getElementById('addButtonTableRow');
			var UpdateButtonTableRow = document.getElementById('updateButtonTableRow');
			var dispType = document.getElementById('disType');
			var otherRow = document.getElementById('otherOption');
			var choiceRows = document.getElementById('choiceRows_1');
			var noteTitleRow = document.getElementById('noteTitleRow');
			document.getElementById("commentTR").style.display = ''
			document.getElementById("requiredTR").style.display = ''
			document.getElementById("sameLineTR").style.display = ''
			document.getElementById("uniqueTR").style.display = 'none'
			

		if(option == "SC"){
		document.getElementById("eleTable").style.display ='block'
		document.getElementById("titleTD").innerHTML =SC;
		var choiceRow = document.getElementById('choiceRows');
			if(document.getElementById("quesTable")!=null && (choiceRow!=null)){
				document.getElementById('quesTable').insertRow(choiceRow.rowIndex);
			}
			var choiceRows = document.getElementById('choiceRows_1');
			if(document.getElementById("choiceTable")!=null && (choiceRows!=null)){
			document.getElementById('choiceTable').insertRow(choiceRows.rowIndex);
			}
			var otherRow = document.getElementById('otherOption');
			if(document.getElementById("otherTable")!=null && (otherRow!=null)){
				document.getElementById('otherTable').insertRow(otherRow.rowIndex);
			}
			var dispType = document.getElementById('disType');
			if(document.getElementById("otherTable")!=null && (dispType!=null)){
				document.getElementById('otherTable').insertRow(dispType.rowIndex);
			}
		}
		else if(option == "MC"){
		document.getElementById("eleTable").style.display ='block'
		document.getElementById("titleTD").innerHTML =MC;
		var choiceRow = document.getElementById('choiceRows');
			if(document.getElementById("quesTable")!=null && (choiceRow!=null)){
				document.getElementById('quesTable').insertRow(choiceRow.rowIndex);
			}
			var choiceRows = document.getElementById('choiceRows_1');
			if(document.getElementById("choiceTable")!=null && (choiceRows!=null)){
			document.getElementById('choiceTable').insertRow(choiceRows.rowIndex);
			}
			var otherRow = document.getElementById('otherOption');
			if(document.getElementById("otherTable")!=null && (otherRow!=null)){
			document.getElementById('otherTable').insertRow(otherRow.rowIndex);
			}
			var dispType = document.getElementById('disType');
			if(document.getElementById("otherTable")!=null && (dispType!=null)){
			document.getElementById('otherTable').insertRow(dispType.rowIndex);
			}

			}
		else if(option == "OPEN_TEXT"){
		document.getElementById("eleTable").style.display ='block'
		document.getElementById("titleTD").innerHTML =OET;
		var openRow = document.getElementById('openRows');
		var openCol = document.getElementById('openColoumns');
			if(document.getElementById("quesTable")!=null && (openRow!=null) && (openCol!=null)){
			
			document.getElementById('quesTable').insertRow(openRow.rowIndex);
			document.getElementById('quesTable').insertRow(openCol.rowIndex);
			}
			}
		else if(option == "VS"){
		document.getElementById("eleTable").style.display ='block'
		document.getElementById("titleTD").innerHTML =VS;
		var scaleMini = document.getElementById('scaleMin');
		var scaleMaxi = document.getElementById('scaleMax');
		var scaleCnt = document.getElementById('scaleCount');
		var scaleStrt = document.getElementById('scaleStart');
			if(document.getElementById("quesTable")!=null && (scaleMini!=null) && (scaleMaxi!=null) && (scaleCnt!=null) && (scaleStrt!=null)){
				document.getElementById('quesTable').insertRow(scaleMini.rowIndex);
				document.getElementById('quesTable').insertRow(scaleMaxi.rowIndex);
				document.getElementById('quesTable').insertRow(scaleCnt.rowIndex);
				document.getElementById('quesTable').insertRow(scaleStrt.rowIndex);
			}
		
			}
		else if(option == "SM"){
		document.getElementById("eleTable").style.display ='block'
		document.getElementById("titleTD").innerHTML =SM;
			}
		else if(option == "SMC"){
		document.getElementById("eleTable").style.display ='block'
		document.getElementById("titleTD").innerHTML =SMC;
			}
		else if(option == "SMT"){
		document.getElementById("eleTable").style.display ='block'
		document.getElementById("titleTD").innerHTML =SMT;
			}
		else if(option == "OL"){
		document.getElementById("eleTable").style.display ='block'
		document.getElementById("titleTD").innerHTML =OL;
		var OLRow = document.getElementById('olRow');
			if(document.getElementById("quesTable")!=null && (OLRow!=null)){
				document.getElementById('quesTable').insertRow(OLRow.rowIndex);
			}
		document.getElementById("uniqueTR").style.display = ''
			}
		else if(option == "AF"){
		document.getElementById("eleTable").style.display ='block'
		document.getElementById("titleTD").innerHTML =AF;
		var AfQtionRow = document.getElementById('afQtionRow');
		var AfQuestionTableRow = document.getElementById('afQuestionTableRow');
		var AddButtonTableRow = document.getElementById('addButtonTableRow');
		var UpdateButtonTableRow = document.getElementById('updateButtonTableRow');

			if(document.getElementById("afTable")!=null && (AfQtionRow!=null)){
				document.getElementById('afTable').insertRow(AfQtionRow.rowIndex);
			}
			if(document.getElementById("afQuestionTable")!=null && (AfQuestionTableRow!=null)){
				document.getElementById('afQuestionTable').insertRow(AfQuestionTableRow.rowIndex);
			}
			if(document.getElementById("addButtonTable")!=null && (AddButtonTableRow!=null)){
				document.getElementById('addButtonTable').insertRow(AddButtonTableRow.rowIndex);
			}
			if(document.getElementById("updateButtonTable")!=null && (UpdateButtonTableRow!=null)){
				document.getElementById('updateButtonTable').insertRow(UpdateButtonTableRow.rowIndex);
			}

			}
		else if(option == "DL"){
					document.getElementById("eleTable").style.display ='block'
				document.getElementById("commentTR").style.display = 'none'
			var downloadRow = document.getElementById('downRow');
			if(document.getElementById("downTable")!=null && (downloadRow!=null)){
				document.getElementById('downTable').insertRow(downloadRow.rowIndex);
			}
		document.getElementById("titleTD").innerHTML =DL;
			}
		else if(option == "ATT"){
		document.getElementById("eleTable").style.display ='block'
		document.getElementById("titleTD").innerHTML =ATT;
		var uploadRow = document.getElementById('upRow');
			if(document.getElementById("upTable")!=null && (uploadRow!=null)){
				document.getElementById('upTable').insertRow(uploadRow.rowIndex);
			}
		
			}
		else if(option == "BSW"){
		document.getElementById("eleTable").style.display ='block'
		document.getElementById("titleTD").innerHTML =BSW;
		var betterRow = document.getElementById('bswRow');
		if(document.getElementById("bswTable")!=null && (betterRow!=null)){
			document.getElementById('bswTable').insertRow(betterRow.rowIndex);
		}

		}
		else if(option == "IS"){
		document.getElementById("eleTable").style.display ='block'
		document.getElementById("titleTD").innerHTML =IS;
		var scaleRow = document.getElementById('scaleCntRow');
		var criterRow = document.getElementById('criteriaRow');
		if(document.getElementById("isTable")!=null && (scaleRow!=null) && (criterRow!=null)){
			document.getElementById('isTable').insertRow(scaleRow.rowIndex);
			document.getElementById('isTable').insertRow(criterRow.rowIndex);
		}
	
		}
		else if(option == "YN"){
		document.getElementById("eleTable").style.display ='block'
		document.getElementById("titleTD").innerHTML =YN;
		var yesRow = document.getElementById('yesRows');
			var titleRows = document.getElementById('titleRow');
			if(document.getElementById("quesTable")!=null && (yesRow!=null)){
			document.getElementById('quesTable').insertRow(yesRow.rowIndex);
			}
		}
		else if(option == "NOTE"){
		document.getElementById("eleTable").style.display ='block'
		document.getElementById("commentTR").style.display = 'none'
		document.getElementById("requiredTR").style.display = 'none'
		document.getElementById("sameLineTR").style.display = 'none'
		document.getElementById("titleTD").innerHTML =NOTE;
		}
		else {
		document.getElementById("eleTable").style.display ='block'
		document.getElementById("titleTD").innerHTML =OEN;
		var openRow = document.getElementById('openRows');
			if(document.getElementById("quesTable")!=null && (openRow!=null)){
			document.getElementById('quesTable').insertRow(openRow.rowIndex);
		}

		}
	}

function common(form){
//	alert("Common")

	/*	alert ("Choices" +validationMessages.Choices+" displaytype "+validationMessages.DisplayType+" OpenEndedRows "+ validationMessages.DisplayType+" OpenEndedColumns  "+ validationMessages.OpenEndedColumns +" ScaleMin   "+validationMessages.ScaleMin+
			" ScaleCount "+validationMessages.ScaleCount+" Value "+validationMessages.Value+ "Greater "+validationMessages.Greater+
			"FileCount " + validationMessages.FileCount+" Files "+validationMessages.Files + " Criteria" +validationMessages.Criteria)*/

var Choices = validationMessages.Choices;
var displaytype = validationMessages.DisplayType;
var OpenEndedRows = validationMessages.OpenEndedRows;
var OpenEndedColumns  = validationMessages.OpenEndedColumns;
var ScaleMin  = validationMessages.ScaleMin;
var ScaleMax  = validationMessages.ScaleMax;
var ScaleCount  = validationMessages.ScaleCount;
var Value  = validationMessages.Value;
var Greater  = validationMessages.Greater;
var StartValue  = validationMessages.StartValue;
var FileCount  = validationMessages.FileCount;
var Files  = validationMessages.Files;
var Criteria  = validationMessages.Criteria;
var OrderlistChoices  = validationMessages.OrderlistChoices;


var count =0;
var	message="";
for(i=0;i<document.forms[0].elements.length;i++){
			var qTypeValue = document.forms[0].elements[i].value;
			var choiceName = document.forms[0].elements[i].name;
			///SC & MC displayTypeCode
			if(choiceName == "convertQuestionType" && (qTypeValue =="SC")){
			for(j=0;j<document.forms[0].elements.length;j++){
			var scName = document.forms[0].elements[j].name;
			var str =  scName.substr(scName.indexOf(".")+1,10);
			var Chtxt =  scName.substr(0,7);
			if (str == "choiceText" && Chtxt =="choice["){
				count++;
				field = new FormField(document.forms[0].elements[j], Choices);
				 field.required = true;
				 fields[fields.length] = field;	
			
			}
			if(scName == "displayTypeCode"){
				field = new FormField(document.forms[0].displayTypeCode, displaytype);
				field.required = true;
				fields[fields.length] = field;
				break;
			}
			if(addDiv)
			{    
				setDisplayOrder('choiceHolder'); 
			}
			}
			}
			////////////////MC
			else if(choiceName == "convertQuestionType" && qTypeValue =="MC"){
			
			for(q=0;q<document.forms[0].elements.length;q++){
			var mcName = document.forms[0].elements[q].name;
			var str =  mcName.substr(mcName.indexOf(".")+1,10);
			var Chtxt =  mcName.substr(0,7);
			if (str == "choiceText" && Chtxt =="choice["){
				count++;
				field = new FormField(document.forms[0].elements[q], Choices);
				 field.required = true;
				 fields[fields.length] = field;	
			
			}
			if(mcName == "displayTypeCode"){
				field = new FormField(document.forms[0].displayTypeCode,displaytype);
				field.required = true;
				fields[fields.length] = field;
				break;
			}
			if(addDiv)
			{    
				setDisplayOrder('choiceHolder'); 
			}
			}
			}
			///OET
			else if(choiceName == "convertQuestionType" && (qTypeValue =="OPEN_TEXT")){
			
			for(t=0;t<document.forms[0].elements.length;t++){
			 var oetName = document.forms[0].elements[t].name;
			if(oetName== "openEndedRows"){
			field = new FormField(document.forms[0].elements[t],OpenEndedRows);
			field.required = true;
			field.isInteger = true;
			fields[fields.length] = field;
			}
			if(oetName== "openEndedColumns"){
			field = new FormField(document.forms[0].elements[t],OpenEndedColumns);
			field.required = true;
			field.isInteger = true;
			fields[fields.length] = field;
			}
			addDiv=false;
			}
			}
			/////////////OEN :selectedRoles:::Choice Value::::OPEN_NO
			else if(choiceName == "convertQuestionType" && qTypeValue == "OPEN_NO" ){
				

			for(k=0;k<document.forms[0].elements.length;k++){
			 var oenName = document.forms[0].elements[k].name;
			if(oenName== "openEndedColumns"){
			field = new FormField(document.forms[0].elements[k], OpenEndedColumns);
			field.required = true;
			field.isInteger = true;
			fields[fields.length] = field;
			}
			addDiv = false;
			}
			}
			///VS
			
		   /*if (count==0){
			alert('<bean:message key="QTN.EditSingleChoice.choiceAlert"/>');
			return null;
		   }*/
		 /////////////////VS
		 else if(choiceName == "convertQuestionType" && qTypeValue =="VS"){
			 

		var check = false;
		var start = true;
		var countLessThen = true; 
		var countGreaterThen = true;
		 for(m=0;m<document.forms[0].elements.length;m++){
		   var vsName = document.forms[0].elements[m].name;
		 if(vsName == "scaleMin"){
		 field = new FormField(form.elements[m], ScaleMin);
		 field.required = true;
         fields[fields.length] = field;
		 }
		 if(vsName == "scaleMax"){
		 field = new FormField(form.elements[m], ScaleMax);
		 field.required = true;
         fields[fields.length] = field;
		 }
		 if(vsName == "count"){
		 field = new FormField(form.elements[m], ScaleCount);
		 field.required = true;
         field.isInteger = true;
         fields[fields.length] = field;
		 ///////////////////Scale count
			var countValue = form.elements[m].value;
			
			if(countValue.indexOf('+') == 0)
			{
				var cotValue = countValue.replace('+',"");
				form.elements[m].value = cotValue;
			}
			var nos = form.elements[m].value;			
			if(nos < 1)
			{
			//message = message + "\n" + "- <bean:message key="QTN.EditValueScale.count.Value"/>";
			alert(Value);
			countLessThen = false;
			return false;
			}
			if(nos > 100)
			{
			//message = message + "\n" + "- <bean:message key="QTN.EditValueScale.count.Value.greater.than"/>";
			alert(Greater);
			countGreaterThen = false;
			return false;
			}
		 }
		 if(vsName =="scaleStartValue"){
		 ///////////////////Scale Start
		
		 field = new FormField(form.elements[m], StartValue);
		 field.required = true;
         field.isInteger = true;
         fields[fields.length] = field;

			var startScaleValue = form.elements[m].value;
			if(startScaleValue.indexOf('+') == 0)
			{
			var changeValue = startScaleValue.replace('+',"");
			form.elements[m].value = changeValue;
			}
			if(!isSignedInteger(form.elements[m].value))
			{
//			message = message + "\n" + "- "+StartValue;
			//alert("aa"+StartValue)
			start = false;
			}
		 }
		 addDiv = false;
		 if((check) && (start) && (countLessThen) &&(countGreaterThen))
		 {
			formOK = false;
			disableTitleBarButtons();
		 }
		 
		 }
		 }
		 ///Download
		 else if(choiceName == "convertQuestionType" && qTypeValue =="DL"){
			 
		 for(n=0;n<document.forms[0].elements.length;n++){
		 var dlName = document.forms[0].elements[n].name;
		 var str =  dlName.substr(0,6);
		 
		
		 if(form.elements[n].name.search(".downloadFile") != -1)
			{ 
			count++;
			field = new FormField(form.elements[n], Files);
			field.required = true;
			fields[fields.length] =  field; 
			}
		
			if(addDiv)
			{    
				setDisplayOrder('choiceHolder'); 
			}
		 }
		 }
		///////UPLOAD
		
		else if(choiceName == "convertQuestionType" && qTypeValue =="ATT"){
			
		 for(p=0;p<document.forms[0].elements.length;p++){
		   var upName = document.forms[0].elements[p].name;
			if(upName == "count"){
			field = new FormField(form.elements[p], FileCount);
			field.required = true;
			field.isInteger = true;
			fields[fields.length] = field;
		   }
		   addDiv = false;
		  }
		}
		//////////////OL
		else if(choiceName == "convertQuestionType" && qTypeValue == "OL" ){
				
			for(tt=0;tt<document.forms[0].elements.length;tt++){
			 var olName = document.forms[0].elements[tt].name;
			var str =  olName.substr(olName.indexOf(".")+1,10);
			var Chtxt =  olName.substr(0,7);
			if (str == "choiceText" && Chtxt =="choice["){
				count++;
				field = new FormField(document.forms[0].elements[tt], OrderlistChoices);
				 field.required = true;
				 fields[fields.length] = field;	
			
			}
			if(addDiv)
			{    
				setDisplayOrder('choiceHolder'); 
			}
			}
			}
	/////////////////BSW
	else if(choiceName == "convertQuestionType" && qTypeValue == "BSW" ){
				
			for(pp=0;pp<document.forms[0].elements.length;pp++){
			 var bswName = document.forms[0].elements[pp].name;
			var str =  bswName.substr(bswName.indexOf(".")+1,10);
			var Chtxt =  bswName.substr(0,7);
			if (str == "choiceText" && Chtxt =="choice["){
				count++;
				field = new FormField(document.forms[0].elements[pp], Criteria);
				 field.required = true;
				 fields[fields.length] = field;	
			
			}
		
			if(addDiv)
			{    
				setDisplayOrder('choiceHolder'); 
			}
			}
			}

	/////////////////IS
	else if(choiceName == "convertQuestionType" && qTypeValue == "IS" ){
				
			for(pr=0;pr<document.forms[0].elements.length;pr++){
			 var impName = document.forms[0].elements[pr].name;
			var str =  impName.substr(impName.indexOf(".")+1,10);
			var Chtxt =  impName.substr(0,7);
			if (str == "choiceText" && Chtxt =="choice["){
				count++;
				field = new FormField(document.forms[0].elements[pr], Criteria);
				 field.required = true;
				 fields[fields.length] = field;	
			
			}
			if(impName == "count"){
				field = new FormField(form.elements[pr], ScaleCount);
				field.required = true;
				field.isInteger = true;
				fields[fields.length] = field;
			}
			if(addDiv)
			{    
				setDisplayOrder('choiceHolder'); 
			}
			}
			}

	/////////////////////SM
	else if(choiceName == "convertQuestionType" && (qTypeValue == "SM" || qTypeValue == "SMC" || qTypeValue == "SMT")){
				
			for(ps=0;ps<document.forms[0].elements.length;ps++){
			 var smName = document.forms[0].elements[ps].name;
			var str =  smName.substr(smName.indexOf(".")+1,10);
			var Chtxt =  smName.substr(0,6);
			if (str == "choiceText" && Chtxt !="matrix"){
				count++;
				field = new FormField(form.elements[ps], OpenEndedRows);
				field.required = true;
				fields[fields.length] =  field;	
			
			}
			else if(str == "choiceText"){
				field = new FormField(form.elements[ps],OpenEndedColumns);
				field.required = true;
				fields[fields.length] =  field;
			}
			if(addDiv)
			{    
				setDisplayOrder('choiceHolder'); 
			}
			}
			}
	/////////YES/NO
	else {
		if(choiceName == "convertQuestionType" && (qTypeValue == "YN")){
		
		 for(r=0;r<document.forms[0].elements.length;r++){
		   var ynName = document.forms[0].elements[r].name;
			if(ynName == "displayTypeCode"){
				field = new FormField(document.forms[0].displayTypeCode, displaytype);
				field.required = true;
				fields[fields.length] = field;
				break;
			}
			addDiv = false;
		  }
		}
		}
		}

}
function setDisplayOrder(holderId) {
     var tt = document.getElementById(holderId);
     var chs = tt.getElementsByTagName('li');
     for (var i=0; i < chs.length; i++) {
         var ch = chs.item(i);
         var inps = ch.getElementsByTagName("input");
     for (var j=0; j < inps.length; j++) {
         var inp = inps.item(j);
         if (inp.type == 'hidden' && inp.name.indexOf('displayOrder') > 0) {
         inp.value = i;
         break;
         }
     }
 }
}

function loadFile(item){
	if(isSafari){
		if(webkitVersion<420){
			item.click();
		}
	}
}

