// Start Loading Message///////////
var loadingCount = 2;
var loadingDelay = 100;
var loadingTimerId = 0;

function splitString(str, separator) {
    tokens = str.split(separator);
    return tokens;
}
function startTimer(getVar) {
   // alert('calling start timer');
    if (getVar == 0) {
        stopTimer();
    } else {
        loadingTimerId = self.setTimeout("showWaitMsg()", loadingDelay); //continously call timer
    }
}

function stopTimer() {
   // alert('calling stop  timer');
    if (loadingTimerId) {
        clearTimeout(loadingTimerId); //stop the timer
        loadingTimerId = 0;
    }
}

//this function takes theme and opens login window
function openLoginWindow( theme )
{
    var left = (screen.width / 2) - (485 / 2);
    var top = (screen.height / 2) - (288 / 2);

    var url = "/apolloweb/DefaultLoginPage.jsp?displayMenu=false&theme=" + theme;

    var hWnd = window.open(url, '', 'width=485,height=288');
    hWnd.moveTo(left, top);
    return hWnd;
}


function fixHtmlTags( htmlStr )
{
    //var htmlStr = "<TABLE class=table cellSpacing=0 cellPadding=0 width=\"95%\" align=center border=0>";

    var startIndex;
    var endIndex;
    var text;
    var textFixed;
    var regExp;
    var matched;

    var tagList = new Array
                        (
                        "class=",
                        "cellSpacing=",
                        "cellPadding=",
                        "align=",
                        "colSpan=",
                        "border=",
                        "height=",
                        "id="
                        );

    //alert(htmlStr);

    for( i=0 ; i < tagList.length ; i++ )
    {
        //alert("loop: " + i);
        regExp = new RegExp("(" + tagList[i] + ")([a-z|0-9])", "i");
        matched = regExp.exec(htmlStr);
        while( matched != null )
        {
            if( htmlStr.indexOf(matched[0]) != -1 )
            {
                startIndex = htmlStr.indexOf(matched[0]);

                endIndex = htmlStr.indexOf(" ", startIndex);
                if( endIndex != -1 )
                {
                    if( endIndex > htmlStr.indexOf(">", startIndex) )
                        endIndex = htmlStr.indexOf(">", startIndex);
                }
                else
                    endIndex = htmlStr.indexOf(">", startIndex);

                text = htmlStr.substring(startIndex,endIndex);
                if( text.search("=\"") == -1 )
                {
                    var quotePos = text.search("=");
                    textFixed = text.substring(0,quotePos+1) + "\"" + text.substring(quotePos+1, text.length) + "\"";
                    text = "/" + text + "/gi";
                    htmlStr = htmlStr.replace(eval(text), textFixed);
                }

            }
            matched = regExp.exec(htmlStr);
        }
    }
    //alert(htmlStr);

    return htmlStr;
}

function getDots(loadingCount) {
    var dots = '';
    var modVal = 10; //dots will be N-1
    var mod = loadingCount % modVal;
    for (i = 0; i < mod; i++)
        dots += ".";
	//patch up emppty place else the text will start to dance
    for (i = modVal; i > mod; i--)
        dots += "&nbsp;";
    return dots;
}

function setPointerWithWaitMsg() {
    showWaitMsg();
    if (document.all) {
        var iLength = document.all.length;
        for (var i = 0; i < iLength; i++) {
            var obj = document.all(i);
            if (obj.style.cursor != 'hand') obj.style.cursor = 'wait';
        }
    }
}
function resetPointerWithWaitMsg() {
    resetWaitMsg();
    if (document.all) {
        var iLength = document.all.length;
        for (var i = 0; i < iLength; i++) {
            var obj = document.all(i);
            if (obj.style.cursor != 'hand') obj.style.cursor = '';
        }
    }
}

function showWaitMsg() {
    //alert(document.getElementById('loadingMsg'));
    loadingCount++;
    if (document.getElementById('loadingMsg') == null) {
        stopTimer();
    } else {
        document.getElementById('loadingMsg').innerHTML = 'Loading <font size=4>' + getDots(loadingCount) + '</font>';
	//document.getElementById('msg1').innerHTML='Loading ' + getDots(loadingCount);
        startTimer();
    }
}

function resetWaitMsg() {
    if(document.getElementById('loadingMsg'))
      document.getElementById('loadingMsg').innerHTML = '&nbsp;';
	//document.getElementById('msg1').innerHTML='&nbsp;';
    stopTimer();
}


//End Loading Message/////


if (document.styleSheets && document.styleSheets.length > 0) {
    for (i = 0; i < document.styleSheets[0].rules.length; i++) {
        //Right Click Menue per MouseOver per BackGround Color Change kernay kay liey... Blue or Default Theme Dono say uthata hay
        if (document.styleSheets[0].rules[i].selectorText == '.mmHighlight') {
            bg = document.styleSheets[0].rules[i].style.backgroundColor;
            clr = document.styleSheets[0].rules[i].style.color;
			//fclr=document.styleSheets[0].rules[i].style.color;
            //brdclr = document.styleSheets[0].rules[i].style.borderTopColor;
        }

    }//end for
}//end if

function MM_swapImgRestore() { //v3.0
    var i,x,a = document.MM_sr;
    for (i = 0; a && i < a.length && (x = a[i]) && x.oSrc; i++) x.src = x.oSrc;
}

function MM_preloadImages() { //v3.0
    var d = document;
    if (d.images) {
        if (!d.MM_p) d.MM_p = new Array();
        var i,j = d.MM_p.length,a = MM_preloadImages.arguments;
        for (i = 0; i < a.length; i++)
            if (a[i].indexOf("#") != 0) {
                d.MM_p[j] = new Image;
                d.MM_p[j++].src = a[i];
            }
    }
}

function MM_findObj(n, d) { //v4.01
    var p,i,x;
    if (!d) d = document;
    if ((p = n.indexOf("?")) > 0 && parent.frames.length) {
        d = parent.frames[n.substring(p + 1)].document;
        n = n.substring(0, p);
    }
    if (!(x = d[n]) && d.all) x = d.all[n];
    for (i = 0; !x && i < d.forms.length; i++) x = d.forms[i][n];
    for (i = 0; !x && d.layers && i < d.layers.length; i++) x = MM_findObj(n, d.layers[i].document);
    if (!x && d.getElementById) x = d.getElementById(n);
    return x;
}

function MM_swapImage() { //v3.0
    var i,j = 0,x,a = MM_swapImage.arguments;
    document.MM_sr = new Array;
    for (i = 0; i < (a.length - 2); i += 3)
        if ((x = MM_findObj(a[i])) != null) {
            document.MM_sr[j++] = x;
            if (!x.oSrc) x.oSrc = x.src;
            x.src = a[i + 2];
        }
}


function removeCharAt(src, charToBeRemoved, index) {
    var i = 0;
    var tmpValue = '';
    if (src.length <= index) return src;
    tmpValue = src.substring(0, index);
    tmpValue += src.substring(index + 1);
    return tmpValue;
} // end of function removeChar

function removeChar(src, charToBeRemoved) {
    var i = 0;
    var tmpValue = '';
    for (i = 0; i < src.length; i++) {
        if (src.charAt(i) != charToBeRemoved) {
            tmpValue += src.charAt(i);
        } // end of if
    } // end of for
    return tmpValue;
} // end of function removeChar

function checkDEA(dea, lastName) {
    if (!lastName) {
        return '- Please provide name to validate DEA\n';
    } // end of if

    if (dea) {
        if (dea.length != 9) {
            return '- Incorrect DEA\n';
        } // end of if
        if (dea.charAt(0) != 'A' || dea.charAt(0) != 'B') {
            return '- Incorrect DEA\n';
        } // end of if
        if (dea.charAt(1) != lastName.charAt(0)) {
            return '- Incorrect DEA\n';
        } // end of if
        if (dea.charAt(1) != lastName.charAt(0)) {
            return '- Incorrect DEA\n';
        } // end of if
        if (isNan(dea.substring(2))) {
            return '- Incorrect DEA\n';
        }
        var sum1 = parseInt(dea.charAt(2)) + parseInt(dea.charAt(4)) + parseInt(dea.charAt(6));
        var sum2 = parseInt(dea.charAt(3)) + parseInt(dea.charAt(5)) + parseInt(dea.charAt(7));
        var total = '' + (sum1 + (2 * sum2));
        if (total.charAt(total.length - 1) != dea.charAt(dea.length - 1)) {
            return '- Incorrect DEA\n';
        } // end of if
    } // end of if
    else {
        return '- Incorrect DEA\n';
    }
    return '';
} // end of function checkDEA



/**
 @author:Vicky
 Function checkEmail verifies email if required with passed with true.

 */


function checkEmail(email, required) {
    var errors = '';
    var filter = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;

    if (required) {
        if (email.length == 0)
            errors += ('- Email is required.\n');
        else if (! (filter.test(email)))
            errors += ('Invalid E-mail ID.\n');
    }
    else {
        if (email.length > 0)
            if (! (filter.test(email)))
                errors += ('- Invalid E-mail ID.\n');
    }


    return errors;


    /*
     var at="@"
     var dot="."
     var lat=email.indexOf(at)
     var lemail=email.length
     var ldot=email.indexOf(dot)

     if(required && email.length == 0) {
         errors += ('- Email is required.\n');
       }else if (email.indexOf(at)==-1){
       errors += ('- Invalid E-mail ID.\n');
     }else if (email.indexOf(at)==-1 || email.indexOf(at)==0 || email.indexOf(at)==lemail){
       errors += ('Invalid E-mail ID.\n');

     }else if (email.indexOf(dot)==-1 || email.indexOf(dot)==0 || email.indexOf(dot)==lemail){
          errors += ('Invalid E-mail ID.\n');
     }else if (email.indexOf(at,(lat+1))!=-1){
          errors += ('Invalid E-mail ID.\n');
     }else if (email.substring(lat-1,lat)==dot || email.substring(lat+1,lat+2)==dot){
          errors += ('Invalid E-mail ID.\n');

      }else if (email.indexOf(dot,(lat+2))==-1){
          errors += ('Invalid E-mail ID.\n');
      }else if (email.indexOf(" ")!=-1){
          errors += ('Invalid E-mail ID.\n');
      }

      return errors;
     */



    /*  if(required && email.length == 0) {
errors += ('- Email is required.\n');
} // end of if not provided
else if(email.length != 0 ){
if(email.length < 5) {
errors += ('- Email is incorrect.\n');
} // end of if
else if (email.indexOf('@') == -1 || email.indexOf('.') == -1) {
errors += ('- Email is incorrect.\n');
} // end of if @ sign or . sign not found
else if(email.charAt(0) == '@' || email.charAt(0) == '.') {
errors += '- Email cannot start with ' + email.charAt(0) + '.\n';
} // end of if
else if(email.charAt(email.length - 1) == '@' || email.charAt(email.length - 1) == '.') {
errors += '- Email cannot end with ' + email.charAt(0) + '.\n';
} // end of if
else if(email.indexOf('@') != email.lastIndexOf('@')){
errors += '- Email cannot have more than one @ signs.\n';
} // end of if
} // end of if not complete
else if(email.length != 0 && (email.indexOf('@') == -1 || email.indexOf('.') == -1)) {
errors += ('- Email is incorrect.\n');
} // end of if ssn is not complete*/


} // end of function checkEmail


//clean the bracket in the field value that is left Unneccessarily by spry. 
function  clearnSpryEffect(val)
{
    if( val.length == 1 )
        return "";
    else
        return val;
}


/**
 * This method checks for DOB to be less than or equal to Current Date passed as argument
 * (the reason for passing current date of server is timezone issue and client not able to change it locally )
 * It also unformats , check for number only in field and then format it again as Date
 *@ author MFB
 *created 11 APR 2007
 */

function checkDOB(currentDateString, dobField, title, required) {
    var errors = '';

    unformatDate(dobField);
    errors += checkNumber(dobField.value, title, required, 8);
    formatDate(dobField);

    if (errors == '' && dobField.value.length != 0) {
        var currentDate = getDateFromFormat(currentDateString, 'MM-dd-yyyy');
        var dob = getDateFromFormat(dobField.value, 'MM-dd-yyyy');
//	    var i=compareDate( currentDate.getYear() , currentDate.getMonth() , currentDate.getDay() , dob.getYear(), dob.getMonth() , dob.getDay());

        if (Date.parse(dob) > Date.parse(currentDate)) {
            if (title) {
                errors += '- ' + title + ' cannot be greater than current date ( ' + currentDateString + ' ) \n';
            }
            else {
                errors += '- Date of Birth cannot be greater than current date ( ' + currentDateString + ' ) \n';
            }
        }
    }
    return errors;
}

function isBeforeCurrentDate(currentDateString, dobField, title, required) {
    var errors = '';

    unformatDate(dobField);
    errors += checkNumber(dobField.value, title, required, 8);
    formatDate(dobField);

    if (errors == '' && dobField.value.length != 0) {
        var currentDate = getDateFromFormat(currentDateString, 'MM-dd-yyyy');
        var dob = getDateFromFormat(dobField.value, 'MM-dd-yyyy');
//	    var i=compareDate( currentDate.getYear() , currentDate.getMonth() , currentDate.getDay() , dob.getYear(), dob.getMonth() , dob.getDay());

        if (Date.parse(dob) > Date.parse(currentDate)) {
            if (title) {
                errors += '- ' + title + ' cannot be greater than current date ( ' + currentDateString + ' ) \n';
            }
            else {
                errors += '- Date of Birth cannot be greater than current date ( ' + currentDateString + ' ) \n';
            }
        }
    }
    return errors;
}
/**
 * This method checks for valid CPT format. It should be 5 digits and can only contain numbers
 *  & english characters. UniCode: {0,9 = 48,57} {A,Z = 65,90} {a,z = 97,122}.
 * @return
 * @author Saleem Lakhani
 * created April 26 2005
 */
function checkCPTFormat(cpt, title) {
    var errors = '';

    if (cpt == null || cpt.length <= 0 || cpt.length > 5 || cpt.length < 5) {
        errors += "- " + title + " is invalid."
        return errors;
    }
    else {
        for (i = 0; i < cpt.length; i++) {
            if (!((cpt.charCodeAt(i) >= 48 && cpt.charCodeAt(i) <= 57) || (cpt.charCodeAt(i) >= 65 && cpt.charCodeAt(i) <= 90)
                    || (cpt.charCodeAt(i) >= 97 && cpt.charCodeAt(i) <= 122))) {
                errors += "- " + title + " can only be Alphanumeric.";
                return errors;
            }
        }
    }
    return "";
}

/**
 * This method checks for valid Payment Mode No. It should contain integers (no decimal) or alphabets and * if required.
 * UniCode: {0,9 = 48,57} {A,Z = 65,90} {a,z = 97,122} , (# : 35) , {* : 42} , (, : 44) , (- : 45)
 * @return
 * @author MFB
 * created 7th Dec 2006
 */
function checkPaymentModeNo(val, title, required, length) {
    var errors = '';

    if (required && val.length == 0) {
        errors += ('- ' + title + ' is required.\n');
        return errors;
    } // end of if not provided
    else if (val.length != 0 && val.length != length && length != 0) {
        errors += ('- ' + title + ' is incomplete.\n');
        return errors;
    } // end of if not complete
    else {
        for (i = 0; i < val.length; i++) {
            if (!(
                    (val.charCodeAt(i) >= 48 && val.charCodeAt(i) <= 57) || (val.charCodeAt(i) >= 65 && val.charCodeAt(i) <= 90)
                            || (val.charCodeAt(i) >= 97 && val.charCodeAt(i) <= 122) || (val.charCodeAt(i) == 35)
                            || (val.charCodeAt(i) == 42) || (val.charCodeAt(i) == 44) || (val.charCodeAt(i) == 45)
                    )
                    ) {
                errors += "- " + title + " can only contain numbers , alphabets or ( * , # - ).";
                return errors;
            }
        }
    }
    return "";
}

function checkCreditCardNo(val, title, required, cardType) {

    var errors = '';
    var cardMaxLen = 16;
    var cardMinLen = 13;

     errors += checkNumber(val, title, required, 0);

    /*if (required && val.length == 0) {
        errors += ('- ' + title + ' is required.\n');
        return errors;
    } // end of if not provided*/


    if (val.length > cardMaxLen) {
        errors += ('- ' + title + ' length cannot be greater than ' + cardMaxLen + '.\n');
        return errors;
    }

    if (val.length < cardMinLen) {
        errors += ('- ' + title + ' length cannot be less than ' + cardMinLen + '.\n');
        return errors;
    }


   /* if (cardType && (cardType == 'M' || cardType == 'V' || cardType == 'A' ) ) {

        var creditCardRegex = '';
        var cardTypeName = '';

        if (cardType == 'M') {
            creditCardRegex = /^5[1-5]\d{14}/;
            cardTypeName = 'Master Card';
        }

        else if (cardType == 'V') {
            creditCardRegex = /^4\d{15}/;
            cardTypeName = 'VISA Card';
        }

        else if (cardType == 'A') {
                    creditCardRegex = /^3\d{14}/;
                    cardTypeName = 'American Express';
        }



        if (!( creditCardRegex.test(val) )) {
            errors += ('- ' + title + ' is not a valid ' + cardTypeName + ' No.\n');
        }
    }*/
    return errors;

}

function checkEmailWithTitle(email, title, required) {
    var errors = '';
    if (required && email.length == 0) {
        errors += ('- ' + title + ' is required.\n');
    } // end of if not provided
    else if (email.length != 0) {
        if (email.length < 5) {
            errors += ('- ' + title + ' is incorrect.\n');
        } // end of if
        else if (email.indexOf('@') == -1 || email.indexOf('.') == -1) {
            errors += ('- ' + title + ' is incorrect.\n');
        } // end of if @ sign or . sign not found
        else if (email.charAt(0) == '@' || email.charAt(0) == '.') {
            errors += '- ' + title + ' cannot start with ' + email.charAt(0) + '.\n';
        } // end of if
        else if (email.charAt(email.length - 1) == '@' || email.charAt(email.length - 1) == '.') {
            errors += '- ' + title + ' cannot end with ' + email.charAt(0) + '.\n';
        } // end of if
        else if (email.indexOf('@') != email.lastIndexOf('@')) {
            errors += '- ' + title + ' cannot have more than one @ signs.\n';
        } // end of if
    } // end of if not complete
    else if (email.length != 0 && (email.indexOf('@') == -1 || email.indexOf('.') == -1)) {
        errors += ('- ' + title + ' is incorrect.\n');
    } // end of if ssn is not complete
    return errors;
} // end of function checkEmail


/**
 * This function checks text values. It does not notify error
 * when the given values is pure text or combination of
 * characters and number. In case of pure number, this method
 * rasises and error.
 * @return error string if there is error or empty string.
 */
function checkText(txt, title, required, length) {
    var errors = ''; 
    if (required && txt.length == 0) {
        errors += ('- ' + title + ' is required.\n');
    } // end of if not provided
    else if (txt.length != 0 && txt.length != length && length != 0) {
        errors += ('- ' + title + ' is incomplete.\n');
    } // end of if not complete
    else if (txt.length != 0 && isNaN(txt) == false) {
        errors += ('- ' + title + ' cannot be a number.\n');
    } // end of if ssn is not complete
    return errors;
} // end of function checkText

/**
 * This function checks alpha numeric values. It does not notify error
 * When the given values is pure number, pure text or combination of
 * characters and number
 * @return error string if there is error or empty string.
 */

// start Add function by mr Kashif on 23rd April

function checkData(txt, title, required, length) {

    var errors = '';
    if (required && txt.length == 0) {

        errors += ('- ' + title + ' is required.\n');
    } else if (txt.length != 0 && txt.length != length && length != 0) {
        errors += ('- ' + title + ' is incomplete.\n');
    }
    return errors;
}

// End Add function by mr Kashif on 23rd April

function checkTaxonomyCode(txt, title, required, length) {

    var errors = '';
    var txtLength, lastChar;

    errors += checkAlphaNumeric(txt, title, required, length);
    if (errors.length > 1) {
        return errors;
    }
    if (txt != null && txt.length > 0) {
        txtLength = txt.length;
        lastChar = txt.substring(txtLength, txtLength - 1);
        if (lastChar != 'X' && lastChar != 'x') {
            errors += ' -' + title + ' syntax is incorrect (X should be the last character.) \n';
            return errors;
        }
    }
    return errors;
}


function checkAlphaNumericWithChar(txt, title, required, length, extChar) {


    var extCharArray = extChar.split("");
  
    var a;
    var errors = '';

    if (required && txt.length == 0) {

        errors += ('- ' + title + ' is required.\n');
    } // end of if not provided
    else if (txt.length != 0 && txt.length != length && length != 0) {
        errors += ('- ' + title + ' is incomplete.\n');
    }


    for (i = 0; i < txt.length; i++) {//Check In TextField
        if (!((txt.charCodeAt(i) >= 48 && txt.charCodeAt(i) <= 57) || (txt.charCodeAt(i) >= 65 && txt.charCodeAt(i) <= 90)
                || (txt.charCodeAt(i) >= 97 && txt.charCodeAt(i) <= 122))) {

          /////Start/////////

            for (j = 0; j < extCharArray.length; j++) { //Check in Char Array.

                if (txt.charCodeAt(i) == extCharArray[j].charCodeAt()) {
                    a = true
                    break;
                }
            }

            if (a == true) {
                a = false;
            } else {

                errors += "- " + title + " can only be Alphanumeric with these characters "+extChar+".\n";
                return errors;

            }

           /////End/////////
        }

    }

    return errors;
 //alert(extChar.charCodeAt())
}



function checkAlphaWithChar(txt, title, required, length, extChar) {


    var extCharArray = extChar.split("");

    var a;
    var errors = '';

    if (required && txt.length == 0) {

        errors += ('- ' + title + ' is required.\n');
    } // end of if not provided
    else if (txt.length != 0 && txt.length != length && length != 0) {
        errors += ('- ' + title + ' is incomplete.\n');
    }


    for (i = 0; i < txt.length; i++) {//Check In TextField
        if (!(     //(txt.charCodeAt(i) >= 48 && txt.charCodeAt(i) <= 57) ||
		   (txt.charCodeAt(i) >= 65 && txt.charCodeAt(i) <= 90) ||
		   (txt.charCodeAt(i) >= 97 && txt.charCodeAt(i) <= 122)
	     )
    	   ) {

          /////Start/////////

            for (j = 0; j < extCharArray.length; j++) { //Check in Char Array.

                if (txt.charCodeAt(i) == extCharArray[j].charCodeAt()) {
                    a = true
                    break;
                }
            }

            if (a == true) {
                a = false;
            } else {

                errors += "- " + title + " can only be Alphabets with these characters "+extChar+".\n";
                return errors;

            }

           /////End/////////
        }

    }

    return errors;
 //alert(extChar.charCodeAt())
}




function checkAlphaNumeric(txt, title, required, length) { //,getObj) {
    var errors = '';


    if (required && txt.length == 0) {
        errors += ('- ' + title + ' is required.\n');
		//getObj.focus();
    } // end of if not provided
    else if (txt.length != 0 && txt.length != length && length != 0) {
        errors += ('- ' + title + ' is incomplete.\n');
		//getObj.focus();
    }
 	// end of if not complete

    for (i = 0; i < txt.length; i++) {
        if (!((txt.charCodeAt(i) >= 48 && txt.charCodeAt(i) <= 57) || (txt.charCodeAt(i) >= 65 && txt.charCodeAt(i) <= 90)
                || (txt.charCodeAt(i) >= 97 && txt.charCodeAt(i) <= 122))) {
            errors += "- " + title + " can only be Alphanumeric.\n";
	  		//getObj.focus();
            return errors;
        }
    }
    return errors;
} // end of function checkAlphaNumeric


/**
 * This function checks alpha numeric values specially maximum value check.
 * It does not notify error when the given values is pure number, pure text or combination of
 * characters and number
 * @return error string if there is error or empty string.
 */

function checkAlphaNumericMax(txt, title, required, maxLength) {

    var errors = '';

    if (txt.length > maxLength)
    {
        errors += ('- ' + title + ' cannot exceed ' + maxLength + ' characters.\n');
    }
    else
    {
        checkAlphaNumeric(txt, title, required, 0);
        /*
      if(required && txt.length == 0) {
      errors += ('- ' + title + ' is required.\n');
        } // end of if not provided
        else if(txt.length != 0 && txt.length != length && length != 0) {
      errors += ('- ' + title + ' is incomplete.\n');
        } // end of if not complete
      */
    }
    return errors;
} // end of function checkAlphaNumericMax

function checkNPINumber(num, title, required, Requiredlength) {


    return checkNumber(num, title, required, Requiredlength);

}


function checkNumberWithChar(num, title, required, length, extChar) {
    numArr = num.split("")
    extChar = extChar.split("");
//var getErr='';
    var a;
    var errors = '';
    if (required && num.length == 0) {

        errors += ('- ' + title + ' is required.\n');
    } // end of if not provided


    for (i = 0; i < num.length; i++) {

        if (isNaN(numArr[i])) {

            /////Start/////////

            for (j = 0; j < extChar.length; j++) {

                if (num.charCodeAt(i) == extChar[j].charCodeAt()) {

                    a = true
                    break;
                }
            }

            if (a == true) {
                a = false;
            } else {

                errors += "- " + title + " can only be Number.\n";
                return errors;

            }

/////End/////////
        }

    }

    return errors;
 //alert(extChar.charCodeAt())
}


function checkNumber(num, title, required, Requiredlength) {
    var errors = '';
    if (required && num.length == 0) {
        errors += ('- ' + title + ' is required.\n');
    } // end of if not provided
    else if (isNaN(num) || num.indexOf('e') > -1 || num.indexOf('.') > -1) {
        errors += ('- ' + title + ' cannot contain characters.\n');

    } // end of if not valid
    else if (num.length != 0 && num.length != Requiredlength && Requiredlength != 0) {
        errors += ('- ' + title + ' does not have required length.\n');
    } // end of if not complete

    else if (num.length > 0) {
        for (i = 0; i < num.length; i++) {
            if ((parseInt(num.charAt(i))) > 0) {
                return errors;
            } // end of if
        } // end of for
        errors += ('- Please enter a valid ' + title + '.\n');
    }
    else if (num.charAt(0) == ' ' || num.charAt(num.length - 1) == ' ') {
        errors += ('- ' + title + ' cannot have spaces.\n');
    } // end of if
    return errors;
} // end of function checkNumber


function checkNumberMax(num, title, required, maxLength) {
    var errors = '';

    if (num.length > maxLength)
    {
        errors += ('- ' + title + ' cannot exceed ' + maxLength + ' digits.\n');
    }
    else
    {
        errors += checkNumber(num, title, required, 0);
    }
    return errors;
} // end of function checkPositiveNumberMax


function checkPositiveNumber(num, title, required, Requiredlength) {
    var errors = '';

    var regex = /^\d+$/;
    if (required && num.length == 0) {
        errors += ('- ' + title + ' is required.\n');
    } // end of if not provided
    else if (num.length != 0 && num.length != Requiredlength && Requiredlength != 0) {
        errors += ('- ' + title + ' does not have required length.\n');
    } // end of if not complete
    else if (isNaN(num) || num.indexOf('e') > -1 || num.indexOf('.') > -1 || num.indexOf('-') > -1) {
        errors += ('- ' + title + ' cannot contain characters.\n');
    } // end of if not valid
    else if (num.length > 1 && !regex.test(num)) {
        errors += ('- Please enter a valid ' + title + '.\n');
    } // end of if all zero
    else if (num.charAt(0) == ' ' || num.charAt(num.length - 1) == ' ') {
        errors += ('- ' + title + ' cannot have spaces.\n');
    } // end of if
    return errors;
} // end of function checkNumber

function checkPositiveNumberMax(num, title, required, maxLength) {
    var errors = '';

    if (num.length > maxLength)
    {
        errors += ('- ' + title + ' cannot exceed ' + maxLength + ' characters.\n');
    }
    else
    {
        checkPositiveNumber(num, title, required, 0)

        /*
      if(required && txt.length == 0) {
      errors += ('- ' + title + ' is required.\n');
        } // end of if not provided
        else if(txt.length != 0 && txt.length != length && length != 0) {
      errors += ('- ' + title + ' is incomplete.\n');
        } // end of if not complete
      */
    }
    return errors;
} // end of function checkPositiveNumberMax


function checkSSN(ssn, required) {
    var errors = '';
    if (required && ssn.length == 0) {
        errors += '- SSN is required.\n';
    } // end of if not provided
    else if (ssn.length != 0 && ssn.length != 9) {
        errors += '- SSN should be of nine digits.\n';
    } // end of if ssn is not complete
    else if (isNaN(ssn) || ssn.indexOf('e') > -1 || ssn.indexOf('-') > -1 || ssn.indexOf('.') > -1) {
        errors += '- SSN cannot contain characters or spaces.\n';
    } // end of if ssn is not complete

        //else if(parseInt(ssn) == 0) {
        //  errors+='- Please enter a valid SSN.\n';
        //}

    else if (ssn.charAt(0) == ' ' || ssn.charAt(ssn.length - 1) == ' ') {
        errors += '- SSN can neither start or end with spaces nor contain spaces.\n';
    }
    else if (ssn.length > 0) {
        for (i = 0; i < ssn.length; i++) {
            if ((parseInt(ssn.charAt(i))) > 0) {
                return errors;
            } // end of if
        } // end of for
        errors += '- Please enter a valid SSN.\n';
    }

    return errors;
} // end of function checkSSN

function checkZip(zip, required) {
    var errors = '';
    var zip1 = zip.substring(0, 5);
    var zip2 = '';
    if (zip.length > 6) {
        zip2 = zip.substring(6);
    } //end of if zip has last four digits as well
    if (required && zip.length == 0) {
        errors += '- Zip is required.\n';
    } // end of if zip is required
    else if (zip.indexOf(' ') != -1) {
        errors += '- Zip cannot contain spaces.\n';
    }
    else if (zip.length != 0 && zip.length != 5 && zip.length != 10) {
        errors += '- Zip Code can either be of 5 digits or 5 + 4 digits.\n';
    } // end of if
    else if (zip.length > 5 && zip.charAt(5) != '-') {
        errors += '- Zip Code is not correct.\n';
    }
    else if (zip.length <= 5 && zip.indexOf('-') != -1) {
        errors += '- Zip Code is not correct.\n';
    }
    else if (isNaN(zip1)) {
        errors += '- Zip Code is not correct.\n';
    } // end of if
    else if (isNaN(zip2)) {
        errors += '- Zip Code is not correct.\n';
    } // end of if
    return errors;
} // end of function checkZip

function checkZipWithTitle(zip, title, required) {
    var errors = '';
    var zip1 = zip.substring(0, 5);
    var zip2 = '';
    if (zip.length > 6) {
        zip2 = zip.substring(6);
    } //end of if zip has last four digits as well
    if (required && zip.length == 0) {
        errors += '- ' + title + ' is required.\n';
    } // end of if zip is required
    else if (zip.indexOf(' ') != -1) {
        errors += '- ' + title + ' cannot contain spaces.\n';
    }
    else if (zip.length != 0 && zip.length != 5 && zip.length != 10) {
        errors += '- ' + title + ' can either be of 5 digits or 5 + 4 digits.\n';
    } // end of if
    else if (zip.length > 5 && zip.charAt(5) != '-') {
        errors += '- ' + title + ' is not correct.\n';
    } else if (zip.length <= 5 && zip.indexOf('-') != -1) {
        errors += '- ' + title + ' is not correct.\n';
    }
    else if (isNaN(zip1)) {
        errors += '- ' + title + ' is not correct.\n';
    } // end of if
    else if (isNaN(zip2)) {
        errors += '- ' + title + ' is not correct.\n';
    } // end of if
    return errors;
} // end of function checkZip


function checkRequired(val, title) {
    var errors = '';
    if (!val || val.length == 0) {
        errors += '- ' + title + ' is required.\n';
    } // end of function checkRequired
    return errors;
}

function autoTab(source, dest, len) {
    if (source.value.length >= len) {
        dest.focus();
    } // end of if
} // end of function autoTab

function isNumeric(sText)
{
    var ValidChars = "0123456789.";
    var IsNumber = true;
    var Char;
    for (i = 0; i < sText.length && IsNumber == true; i++)
    {
        Char = sText.charAt(i);
        if (ValidChars.indexOf(Char) == -1)
        {
            IsNumber = false;
        }
    }
    return IsNumber;

}
/**
 * This method checks whether the given value is empty string or not.
 * @return message string if empty. Otherwise returns zero length string.
 */
function checkEmpty(val, title) {
    var errors = '';
    var i = 0;
    if (val == null || val.length < 1) {
        errors = "- " + title + " cannot be empty.\n";
    } // end of if
    else {                                      
        for (i = 0; i < val.length; i++) {
            if (val.charAt(i) == ' ') {
                val = val.substring(1);
            } // end of if
            else {
                break;
            } // end of if
        } // end of for

        if (val.length < 1) {
            errors = "- " + title + " cannot contain spaces only.\n";
        } // end of if

    } // end of else

    return errors;
} // end of function checkEmpty

/*
This method removes the spaces at the start and at the end of the given
text and returns the remaining text.
@author Ali Ahsan

function trim(src){
  var errors ='';
  var i = 0;
  if(src != null && src.length > 0) {
    while(src.charAt(0) == ' ' || src.charAt(src.length - 1) == ' ') {
      if(src.charAt(0) == ' '){
        src = src.substring(1);
      } // end of if
      if(src.charAt(src.length - 1) == ' '){
        src = src.substring(0, src.length - 1);
      } // end of if
    } // end of while
  } // end of if
  return src;
} // end of function checkEmpty
*/

/**
 * This method trims a string much faster using regular expressions
 * @author Faisal Moin Khan
 * @created on 4th January 2005
 */
function trim(s)
{
    //regex explanation:
    //regex is in forward slashes:  //
    // syntax  string = string.replace(/pattern/, 'replace with this');

    //    ^        = beginning of line
    //    (\s+)?   = one or more characters of whitespace, optional
    //    (.*\S)   = any characters, with the last one not being whitespace

    //    (\s+)?   = one or more characters of whitespace, optional
    //    $        = end of line
    //    $2       = what was in the 2nd set of parenthesis
    return isEmpty(s) ? '' : s.replace(/^(\s+)?(.*\S)(\s+)?$/, '$2');
}


function checkTeleNo(areacode, phone2, phone3, ext, title, isReq, phone) {
    var errors = '';
    errors += checkPositiveNumber(areacode + phone2 + phone3, title, isReq, 10);

    if (!errors) {

        errors += checkPositiveNumber(ext, title, false, 0);

    } // end of if

    if (!errors) {

        phone.value = areacode + phone2 + phone3;

        if (ext) {

            phone.value += ':' + ext;
        }
    } // end of if
    return errors;
} // end of function checkTeleNo

function checkPagerNo(pager1, pager2, pager3, pager4, title, isReq, pager) {
    var errors = '';
    var tmp = pager1 + pager2 + pager3 + pager4;
    pager.value = "";
    errors = checkPositiveNumber(tmp, title, isReq, 17);
    if (!errors) {
        pager.value = tmp;
    } // end of if
    return errors;
} // end of function checkPagerNo



/**
 * this method check specialText like Login and Password
 * it takes 4 parametres Field ,Title, Minimum Length , Maximum Length
 */
function checkSpecialText(txt, title, minLength, maxLength) {
    var errors = '';
    if (txt.length == 0) {
        errors += '- ' + title + ' is required.\n';
        return errors;
    }
    if (txt.length < minLength) {
        errors += '- ' + title + ' should be ' + minLength + '-' + maxLength + ' characters\n';
        return errors;
    }
    if (txt.length > maxLength) {
        errors += '- ' + title + ' should be ' + minLength + '-' + maxLength + ' characters\n';
    }
    return errors;
} // end of function checkSpecialText

function fillNumbersInList(lst, start, end, selectedIndex, selectedValue) {
    var i = 0;
    var index = 0;
    var opt = null;
    for (i = start; i <= end; i++) {
        opt = new Option(i, i, false);
        lst.options[lst.options.length] = opt;
    } // end of for
    if (selectedIndex > -1) {
        lst.value = lst.options[selectedIndex].value;
    } // end of if
    else {
        lst.value = selectedValue;
    } // end of if
} // end of function

/**
 * This function removes all the options from the given HTML select list.
 */
function clearList(lst) {
    if (isList(lst) == false) {
        return;
    } // end of if
    if (lst == null || lst.options == null) {
        alert(lst.type);
        return;
    } // end of if
    var i = 0;
    for (i = lst.options.length; i > 0; i--) {
        lst.options[i - 1] = null;
    } // end of for
} // end of fuction clearList

/**
 * This function inserts the selected options of source list in destination
 * list. If the duplicate argument is true, it inserts all the selected
 * options of source list in destination list.
 * If the duplicate argument is false, it does not inserts selected option
 * of source list whose values is already a value of one of the destination
 * list options.
 */
function addToListFromList(src, dest, duplicate) {
    //modified by Faisal Moin Khan on 4th Nov
    //storing the state of destination list, so that
    //new icds could be searched in this list, rather than searching in dest list each time
    //which was making the process slow
    var tempDestList = dest;
  //alert(tempDestList.options.length);
    if (isList(src) == false || isList(dest) == false) {
        return '- Invalid parameters to function addToListFromList';
    } // end of if
    var i = 0;
    var opt = null;
    if (duplicate) {
        for (i = 0; i < src.options.length; i++) {
            if (src.options[i].selected == true) {
                opt = new Option(src.options[i].text, src.options[i].value, false);
                dest.options[dest.options.length] = opt;
            } // end of if
        } // end of for
    } // end of if duplicate values are allowed.
    else {
        for (i = 0; i < src.options.length; i++) {
            //searching in tempDetList for duplicates
            if (src.options[i].selected == true && isListOption(tempDestList, src.options[i].value) == false) {
                opt = new Option(src.options[i].text, src.options[i].value, false);
                dest.options[dest.options.length] = opt;
            } // end of if
        } // end of for
    } // end of if duplicate values are not allowed.
} // end of function addToListFromList


/**
 * @desc This function inserts the selected options of source list and selected
 * value send from second list (attrib) in destinationlist. If the duplicate
 * argument is true, it inserts all the selected options of source list in
 * destination list. If the duplicate argument is false, it does not inserts
 * selected option of source list whose values is already a value of one of
 * the destination list options.
 * @author Yasir Qureshi
 */
function addToListFromLists(src, dest, attrib, duplicate) {

    var i = 0;
    var opt = null;

    if (isList(src) == false || isList(dest) == false) {
        return '- Invalid parameters to function addToListFromList';
    } // end of if

    if (duplicate) {
        for (i = 0; i < src.options.length; i++) {
            if (src.options[i].selected == true) {
                opt = new Option(attrib + " " + src.options[i].text, attrib + " " + src.options[i].value, false);
                dest.options[dest.options.length] = opt;
            } // end of if
        } // end of for
    } // end of if duplicate values are allowed.

    else {
        for (i = 0; i < src.options.length; i++) {
            if (src.options[i].selected == true && isListOption(dest, attrib + " " + src.options[i].value) == false) {
                opt = new Option(attrib + " " + src.options[i].text, attrib + " " + src.options[i].value, false);
                dest.options[dest.options.length] = opt;
            } // end of if
        } // end of for
    } // end of if duplicate values are not allowed.
} // end of function addToListFromList

/**
 * @desc This function inserts the selected options of source lists in destinationlist.
 * If the duplicate argument is true, it inserts all the selected options of
 * source list in destination list. If the duplicate argument is false, it does
 * not inserts selected option of source list whose values is already a value
 * of one of the destination list options.
 * @author Yasir Qureshi
 */
function addToListFromMulitplieList(srcLists, dest, separator, duplicate) {
    var i = 0;
    j = 0;
    var opt = null;
    var destText = "";

    for (i = 0; i < srcLists.length; i++) {
        if (isList(srcLists[i]) == false || isList(dest) == false) {
            return '- Invalid parameters to function addToListFromList';
        }  // end of if
    } // end for

    if (duplicate) {
        for (i = 0; i < srcLists.length; i++) {
            for (j = 0; j < srcLists[i].options.length; j++) {
                if (srcLists[i].options[j].selected == true) {
                    if (destText == "") {
                        destText = srcLists[i].options[j].value;
                    }
                    else {
                        destText = destText + separator + srcLists[i].options[j].value;
                    }
                }
            } // end of if
        } // end of for
        opt = new Option(destText, destText, false);
        dest.options[dest.options.length] = opt;
    } // end of if duplicate values are allowed.

    else {
        for (i = 0; i < srcLists.length; i++) {
            for (j = 0; j < srcLists[i].options.length; j++) {
                if (srcLists[i].options[j].selected == true) {
                    if (destText == "") {
                        destText = srcLists[i].options[j].value;
                    }
                    else {
                        destText = destText + separator + srcLists[i].options[j].value;
                    }
                }
            } // end of if
        } // end of for
        if (isListOption(dest, destText) == false) {
            opt = new Option(destText, destText, false);
            dest.options[dest.options.length] = opt;
        } // end of if
    } // end if duplicates not allowed
} // end of function addToListFromList

/**
 * This function inserts the selected options of source list in destination
 * list. If the duplicate argument is true, it inserts all the selected
 * options of source list in destination list.
 * If the duplicate argument is false, it does not inserts selected option
 * of source list whose values is already a value of one of the destination
 * list options.
 */


/**
 * This function returns true if the given val is value of any of the options
 * of the src list. Otherwise, it returns false.
 */
function isListOption(src, val) {
    if (isList(src) == false || val == null || val == '') {
        return false;
    } // end of if
    var i = 0;
    for (i = 0; i < src.options.length; i++) {
        if (src.options[i].value == val) {
            return true;
        } // end of if
    } // end of for
    return false;
} // end of function isListOption


/**
 * This function adds the given text and value in the give list as an option.
 * If selected is true, then this method sets this option as selected.
 */
function addToList(lst, text, val, selected, duplicate, insertEmpty) {
    if (isList(lst) == false) {
        return '- Invalids parameter to function addToList';
    } // end of if
    if ((text == '' || val == '') && !insertEmpty) {
        return '- Please enter some thing to add.';
    } // end of if
    if (duplicate == false && isListOption(lst, val) == true) {
        return '- Value already exists.';
    } // end of if

    var opt = new Option(text, val, selected);
    lst.options[lst.options.length] = opt;
} // end of function addToListFromList

/*
method populates a list with array values
author aqeela
*/
function addArrayToList(lst, values) {
    for (i = 0; i < values.length; i++) {
        addToList(lst, values[i][1], values[i][0], values[i][2], true, true)
    }
} // end of function addToListFromList


/**
 * This function removes the selected options of the given list
 */
function removeSelectedFromList(src) {

    if (isList(src) == false) {
        return;
    } // end of if
    var i = 0;
    for (i = src.length; i > 0; i--) {
        if (src.options[i - 1].selected == true) {
            src.options[i - 1] = null;
        } // end of if selected
    } // end of for
} // end of function removeSelectedFromList

/**
 * This function removes all options of the given list whose value is equal
 * to the given value
 */
function removeFromList(src, val) {
    if (isList(src) == false) {
        return;
    } // end of if
    var i = 0;
    for (i = src.length; i > 0; i--) {
        src.options[i - 1] = null;
    } // end of for
} // end of function removeFromList

/**
 * This function returns true if the given control is HTML list.
 * Otherwise it returns false
 */
function isList(src) {
    if (src == null || (src.type != 'select-multiple' && src.type != 'select-one')) {
        return false;
    } // end of if
    return true;
} // end of function isList

/**
 * This method selects all the options of the given list
 */
function selectAllOptions(src) {
    if (isList(src) == false) {
        return;
    } // end of if
    var i = 0;
    for (i = 0; i < src.options.length; i++) {
        src.options[i].selected = true;
    } // end of for
} // end of function selectAllOptions

/**
 * This method deselects all the options of the given list
 */
function deselectAllOptions(src) {
    if (isList(src) == false) {
        return;
    } // end of if
    var i = 0;
    for (i = 0; i < src.options.length; i++) {
        src.options[i].selected = false;
    } // end of for
} // end of function deselectAllOptions

/**
 * This method selects all options in the passed select list
 */
function selectAllInList(src) {
    for (i = 0; i < src.options.length; i++) {
        src.options[i].selected = true;
    }
}

function isDate(dt) {
    return true;
} // end of if

/*

month passed should be 0-11
*/
function checkDate(year, month, day, text) {
    var date = new Date(year, month, day);
//  alert(month + " : " + date.getMonth());
    //  alert(day + " : " + date.getDate());
    //  alert(date.toString());
    if (date.getMonth() != month || date.getDate() != day) {
        if (text) {
            return '- ' + text + ' is not valid.\n';
        }
        else {
            return '- Date is not valid.\n';
        }
    }
    return '';
} // end of function

function validateDate(year, month, day, text) {
    var date = new Date(year, month, day);
//  alert(month + " : " + date.getMonth());
    //  alert(day + " : " + date.getDate());
    //  alert(date.toString());
    if (date.getMonth() != month || date.getDate() != day) {
        if (text) {
            return '- ' + text + ' is not valid.\n';
        }
        else {
            return '- Date is not valid.\n';
        }
    }
    return '';
} // end of function

/*
  Checks the given date string in the format yyyy-MM-dd
*/
function checkDateInFull(date, title, required) {


    if (date.length == 0) {
        if (required == true) {
            return "- " + title + " is required.\n";
        } // end of if
        else {
            return "";
        } // end of if
    } // end of if
    if (date.length < 8) {
        return '- ' + title + ' is not valid.\n';
    } // end of if

    var dateParts = date.split("-");
    if (dateParts == null || dateParts.length != 3) {
        return '- ' + title + ' is not valid.\n';
    } // end of if
    if (dateParts[0].length != 4) {
        return '- ' + title + ' is not valid.\n';
    } // end of if

    var tmpMonth = 0;
    var tmpDay = 0;
    var tmpYear = parseInt(dateParts[0]);
    if (dateParts[1].length == 2 && dateParts[1].charAt(0) == "0") {
        tmpMonth = parseInt(dateParts[1].charAt(1));
    }
    else {
        tmpMonth = parseInt(dateParts[1]);
    } // end of else
    tmpMonth = tmpMonth - 1;
    if (dateParts[2].length == 2 && dateParts[2].charAt(0) == "0") {
        tmpDay = parseInt(dateParts[2].charAt(1));
    }
    else {
        tmpDay = parseInt(dateParts[2]);
    } // end of else
    var tmpDate = new Date(tmpYear, tmpMonth, tmpDay);
    if (tmpDate.getMonth() != tmpMonth || tmpDate.getDate() != tmpDay) {
        if (title) {
            return '- ' + title + ' is not valid.\n';
        }
        else {
            return '- Date is not valid.\n';
        }
    }
    return '';
} // end of function checkDateInFull



/*
This method compares dates
If date1 > date2 it returns 1
If date1 < date2 it returns -1
If date1 = date2 it returns 0
*/
function compareDate(year1, month1, day1, year2, month2, day2)
{
    var date1 = new Date(year1, month1, day1);
    var date2 = new Date(year2, month2, day2);

    if (( (date1.getTime() - date2.getTime()) < 0)) {
        return -1;
    }
    else if (( (date1.getTime() - date2.getTime()) > 0)) {
        return 1;
    }
    else if (( (date1.getTime() - date2.getTime()) == 0)) {
        return 0;
    }

    return '';

}

/*
this method will compare two dates and return error if date1
is greater than date 2 else return empty string.
*/
function checkDateBeforeOrEqual(year1, month1, day1, year2, month2, day2, name1, name2) {
    var errors = '';
    var i = compareDate(year1, month1, day1, year2, month2, day2);
    if (i == 1) {
        errors += ('- ' + name2 + ' cannot be less than ' + name1 + '\n');
    }
    return errors;
} // end of method checkDateBefore

/*
this method will compare two dates and return error if date1
is less than date 2 else return empty string.
*/
function checkDateAfterOrEqual(year1, month1, day1, year2, month2, day2, name1, name2) {
    var errors = '';
    var i = compareDate(year1, month1, day1, year2, month2, day2);
    if (i == -1) {
        errors += ('- ' + name2 + ' cannot be greater than ' + name1 + '\n');
    }
    return errors;
} // end of method checkDateAfterOrEqual

/*
this method will compare two dates and return error if date1
is not equal date 2 else return empty string.
*/
function checkDateEqual(year1, month1, day1, year2, month2, day2, name1, name2) {
    var errors = '';
    var i = compareDate(year1, month1, day1, year2, month2, day2);
    if (i == 0) {
        errors += ('- ' + name1 + ' should be equal to ' + name2 + '\n');
    }
    return errors;
} // end of method checkDateEqual


function checkFloat(num, title, required, Requiredlength) {
    var errors = '';
    if (required && num.length == 0) {
        errors += ('- ' + title + ' is required.\n');
    } // end of if not provided
    else if (num.length != 0 && num.length != Requiredlength && Requiredlength != 0) {
        errors += ('- ' + title + ' does not have required length.\n');
    } // end of if not complete
    else if (isNaN(num) || num.indexOf('e') > -1) {
        errors += ('- ' + title + ' cannot contain characters.\n');
    } // end of if not valid
    else if (num.charAt(0) == ' ' || num.charAt(num.length - 1) == ' ') {
        errors += ('- ' + title + ' cannot have spaces.\n');
    } // end of if


    return errors;
} // end of function checkFloat


function checkPositiveFloat(num, title, required, Requiredlength) {
    var errors = '';
    if (required && num.length == 0) {
        errors += ('- ' + title + ' is required.\n');
    } // end of if not provided
    else if (num.length != 0 && num.length != Requiredlength && Requiredlength != 0) {
        errors += ('- ' + title + ' does not have required length.\n');
    } // end of if not complete
    else if (isNaN(num) || num.indexOf('e') > -1 || num.indexOf('-') > -1) {
        errors += ('- ' + title + ' cannot contain characters.\n');
    } // end of if not valid
    else if (num.charAt(0) == ' ' || num.charAt(num.length - 1) == ' ') {
        errors += ('- ' + title + ' cannot have spaces.\n');
    } // end of if
    return errors;
} // end of function checkPositiveFloat


function checkFloatRange(num, title, required, Requiredlength, minValue, maxValue, precision) {
    var errors = '';
    if (required && num.length == 0) {
        errors += ('- ' + title + ' is required.\n');
    } // end of if not provided
    else if (num.length != 0 && num.length != Requiredlength && Requiredlength != 0) {
        errors += ('- ' + title + ' does not have required length.\n');
    } // end of if not complete
    else if (isNaN(num) || num.indexOf('e') > -1 || num.indexOf('-') > 0) {
        errors += ('- ' + title + ' cannot contain characters.\n');
    } // end of if not valid
    else if (num.charAt(0) == ' ' || num.charAt(num.length - 1) == ' ') {
        errors += ('- ' + title + ' cannot contain spaces.\n');
    } // end of if
    else if (parseFloat(num) < minValue) {
        errors += ('- ' + title + ' should be greater than or equal to ' + minValue + '.\n');
    } // end of if

    else if (parseFloat(num) > maxValue) {
        errors += ('- ' + title + ' should be less than or equal to ' + maxValue + '.\n');
    } // end of if

    else if (precision > -1 && num.indexOf('.') > -1 && (num.length - (num.indexOf('.') + 1) > precision)) {
        errors += ('- Only ' + precision + ' digits are allowed for ' + title + ' precision.\n');
    } // end of if

    return errors;
} // end of function checkFloatRange

// thie method will check the Precision of Float
function checkFloatpPrecision(num, title, precision) {
    var errors = '';
    if (precision > -1 && num.indexOf('.') > -1 && (num.length - (num.indexOf('.') + 1) > precision)) {
        errors += ('- Only ' + precision + ' precision digits are allowed for ' + title + '.\n');
    } // end of if
    return errors;
} // end of function checkFloatpPrecision


function checkAmount(num, title, required, Requiredlength, minValue, maxValue, precision) {
    var errors = '';
	//checkFloatpPrecision(num,title,precision);
    if (precision > -1 && num.indexOf('.') > -1 && (num.length - (num.indexOf('.') + 1) > precision)) {
        errors += ('- Only ' + precision + ' precision digits are allowed for ' + title + '.\n');
        return errors;

    }

    return checkFloatRange(num, title, required, Requiredlength, minValue, maxValue, precision);
}

/**
 * Opens Patient Alert Screen
 * @return
 */
function openPatientAlerts(patId, pracId) {
    // setting the following parameters to display the popup in center
    var url = "/apolloweb/popup/viewPatientAlerts.do?displayMenu=false&patientId=" + patId + "&practiceId=" + pracId;
    var pxOffset = 00;
    var pyOffset = 00;
    var wnd = window.open(url, "Alerts", "toolbar=n,location=n,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,width=550,height=240,screenX=" + pxOffset + ",screenY=" + pyOffset + ",top=" + pyOffset + ",left=" + pxOffset);
    wnd.focus();
} // end of function patientReferral




/**
 * this method removes trailing spaces, from the textbox
 * @return
 * @author Saleem Lakhani
 */
function removeTrailingSpaces(textBox) {
    while ('' + textBox.value.charAt(0) == ' ') {
        textBox.value = textBox.value.substring(1, textBox.value.length);
    }
}

/**
 * this method removes leading and traling spaces of a string and returns
 * @return
 * @author Aqeela Hemani
 */

function trimString(str) {
    var strLength = str.length;
    var begin = 0;
    var end = str.length - 1;
    while (begin < strLength && str.charAt(begin) == ' ') {
        begin ++;
    }
    if (begin == strLength) {
        return '';
    }

    while (str.charAt(end) == ' ' && end > 0) {
        end --;
    }

    return str.substring(begin, end + 1);
}

/**
 * this method searches for a text in the select list. it matches the
 * text starting with the passed value
 * @return
 * @author Saleem Lakhani
 */
function searchInSelectList(list1, val) {

    for (i = 0; i < list1.options.length; i++) {
        if (String(list1.options[i].text).substring(0, val.length).toUpperCase().indexOf(val.toUpperCase()) > -1) {
            list1.options[i].selected = true;
            return;
        }
    }//for
}

function checkMaxLength(control, len) {
    if (control.value.length > len) {
        control.value = control.value.substring(0, len);
    } // end of if
} // end of function checkMaxLength


/**
 * This method selects all Checkboxes for the given src
 * @author Kazim
 */
function toggleCheckBoxes(src, checked) {
    if (src != null) {
        if (!src.length) {
            src.checked = checked;
        } else {
            for (i = 0; i < src.length; i++) {
                src[i].checked = checked;
            }
        } // end of if
    } // end of if
}

/**
 * This method selects all Checkboxes for the given src
 * @author Kazim
 */
function checkAll(src) {
    if (src != null) {
        if (!src.length) {
            src.checked = true;
        } else {
            for (i = 0; i < src.length; i++) {
                src[i].checked = true;
            }
        } // end of if
    } // end of if
}

function uncheckAll(src) {
    if (src != null) {
        if (!src.length) {
            src.checked = false;
        } else {
            for (i = 0; i < src.length; i++) {
                src[i].checked = false;
            }
        } // end of if
    } // end of if
}


function showTemplate(templateId, parameterValue, parameterName) {
    var pxOffset = 300;
    var pyOffset = ((screen.availHeight - 450) / 1);
    var div = parseInt(templateId / 1000);
    var url = "/apolloweb/templates/" + templateId + ".tp";
    url += "?parameterName=" + parameterName;
    url += "&parameterValue=" + parameterValue;

    var wnd = window.open(url, "", "toolbar=n,location=n,directories=no,status=no,menubar=no,scrollbars=yes,resizable=no,width=500,height=400,screenX=" + pxOffset + ",screenY=" + pyOffset + ",top=" + pyOffset + ",left=" + pxOffset);
}

// This method returns the num rounded to decimalPlaces
// @author Aqeela Hemani
function roundOff(num, decimalPlaces) {
    val = Math.pow(10, decimalPlaces);
    return Math.round(num * val) / val;
}


// This method returns the num truncates to specified decimalPlaces
// @author Aqeela Hemani
function truncateFloat(num, decimalPlaces) {
    var val = String(num);
    var i = val.indexOf(".");
    var l = val.length;
    var str = "";

    if (i < 0) {
        for (j = 0; j < decimalPlaces; j++) {
            str += "0";
        }

        return (val + "." + str);
    }
    else {
        if ((l - i - 1) > decimalPlaces) {
            return val.substr(0, i + 1 + decimalPlaces);
        }
        else if ((l - i - 1) < decimalPlaces) {
            while (val.length < i + decimalPlaces + 1) {
                val = val + "0";
            }
            return val;
        }
        else {
            return val;
        }
    }
}

function checkSpecialCharacters(text, title, required) {
    var errors = '';
    if (required && text.length == 0) {
        errors += ('- ' + title + ' is required.\n');
    } // end of if not provided
    else if (text.length != 0) {
        if (text.indexOf('@') != -1 || text.indexOf('.') != -1 || text.indexOf('"') != -1 || text.indexOf("'") != -1) {
            errors += ('- ' + title + ' cannot contain special characters.\n');
        }
    } // end of else
    return errors;
} // end of function

/**
 * Sets "checked = true" of the <code>radioName</code> element of
 * <code>frm</code> if its value is equal to <code>radioValue</code>.
 */
function selectRadio(frm, radioName, radioValue) {
    var i = 0;
    var half = frm.elements.length / 2;
    var length = frm.elements.length - 1;

    for (i = 0; i < half; i++) {
        if (frm.elements[i].name == radioName && frm.elements[i].value == radioValue) {
            frm.elements[i].checked = true;
            break;
        } // end of if
        if (frm.elements[length - i].name == radioName && frm.elements[length - i].value == radioValue) {
            frm.elements[length - i].checked = true;
            break;
        } // end of if
    } // end of if
} // end of function selectRadio



// set the radio button with the given value as being checked
// do nothing if there are no radio buttons
// if the given value does not exist, all the radio buttons
// are reset to unchecked
// copied from http://www.somacon.com/p143.php by MFB
function setRadioButtonValue(frm,radioObj, newValue) {
	if(!radioObj)
		return;
	var radioLength = radioObj.length;
	if(radioLength == undefined) {
		radioObj.checked = (radioObj.value == newValue.toString());
		return;
	}
	for(var i = 0; i < radioLength; i++) {
		radioObj[i].checked = false;
		if(radioObj[i].value == newValue.toString()) {
			radioObj[i].checked = true;
		}
	}
}

function setRadioButtonVal(frm,radioObj, newValue) {
	if(!radioObj)
		return;
	var radioLength = radioObj.length;

	for(var i = 0; i < radioLength; i++) {

		if( radioObj[i].checked ) 
		{
		    radioObj[i].value = newValue;
 		    break;
		}
	}
}

/**
 * This function returns the value of checked radio element in the given form
 * with the given name.
 * @author Ali Ahsan
 */
function getSelectedRadioValue(frm, radioName) {
    return getCheckedValue(frm, radioName, "radio");
} // end of function getSelectedRadioValue

/**
 * This function returns the value of checked checkbox element in the given form
 * with the given name.
 * @author Ali Ahsan
 */
function getSelectedCheckboxValue(frm, checkboxName) {
    return getCheckedValue(frm, checkboxName, "checkbox");
} // end of function getSelectedRadioValue

/**
 * This function returns the value of first checked element (radio or checkbox)
 * in the given form with the given name.
 * @author Ali Ahsan
 */
function getCheckedValue(frm, radioName, typeName) {
    var i = 0;
    var val = '';
    if (frm) {
        for (i = 0; i < frm.elements.length; i++) {
            if (frm.elements[i].name == radioName && frm.elements[i].type == typeName) {
                if (frm.elements[i].checked == true) {
                    val = frm.elements[i].value;
                    break;
                } // end of if
            } // end of if
        } // end of for
    }
    return val;
} // end of function getSelectedRadioValue

/**
 * This function returns all the values of checked elements of checkbox
 * in the given form with the given name. The returned values are in the form
 * of a string separating the values with '@' sign. The user can get an array
 * of values by using split function on this returned string.
 * @author Ali Ahsan
 */
function getCheckedValues(frm, checkboxName) {
    var i = 0;
    var val = "";
    if (frm) {
        for (i = 0; i < frm.elements.length; i++) {
            if (frm.elements[i].name == checkboxName && frm.elements[i].type == 'checkbox') {
                if (frm.elements[i].checked == true) {
                    if (val) {
                        val = val + "@";
                    } // end of if
                    val = val + frm.elements[i].value;
                    break;
                } // end of if
            } // end of if
        } // end of for
    }
    return val;
} // end of function getSelectedRadioValue

/**
 * Prints names of all the elements in the given form on the given text control.
 */
function formFieldNames(frm, element) {
    var i = 0;
    for (i = 0; i < frm.elements.length; i++) {
        element.value = element.value + frm.elements[i].name + "\n";
    } // end of for
} // end of function formFieldNames

/**
 * Sets the value of given array of text control names in the given form to
 * empty string.
 */
function clearTextControls(frm, controlNames) {
    var i = 0;
    for (i = 0; i < controlNames.length; i++) {
        eval("frm." + controlNames[i] + ".value = ''");
    } // end of for
} // end of function

/**
 * Enables or disables the given array of control names in the given form
 * based on the given boolean value.
 * @return
 */
function enableControls(frm, controlNames, enable) {
    var i = 0;
    for (i = 0; i < controlNames.length; i++) {
        eval("frm." + controlNames[i] + ".disabled = " + !enable);
    } // end of for
} // end of function

/**
 * This method will check the text that if the required length
 * of word in text greater than length , then this will return
 * error , otherwise no error
 * @return
 */
function checkWordsLengthInText(txt, title, length, required) {

    var errors = '';

    if (required && txt.length == 0) {
        errors += ('- ' + title + ' is required.\n');
    } // end of if not provided


    while (txt.length > 0) {
        var index = txt.indexOf(' ');
        var word = txt;
        if (index != -1) {
            word = txt.substring(0, index);
        }
        txt = txt.substring(index + 1, txt.length);
        if (word.length > length) {
            errors += ('- Please decrease the length of ' + word + ' to ' + length + ' characters.\n');
        }
        if (index == -1) {
            break;
        }
    } // end of while

    return errors;
}

function getCheckedCount(frm, controlName) {
    var checkCount = 0;
    var i = 0;
    var elements = frm.elements[controlName];

    if (elements) {
        if (elements.length) {
            for (i = 0; i < elements.length; i++) {
                if (elements[i].type == "checkbox" && elements[i].checked == true) {
                    checkCount++;
                } // end of if
            }// end of for
        }// end of if
        else if (elements.checked) {
            checkCount ++;
        }
    }

    /*for(i = 0; i < frm.elements.length; i++) {
      if(frm.elements[i].type == "checkbox"
         && frm.elements[i].name == controlName
         && frm.elements[i].checked == true) {

        checkCount++;

      } // end of if
    } // end of for
    */

    return checkCount;
} // end of function getCheckedCount


/*author Aqeela
This method retuns date in default mmm-dd-yyyy format
*/
function getFormatedDate(month, day, year, format) {

    if (!(month > 0 && day > 0 & year > 0 )) {
        return  '';
    }
    if (!format) {
        format = "mmm-dd-yyyy";
    }

    var months = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
    var formatedDate = "";

    if (format.toLowerCase() == "mmm-dd-yyyy") {
        formatedDate = months[month - 1];
        formatedDate += "-" + (day < 10 ? '0' + day : '' + day);
        formatedDate += "-" + year;
    }
    else if (format.toLowerCase() == "yyyy-mm-dd") {
        formatedDate += year;
        formatedDate += "-" + (month < 10 ? '0' + month : '' + month);
        formatedDate += "-" + (day < 10 ? '0' + day : '' + day);
    }
    else if (format.toLowerCase() == "mm-dd-yyyy") {
        formatedDate += (month < 10 ? '0' + month : '' + month);
        formatedDate += "-" + (day < 10 ? '0' + day : '' + day);
        formatedDate += "-" + year;

    }

    return formatedDate;
}

/*
sets month, day and year control
format should be yyyy-mm-dd
*/
function fillDate(date, month, day, year, format) {
    if (date.length == 0) {
        if (month.type && month.type == "select-one") {
            year.selectedIndex = 0;
            month.selectedIndex = 0;
            day.selectedIndex = 0;
        }
        else {
            year.value = "";
            month.value = "";
            day.value = "";
        }
    }
    /*if(!format){
  format = "mmm-dd-yyyy";
 }
 var months = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
 var formatedDate = "";*/
    if (!format) {
        format = "yyyy-mm-dd";
    }
    var dateComponents = date.split("-");
    if (format == "yyyy-mm-dd") {
        year.value = dateComponents[0];
        var a = new String(dateComponents[1]);
        if (a.indexOf("0") == 0) {
            month.value = a.substr(1, 1);
        }
        else {
            month.value = a;
        }


        a = new String(dateComponents[2]);
        if (a.indexOf("0") == 0) {
            day.value = a.substr(1, 1);
        }
        else {
            day.value = a;
        }
    }
    else if (format == "mm-dd-yyyy") {

        year.value = dateComponents[2];

        var a = new String(dateComponents[0]);
        if (a.indexOf("0") == 0) {
            month.value = a.substr(1, 1);
        }
        else {
            month.value = a;
        }


        a = new String(dateComponents[1]);
        if (a.indexOf("0") == 0) {
            day.value = a.substr(1, 1);
        }
        else {
            day.value = a;
        }

    }
    return;
}


/**
 *	desc : sets hours , minutes and am\ pm value of the controls passed as parameters according to time
 *  Format should be "h:mm a"
 *  added by MFB , 5th MAR 2006
 */
function fillTime(time, hours, minutes, ampm) {

    if (time.length > 0) {
        hours.value = time.substr(0, time.indexOf(":"));
        minutes.value = time.substr(time.indexOf(":") + 1, parseInt(time.indexOf(" ")) - ( parseInt(time.indexOf(":")) + 1 ));
        ampm.value = time.substr(time.indexOf(" ") + 1, time.length - time.indexOf(" ") + 1);
    }

    return true;
}


/**
 * This method searches the select list with values starting with
 * text and sets focus on the selected index
 * @return
 */
function searchTextInSelectList(text, list) {
    if (text == null || list == null || list.length <= 1) {
        return;
    }

    var selectedId = 0;

    if (text != "") {
        text = text.toUpperCase();

        for (var i = 0; i < list.length; i++) {
            var listVal = list.options[i].text.toUpperCase();

            if (listVal.indexOf(text) == 0) {
                selectedId = i;
                break;
            }
        }
    }
    list.selectedIndex = selectedId;
}

function checkAddress(txt, title) {

    var unsupportedCharSet = new Array();
    unsupportedCharSet[0] = '*';
    unsupportedCharSet[1] = ':';
    unsupportedCharSet[2] = '~';
    unsupportedCharSet[3] = '%';
    unsupportedCharSet[4] = '@';
    unsupportedCharSet[5] = '[';
    unsupportedCharSet[6] = ']';
    unsupportedCharSet[7] = '_';
    unsupportedCharSet[8] = '{';
    unsupportedCharSet[9] = '}';
    unsupportedCharSet[10] = '\\';
    unsupportedCharSet[11] = '|';
    unsupportedCharSet[12] = '<';
    unsupportedCharSet[13] = '>';
    unsupportedCharSet[14] = '$';

    return checkUnSupportedCharacters(txt, title, unsupportedCharSet);
}

/**
 * This function checks unsupported characters. It does not notify error
 * when the given values does not contain illegal characters.
 * @return error string if there is error or empty string.
 */
function checkUnSupportedCharactersWithHash(txt, title) {
    var unsupportedCharSet;

    var arg = checkUnSupportedCharactersWithHash.arguments;
    if (arg[2] != null) {
        unsupportedCharSet = arg[2];
    }
    else {
        unsupportedCharSet = new Array();
        unsupportedCharSet[0] = '*';
        unsupportedCharSet[1] = ':';
        unsupportedCharSet[2] = '~';
        unsupportedCharSet[3] = '%';
        unsupportedCharSet[4] = '@';
        unsupportedCharSet[5] = '[';
        unsupportedCharSet[6] = ']';
        unsupportedCharSet[7] = '_';
        unsupportedCharSet[8] = '{';
        unsupportedCharSet[9] = '}';
        unsupportedCharSet[10] = '\\';
        unsupportedCharSet[11] = '|';
        unsupportedCharSet[12] = '<';
        unsupportedCharSet[13] = '>';
        unsupportedCharSet[14] = '$';        
    }

    var errors = false;

    if (txt == null || txt.value == '') return '';

    var text = txt.value;

    var ret_val = '';
    for (var i = 0; i < unsupportedCharSet.length; i++) {
        if (text.indexOf(unsupportedCharSet[i]) != -1) {
            errors = true;
        }

        ret_val += unsupportedCharSet[i] + " ";
    }

    if (errors) {
        return '- ' + title + ' cannot contain the following characters:  ' +
               ret_val + '\n';
    }

    return '';
}


function checkUnSupportedCharacters(txt, title) {
    var unsupportedCharSet;

    var arg = checkUnSupportedCharacters.arguments;
    if (arg[2] != null) {
        unsupportedCharSet = arg[2];
    }
    else {
        unsupportedCharSet = new Array();
        unsupportedCharSet[0] = '*';
        unsupportedCharSet[1] = ':';
        unsupportedCharSet[2] = '~';
        unsupportedCharSet[3] = '%';
        unsupportedCharSet[4] = '@';
        unsupportedCharSet[5] = '[';
        unsupportedCharSet[6] = ']';
        unsupportedCharSet[7] = '_';
        unsupportedCharSet[8] = '{';
        unsupportedCharSet[9] = '}';
        unsupportedCharSet[10] = '\\';
        unsupportedCharSet[11] = '|';
        unsupportedCharSet[12] = '<';
        unsupportedCharSet[13] = '>';
        unsupportedCharSet[14] = '#';
        unsupportedCharSet[15] = '$';
        unsupportedCharSet[16] = '^';
        unsupportedCharSet[17] = '&';
    }

    var errors = false;

    if (txt == null || txt.value == '') return '';

    var text = txt.value;

    var ret_val = '';
    for (var i = 0; i < unsupportedCharSet.length; i++) {
        if (text.indexOf(unsupportedCharSet[i]) != -1) {
            errors = true;
        }

        ret_val += unsupportedCharSet[i] + " ";
    }

    if (errors) {
        return '- ' + title + ' cannot contain the following characters:  ' +
               ret_val + '\n';
    }

    return '';
}
function isCheckSpecialCharacters(txt, spaceIgnor)
{
    if(spaceIgnor){
        var iChars = "!@#$%^&*()+=-[]\';,./{}|\":<>?";
    }else{
        var iChars = "!@#$%^&*()+=-[]\';,./{}|\":<>? ";
    }

    for (var i = 0; i < txt.length; i++) {
        if (iChars.indexOf(txt.charAt(i)) != -1) {
            return true;
        return false;
        }
    }
}
function createRequestString(theForm)
{
    var reqStr = "";

    for (i = 0; i < theForm.elements.length; i++)
    {
        isFormObject = false;

        if (theForm.elements[i].tagName == "INPUT"
                && theForm.elements[i].name.indexOf('DiscAdj') == -1
                && theForm.elements[i].name.indexOf('WriteOff') == -1)
        {

            switch (theForm.elements[i].type)
                    {
                case "text":
                case "hidden":
                    reqStr += theForm.elements[i].name + "=" + escape(theForm.elements[i].value);
                    isFormObject = true;
                    break;

                case "checkbox":
                    if (theForm.elements[i].checked)
                    {
                        reqStr += theForm.elements[i].name + "=" + escape(theForm.elements[i].value);
                    } else {
                        reqStr += theForm.elements[i].name + "=";
                    }
                    isFormObject = true;
                    break;

                case "radio":
                    if (theForm.elements[i].checked)
                    {
                        reqStr += theForm.elements[i].name + "=" + escape(theForm.elements[i].value);
                        isFormObject = true;
                    }
            }
        }

        if (theForm.elements[i].tagName == "SELECT" && theForm.elements[i].name.indexOf('Authorization') == -1)
        {
            var sel = theForm.elements[i];
            if (sel.selectedIndex != -1)
                reqStr += sel.name + "=" + escape(sel.options[sel.selectedIndex].value);
            isFormObject = true;
        }

        if ((isFormObject) && ((i + 1) != theForm.elements.length))
        {
            reqStr += "&";
        }

    }
    return reqStr;
}
//Mask for phone format
function formatPhone(h) {

    if (h.value.length > 9 && h.value.charAt(10) == ';') {
        var tmpPhone = h.value;
        h.value = '(' + tmpPhone.substring(0, 3) + ') ' + tmpPhone.substring(3, 6) + '-' + tmpPhone.substring(6, 10);
        if (tmpPhone.length > 11) {
            h.value = h.value + ' Ext. ' + tmpPhone.substring(11)
        }
    }

}	//end of function
function formatPhoneExtended(h) {
    unformatPhoneExtanded(h);
    if(h.value.indexOf(';')==-1 && h.value.length==10)
     h.value=h.value+';';   

    //alert(h.value.charAt(10));
    if (h.value.length > 9 && h.value.charAt(10) == ';') {
        var tmpPhone = h.value;
        h.value = '(' + tmpPhone.substring(0, 3) + ') ' + tmpPhone.substring(3, 6) + '-' + tmpPhone.substring(6, 10);
        if (tmpPhone.length > 11) {
            h.value = h.value + ' Ext. ' + tmpPhone.substring(11)
        }
    }

}	//end of function

//Mask for phone format
function formatPhoneText(value) {
    //  alert(value);
    if (value.length > 9) {
        //    alert(1);
        var tmpPhone = value;
        value = '(' + tmpPhone.substring(0, 3) + ') ' + tmpPhone.substring(3, 6) + '-' + tmpPhone.substring(6, 10);
        if (tmpPhone.length > 11) {
            value = value + ' Ext. ' + tmpPhone.substring(11);
        }
    }

    return value;
}// end of function

/*
Remove mask for Phone number
@author Farhan Parpia
*/
function unformatPhone(h) {
    if (h.value.length == 0) {
        return false;
    }
    if (h.value.length > 13) {
        var tmpPhone = removeChar(removeChar(removeChar(removeChar(removeChar(h.value.substring(0, 14), '('), ')'), '-'), ' '), '.');
        var tmpExt = h.value.substring(20);
        if (isNaN(tmpPhone) == true || isNaN(tmpExt) == true) {
            //			alert('Characters are not allowed in phone number.');
            h.focus();
            return false;
        }
    }
    h.value = tmpPhone + ';' + tmpExt;
}//end of function

function unformatPhoneExtanded(h) {
    if (h.value.length == 0) {
        return false;
    }
    if (h.value.length > 10) {
        var tmpPhone = removeChar(removeChar(removeChar(removeChar(removeChar(h.value.substring(0, h.value.length ), '('), ')'), '-'), ' '), '.');
        var tmpExt = h.value.replace(' Ext. ',';');
        //h.value = tmpPhone + ';' + tmpExt;
        //if (isNaN(tmpPhone) == true || isNaN(tmpExt) == true) {
            //h.focus();
          //  return false;
        //}
    }
    //h.value = tmpPhone + ';' + tmpExt;
}//end of function


/*
Mask Format on Phone Feild
@author Farhan Parpia
*/

function keyPressOnPhone(h) {
    if (event.keycode == 8) {
        ;
    } else if (h.value.length == 3) {
        h.value = '(' + h.value + ') ';
    } else if (h.value.length == 9) {
        h.value = h.value + '-';
    } else if (h.value.length == 14) {
        h.value = h.value + ' Ext. ';
    }
}//end of function

function keyPressOnPhoneWithoutExt(h) {
    //(000) 000-0000
    if (event.keycode == 8) {
        ;
    } else if (h.value.length == 3) {
        h.value = '(' + h.value + ') ';
    } else if (h.value.length == 9) {
        h.value = h.value + '-';
    }
}//end of function

/*
Check the Format for Phone Feild
author Farhan Parpia
*/

function blurOnPhone(h) {
    if (h.value.length == 0) {
        return false;
    }
    if (h.value.length < 14 || h.value.charAt(0) != '(' || h.value.charAt(4) != ')' || h.value.charAt(5) != ' ' || h.value.charAt(9) != '-') {
        alert('Incorrect phone number');
        h.focus();
        return false;
    }
    if (h.value.length > 15 && h.value.charAt(20) == '') {
        alert('Incorrect phone number');
        h.focus();
        return false;
    }
    tempnum = h;
    unformatPhone(tempnum);
    tempnum1 = tempnum.value;
    tempnum1 = removeCharAt(tempnum1, ';', 10);
    formatPhone(h);
//	alert(tempnum.value )
    //	alert(tempnum1 )

    if (isNaN(tempnum1) || tempnum1.indexOf('e') > -1 || tempnum1.indexOf('.') > -1) {
        h.value = "";
        h.focus();
        alert(' Phone number cannot contain characters.');
        return false;
    }

}//end of function

/*
Remove Spaces Form Text box ..
author Farhan Parpia
*/

function removeSpace(frm) {
    if (frm == null || frm.elements == null) {
        return;
    }
    for (var i = 0; i < frm.elements.length; i++) {
        if (frm.elements[i].type == "text" || frm.elements[i].type == "textarea") {
            frm.elements[i].value = trim(frm.elements[i].value);

        }
    }
}//end of function


//SSN Foarmat

function keyPressOnSsn(ssn) {

    if (event.keycode == 8) {

    } else if (ssn.value.length == 3 || ssn.value.length == 6) {
        ssn.value = ssn.value + "-";
    }

}

function blurOnSsn(ssn) {
    if (ssn.value.length > 0)
    {
        var tmpSSN = removeChar(ssn.value, '-');
        var tmp = removeChar(removeChar(tmpSSN, '.'), ' ');
        if (isNaN(tmpSSN) == true || tmp.length != tmpSSN.length)
        {
            alert('Characters are not allowed in social security number.');
            ssn.focus();
            return false;
        } else if (tmpSSN.length != 9 || ssn.value.charAt(3) != '-' || ssn.value.charAt(6) != '-') {
            alert('Incorrect social security number.');
            ssn.focus();
            return false;
        }
    }
}

function unformatSsn(ssn) {

    if (ssn.value.length > 0)
    {
        var tmpSSN = removeChar(ssn.value, '-');
        ssn.value = tmpSSN;


    }
}

function removeChar(src, charToBeRemoved) {
    var i = 0;
    var tmpValue = '';
    for (i = 0; i < src.length; i++) {
        if (src.charAt(i) != charToBeRemoved) {
            tmpValue += src.charAt(i);
        } // end of if
    } // end of for
    return tmpValue;
} // end of function removeChar


function formatSsn(ssn) {

    if(!isNaN(ssn.value))
    {
	ssn.value = appendSsnZeros(ssn.value);
    }

    if (isNaN(ssn.value) == false && ssn.value.length == 9)
    {
        ssn.value = ssn.value.substring(0, 3) + '-' + ssn.value.substring(3, 5) + '-' + ssn.value.substring(5);
    }
}

//end SSN Foarmat
/*
This will replace all the links with id="disableLink" with the inner image tag
@author Aqeela Hemani
*/
function disableDBClick(documentObj) {
    //var objects = documentObj.getElementsByTagName("a");
    var objects = documentObj.all.item("disableLink");
    var found = true;
    while (found && objects) {

        found = false
        for (i = 0; i < objects.length; i++) {
            if (objects[i].id.indexOf("disableLink") >= 0) {
                found = true;
                objects[i].outerHTML = objects[i].innerHTML;
            }
        }
        objects = documentObj.all.item("disableLink");
        if (!objects) {
            found = false;
        }
    }

}

/*
This will hilight the forms elments on Focus (Test Feild , Text Area , Select Box )
@author Farhan Parpia
*/

function hiliteOnFocus() {
    var formsLength = document.forms.length
    for (var x = 0; x < formsLength + 1; x++) {
        if (document.forms[x] == null || document.forms[x].elements == null) {
            return;
        }
        for (var i = 0; i < document.forms[x].elements.length; i++) {
            if (document.forms[x].elements[i].type == "text" || document.forms[x].elements[i].type == "textarea" || document.forms[x].elements[i].type == "select-one") {
                if (document.forms[x].elements[i].type == "text") {
                    document.forms[x].elements[i].style.textTransform = "uppercase"
		//document.forms[x].elements[i].onfocus = function () {this.style.backgroundColor='#FFFF99'}
                }
		//document.forms[x].elements[i].onfocus = function () {this.style.backgroundColor='#FFFF99'}
                //document.forms[x].elements[i].onblur = function () {this.style.backgroundColor='#ffffff'}
            }
        }
    }
}

function checkLoad()
{
    if (document.readyState == "complete") {
        hiliteOnFocus();
    }
}//end hilite on focus


/*
This will change case of Text Feild to uppercase and also  Remove prefix and suffix spaces
@author Farhan Parpia
*/

function uppercase() {
    var formsLength = document.forms.length
    for (var x = 0; x < formsLength + 1; x++) {
        if (document.forms[x] == null || document.forms[x].elements == null) {
            return;
        }
        for (var i = 0; i < document.forms[x].elements.length; i++) {
            if (document.forms[x].elements[i].type == "text") {
                document.forms[x].elements[i].value = document.forms[x].elements[i].value.toUpperCase()
                removeSpace(document.forms[x]);
            }
        }
    }
}
//window.onbeforeunload = uppercase;
//document.onreadystatechange=checkLoad;

/*
All the functions regarding date Component
@author Farhan Parpia
*/
function keyPressOnDate(frmDate) {
    if (event.keycode == 8) {
        ;
    }
    else if (frmDate.value.length == 2 || frmDate.value.length == 5) {
        frmDate.value = frmDate.value + '-';
    }
}

function keyPressOnTime(frmTime) {
    //	alert(event.keyCode);
    if (event.keycode == 8) {
        ;
    }
    else if (frmTime.value.length == 2 && frmTime.value.indexOf(':') < 0 && window.event.keyCode != 58) {
        frmTime.value = frmTime.value + ':';
    }
    else if (frmTime.value.length == 5 && frmTime.value.indexOf('A') < 0 && frmTime.value.indexOf('P') < 0 && frmTime.value.indexOf('a') < 0 && frmTime.value.indexOf('p') < 0) {
        frmTime.value = frmTime.value + ' AM';
    }
}
function blurOnTime(frmTime, dontShowAlert) {
    var regex = /^([1-9]|1[0-2]|0[1-9]){1}(:[0-5][0-9]\s[aApP][mM]){1}$/;
    frmTime.value = trim(frmTime.value);
    if (frmTime.value.length > 0 && !regex.test(frmTime.value)) {
        if (dontShowAlert) {
            return false
        }
        else {
            alert("Time is incorrect");
            frmTime.focus();
        }
    }

}

function blurOnDate(frmDate, dontShowAlert) {
    if (frmDate.value.length > 0) {

        var tmp = removeChar(frmDate.value, '.');
        if (tmp.length != frmDate.value.length || tmp.length != 10) {
            if (!dontShowAlert) {
                alert('Incorrect Date \n-Please check your Month, Day, Year range. Year should be greater then 1900.\n-Please check LEAP YEAR.');
            }
            frmDate.focus();
            return false;
        }
        var dateParts = tmp.split('-');
        var tmpYear = parseInt(dateParts[2]);
        if (tmpYear < 1900) {
            if (!dontShowAlert) {
                alert('Incorrect Date\n-Date should be in MM-DD-YYYY\n-Please check your Month, Day, Year range. Year should be greater then 1900.\n-Please check LEAP YEAR.');
            }
            frmDate.focus();
            return false;

        }

        var tmpMonth = parseInt((dateParts[0].charAt(0) == '0' ? dateParts[0].charAt(1) : dateParts[0]));
        var tmpDay = parseInt((dateParts[1].charAt(0) == '0' ? dateParts[1].charAt(1) : dateParts[1]));
        var tmpDate = new Date(tmpYear, tmpMonth - 1, tmpDay);
	//	 alert(tmpYear + "  ddd  " + tmpDate.getFullYear() + " ddddd  " + tmpDate);
        if (tmpMonth != (tmpDate.getMonth() + 1) || tmpDay != tmpDate.getDate() || tmpYear != tmpDate.getFullYear()) {
            if (!dontShowAlert) {
                alert('Incorrect Date \n-Please check your Month, Day, Year range. Year should be greater then 1900.\n-Please check LEAP YEAR.');
            }
            frmDate.focus();
            return false;
        }
        return true;
    }
}

function unformatDate(frmDate) {
    if (frmDate.value.length > 0)
    {
        var tmpfrmDate = removeChar(frmDate.value, '-');
        frmDate.value = tmpfrmDate;
    }
}
function formatDate(frmDate) {
    //frmDate.background='#FF0000';
    if (isNaN(frmDate.value) == false && frmDate.value.length == 8) {
        frmDate.value = frmDate.value.substring(0, 2) + '-' + frmDate.value.substring(2, 4) + '-' + frmDate.value.substring(4);
    }
}// end functions of date component

/*
This method checks is used for opening Patient Notes Page
from variuos locations in the application.
selected it returns false
@author M.A.Q
*/

function viewNotesDialog(patientId, practiceId) {

    if (patientId == null || patientId == "0" || patientId == "null" || trim(patientId).length <= 0) {
        alert("Select Patient First");
        return;
    }

    var url = "/apolloweb/popup/addUpdatePatientNotes.do?displayMenu=false&patientId=" + patientId + "&practiceId=" + practiceId + "&actionType=view&displayMenu=false&typeId=-1";
    // alert(url);
    // setting the following parameters to display the popup in center
    var width = 794;
    var height = 500;
    var pxOffset = 0;
    var pyOffset = 15;
    //alert( "toolbar=n,location=n,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,width=" + width + ",height=" + height + ",screenX=" + pxOffset + ",screenY=" + pyOffset + ",top=" + pyOffset + ",left=" + pxOffset);
    var popup = window.open(url, "popup", "toolbar=n,location=n,directories=no,status=no,menubar=no,scrollbars=yes,resizable=no,width=" + width + ",height=" + height + ",screenX=" + pxOffset + ",screenY=" + pyOffset + ",top=" + pyOffset + ",left=" + pxOffset);
    popup.moveTo(pxOffset, pyOffset)
    popup.resizeTo(796, 543);
    return;
}

/*
This method checks is used for opening Patient Health Plan Page
from variuos locations in the application.
selected it returns false
@author M.A.Q
*/
function openPatientInsuranceInfo(frm, actionType) {

    if (frm.patientId.value == null || frm.patientId.value == "null" || trim(frm.patientId.value).length <= 0) {
        alert("Select Patient First");
        return;
    }

    var url = "/apolloweb/popup/addUpdateStaffPatientHealthPlan.do?displayMenu=false&actionType=" + actionType + "&patientId=" + frm.patientId.value;

    var pxOffset = 0;
    var pyOffset = 15;

    var hWnd = window.open(url, "", "width=794,height=500,resizable=no,scrollbars=yes,screenX=" + pxOffset + ",screenY=" + pyOffset + ",top=" + pyOffset + ",left=" + pxOffset);

}

function isNotEmpty(value) {
    if (value != null && value.replace(/\s+/g, '') != "") {
        return true;
    } else {
        return false;
    }
}

function isEmpty(value) {
    return (!isNotEmpty(value));
}

/*
This method checks if any item in a list is selected.
If nothing is selected, method return false, also if a blank option is
selected it returns false
@author Faisal Moin Khan
*/
function isItemSelected(list) {
    var selected = true;
    if (list == null || list.options == null || list.options.length == 0) {
        return false;
    }
    if (list.selectedIndex == -1)
        selected = false;
    else {
        if (isEmpty(list.options[list.selectedIndex].text)) {
            selected = false;
        }
    }

    return selected;
}

/*
This method returns the text of the item selected in a select list
@author Faisal Moin Khan
@added 9th December 2004
*/

function getSelectListItemText(list)
{
    var val = '';
    if (isItemSelected(list)) {
        val = list.options[list.selectedIndex].text;
    }
    return val;
}


function getSelectListItemValue(list)
{
    var val = '';
    if (isItemSelected(list)) {
        val = list.options[list.selectedIndex].text;
    }
    return val;
}

/*
following method takes an unformatted fax value,
breaks it into differrent parts and sets it in three fax components
@author: Faisal Moin Khan
@created: 12th November 04
*/
function setFaxComponents(faxValue, fax1, fax2, fax3) {
    fax1.value = '';
    fax2.value = '';
    fax3.value = '';

    if (isNotEmpty(faxValue)) {
        var length = faxValue.length;
        if (length >= 0) {
            fax1.value = faxValue.substring(0, 3);
        }
        if (length >= 3) {
            fax2.value = faxValue.substring(3, 6);

        }
        if (length >= 6) {
            fax3.value = faxValue.substring(6, 10);

        }
    }
}

/*
following method takes an unformatted zip value,
breaks it into differrent parts and sets it in 2 zip components
@author: Faisal Moin Khan
@created: 12th November 04
*/
/*
function fillZip(zip){
	var frm=document.forms[0];
	setZipComponents(zip,frm.zip1,frm.zip2);
}
*/
function setZipComponents(zipValue, zip1, zip2) {
    zip1.value = '';
    zip2.value = '';
    if (isNotEmpty(zipValue)) {
        var length = zipValue.length;
        if (length >= 0) {
            zip1.value = zipValue.substring(0, 5);
        }
        if (length >= 3) {
            zip2.value = zipValue.substring(5, 9);

        }
    }

}

/*
following method takes a fullName and
breaks it into differrent parts .i.e - firstName, middleName, lastName
and sets the parts into respective fields
@author: Faisal Moin Khan
@created: 22th November 04
*/

function setNameComponents(fullNameTxt, firstName, middleName, lastName) {
    //fullNameTxt = trim(fullNameTxt);
    firstName.value = '';
    middleName.value = '';
    lastName.value = '';
    var commaIndex = fullNameTxt.indexOf(',');
    var dotIndex = fullNameTxt.indexOf('.');
	//if last name is provided
    if (commaIndex > -1) {
        lastName.value = fullNameTxt.substring(0, commaIndex);
        commaIndex += 2;
    } else {
        commaIndex = 0;
    }
	//if middle initial is provided
    if (dotIndex > -1) {
        middleName.value = fullNameTxt.charAt(dotIndex - 1);
    } else {
        dotIndex = fullNameTxt.length;
    }
    firstName.value = fullNameTxt.substring(commaIndex, dotIndex - 1);
}

/*
following method checks for a valid Name based on a regular expression.
Method also checks if the field is a required field.
@return: Method returns string based on the error generated
@author: Faisal Moin Khan
@created: 18th November 04
*/

function checkMiddle(txt, title, required) {
    var re = /[a-z]/i;
    var errors = '';
    if (required) {
        if (isEmpty(txt)) {
            errors += ('- ' + title + ' is required.\n');
        } else {
            if (txt.search(re) == -1) {
                errors += ('- ' + title + ' has invalid format.\n');
            }
        }
    } // end of if not provided
    else {
        if (isNotEmpty(txt) && txt.search(re) == -1) {
            errors += ('- ' + title + ' has invalid format.\n');
        }
    } // end of if ssn is not complete
    return errors;
}


function checkName(txt, title, required) {
    var re = /^[^0-9][a-zA-Z0-9_\s()]*$/;
    var errors = '';
    if (required) {
        if (isEmpty(txt)) {
            errors += ('- ' + title + ' is required.\n');
        } else {
            if (txt.search(re) == -1) {
                errors += ('- ' + title + ' has invalid format.\n');
            }
        }
    } // end of if not provided
    else {
        if (isNotEmpty(txt) && txt.search(re) == -1) {
            errors += ('- ' + title + ' has invalid format.\n');
        }
    } // end of if ssn is not complete
    return errors;
}
function checkNumericOnly(txt, title, required) {
    var re = /^[0-9_\s()]*$/;
    var errors = '';
    if (required) {
        if (isEmpty(txt)) {
            errors += ('- ' + title + ' is required.\n');
        } else {
            if (txt.search(re) == -1) {
                errors += ('- ' + title + ' has invalid format.\n');
            }
        }
    } // end of if not provided
    else {
        if (isNotEmpty(txt) && txt.search(re) == -1) {
            errors += ('- ' + title + ' has invalid format.\n');
        }
    } // end of if ssn is not complete
    return errors;
}
function checkCharOnly(txt, title, required) {
    var re = /^[a-zA-Z_\s()]*$/;
    var errors = '';
    if (required) {
        if (isEmpty(txt)) {
            errors += ('- ' + title + ' is required.\n');
        } else {
            if (txt.search(re) == -1) {
                errors += ('- ' + title + ' has invalid format.\n');
            }
        }
    } // end of if not provided
    else {
        if (isNotEmpty(txt) && txt.search(re) == -1) {
            errors += ('- ' + title + ' has invalid format.\n');
        }
    } // end of if ssn is not complete
    return errors;
}

function checkStreetNameWithHash(txt, title, required) {
    var re = /^[a-zA-Z0-9_\s()-//#]*$/;
    var errors = '';
    if (required) {
        if (isEmpty(txt)) {
            errors += ('- ' + title + ' is required.\n');
        } else {
            if (txt.search(re) == -1) {
                errors += ('- ' + title + ' has invalid format.\n');
            }
        }
    } // end of if not provided
    else {
        if (isNotEmpty(txt) && txt.search(re) == -1) {
            errors += ('- ' + title + ' has invalid format.\n');
        }
    } // end of if ssn is not complete
    return errors;
}

function checkStreetName(txt, title, required) {
    var re = /^[a-zA-Z0-9_\s()-]*$/;
    var errors = '';
    if (required) {
        if (isEmpty(txt)) {
            errors += ('- ' + title + ' is required.\n');
        } else {
            if (txt.search(re) == -1) {
                errors += ('- ' + title + ' has invalid format.\n');
            }
        }
    } // end of if not provided
    else {
        if (isNotEmpty(txt) && txt.search(re) == -1) {
            errors += ('- ' + title + ' has invalid format.\n');
        }
    } // end of if ssn is not complete
    return errors;
}

/*
following method checks for a valid Name.
@return: Method returns true/false based on the txt
@author: Faisal Moin Khan
@created: 19th November 04
*/

function isValidName(txt) {
    var re = /^[a-zA-Z0-9_\s()]*$/;

    if (txt.search(re) == -1) {
        return false;
    }
    else {
        return true;
    } // end of if ssn is not complete
}

/*
following method checks for a valid UPIN number.
@return: Method returns error message on invalid format
@author: Faisal Moin Khan
@created: 25th November 04
*/
function checkUPINFormat(txt, name) {
    //var re = /^[A-Z]\d{5}$/;

    //changed By Haroon Masood 7 Nov 2005
    var re = /^[A-Z]([A-Z|0-9]{2})\d{3}$/;

    if (isEmpty(name)) {
        name = 'UPIN';
    }
    if (txt.search(re) == -1) {
        return ('- Invalid ' + name + '\n');

    } else {
        return '';
    }
}

/*
following method checks for a valid Ein/Tax Id.
@return: Method returns error message on invalid format
@author: Faisal Moin Khan
@created: 10th December 04
*/
function checkTaxIdFormat(txt, name) {
    var re = /^\d{9}$/;
    if (isEmpty(name)) {
        name = 'Ein/Tax Id';
    }
    if (txt.search(re) == -1) {
        return ('- ' + name + ' should contain 9 digits. \n');

    } else {
        return '';
    }
}


/*
Following Code is use to display Right Click Menu
@return: Void
@author: Farhan Ahmed Parpia
@Created: 10th Jan 05
*/

var menuskin = "skin0"; // skin0, or skin1
var display_url = 0; // Show URLs in status bar?
var _contextMenuFormName = "";

function setFlag(frmName, menuDiv) {
    _contextMenuFormName = frmName;
    if (_contextMenuFormName != "" && _contextMenuFormName != '') {
        var frm = document.forms[_contextMenuFormName];
        frm.isMenuEnabled.value = "T";

        if (frm && frm.whichMenu.value.length != 0)
            document.all[frm.whichMenu.value].style.visibility = "hidden";

        frm.whichMenu.value = menuDiv;
    }
}

function showmenuie5() {
    //hidemenuie5();
    if (_contextMenuFormName == "" || _contextMenuFormName == '')
        return;
    var frm = document.forms[_contextMenuFormName];

    if (frm.isMenuEnabled.value == "T") {
        // tracing poisition
        var rightedge = document.body.clientWidth - event.clientX;
        var bottomedge = document.body.clientHeight - event.clientY;

				// adjusting position
        if (rightedge < document.all[frm.whichMenu.value].offsetWidth)
            document.all[frm.whichMenu.value].style.left = document.body.scrollLeft + event.clientX - document.all[frm.whichMenu.value].offsetWidth;
        else
            document.all[frm.whichMenu.value].style.left = document.body.scrollLeft + event.clientX;

				// adjusting position
        if (bottomedge < document.all[frm.whichMenu.value].offsetHeight)
            document.all[frm.whichMenu.value].style.top = document.body.scrollTop + event.clientY - document.all[frm.whichMenu.value].offsetHeight;
        else
            document.all[frm.whichMenu.value].style.top = document.body.scrollTop + event.clientY;

				// will use the called DIV
        document.all[frm.whichMenu.value].style.visibility = "visible";

        frm.isMenuEnabled.value = "F";
    }

    return false;
}

function hidemenuie5() {
    var frm = document.forms[_contextMenuFormName];
    if (frm && frm.whichMenu.value.length != 0)
        document.all[frm.whichMenu.value].style.visibility = "hidden";

}

function highlightie5() {


    if (event.srcElement.className == "menuitems") {
        //event.srcElement.style.backgroundColor = "#C8C4A9";
        event.srcElement.style.backgroundColor = bg;
        event.srcElement.style.color = clr;
        if (display_url)
            window.status = event.srcElement.url;
    }
    if (event.srcElement.className == "menuitemsDisabled") {
        event.srcElement.style.backgroundColor = "#C8C4A9";
    }
}

function lowlightie5() {
    if (event.srcElement.className == "menuitems") {
        event.srcElement.style.backgroundColor = "";
        event.srcElement.style.color = "";
        window.status = "";
    } else if (event.srcElement.className == "menuitemsDisabled") {
        event.srcElement.style.backgroundColor = "";
    }
}

function jumptoie5() {
    if (event.srcElement.className == "menuitems") {
        if (event.srcElement.getAttribute("target") != null)
            window.open(event.srcElement.url, event.srcElement.getAttribute("target"));
        else
            window.location = event.srcElement.url;
    } //end of if
    else if (cancel.className == "menuitemsDisabled")
        alert("No Appointment to Cancel");
}//end of function

/*
End Of Right Click Menu Script
*/
/**
 * Javascript method added for Opening Popup window and writing document HTML
 * This method is used in CPT Configuration only. This method is written here
 * because of Sitemesh bug.
 * @author Faisal Moin Khan
 * @created on 12th January 2005
 */
var popUp = null;
function openModifierWindow(cptCode, cptDescription, cptId, modifierValues) {
    var frm = document.forms[0];
    var pxOffset = 200;
    var pyOffset = ((screen.availHeight - 550) / 1);
    if (popUp) {
        popUp.close();
        popUp = null
    }

    var shortDescription = '';
    if (isNotEmpty(cptDescription)) {
        shortDescription = cptDescription;
        if (shortDescription.length > 50) {
            shortDescription = shortDescription.substring(0, 50) + '...';
        }
    }

    if (popUp == null) {
        popUp = window.open("", "", "width=260,height=240,resizable=no,scrollbars=yes,screenX=" + pxOffset + ",screenY=" + pyOffset + ",top=" + pyOffset + ",left=" + pxOffset);
        var fieldModifiers = modifierValues.split(',');
		//alert('fieldModifiers: '+fieldModifiers);
        var doc = popUp.document;
        var popUpHTML = '';
        popUpHTML += '<html><head><title>Select Modifiers</title><link rel="stylesheet" href="../ThemeStaff.css" >';
        popUpHTML += '<script language="JavaScript" src="../include/eprowiz.js"><' + '/script>';
        popUpHTML += '<script language="JavaScript">';
        popUpHTML += ' function save(){';
        popUpHTML += '   var frm = document.forms[0];';
        popUpHTML += '   var count = 0 ;';
        popUpHTML += '   for(i = 0 ; i < frm.serviceModifiers.options.length ; i++){';
        popUpHTML += '		if(frm.serviceModifiers.options[i].selected == true) {';
        popUpHTML += '			count ++;';
        popUpHTML += '		}';
        popUpHTML += '   }';
        popUpHTML += '   if(count > 4) {';
        popUpHTML += '		alert("You can select at most 4 Modifiers values");';

        popUpHTML += '		count = 0;';
        popUpHTML += '		for(i=0;i<frm.serviceModifiers.options.length;i++){';
        popUpHTML += '			if(frm.serviceModifiers.options[i].selected==true){';
        popUpHTML += '				if(count>=4){';
        popUpHTML += '					frm.serviceModifiers.options[i].selected=false;';
        popUpHTML += '				}else{';
        popUpHTML += '					count++;';
        popUpHTML += '				}';
        popUpHTML += '			}';
        popUpHTML += '		}';

        popUpHTML += '		frm.serviceModifiers.focus();';
        popUpHTML += '		return;';
        popUpHTML += '   }';
        popUpHTML += '	var selectedValues = "";';
        popUpHTML += '	for(i=0;i<frm.serviceModifiers.options.length;i++){';
        popUpHTML += '		 if(frm.serviceModifiers.options[i].selected && frm.serviceModifiers.options[i].value!="-1" ){';
        popUpHTML += '			selectedValues+=frm.serviceModifiers.options[i].value+",";';
        popUpHTML += '		 }';
        popUpHTML += '	}';
        popUpHTML += '	selectedValues = selectedValues.substring(0,selectedValues.length-1);';
//		popUpHTML += ' alert(selectedValues);';
        popUpHTML += '	var modifierElement = window.opener.document.forms[0].modifiers' + cptId + ';';
//		popUpHTML += ' alert(modifierElement);';
        popUpHTML += '	modifierElement.value=selectedValues; ';
		//popUpHTML += ' eval("window.opener.modifierLinks'+cptId+'.innerHTML = selectedValues.substring(0,selectedValues.length-1)");';
        popUpHTML += '	self.close();';

        popUpHTML += ' } // end of function save';
        popUpHTML += '</' + 'script>';
        popUpHTML += '</head><body scroll="no" ><table width="100%" border="0" cellpadding="0" cellspacing="0" class="border">';
        popUpHTML += '<tr><td valign="top" class="taskBar">Select Modifiers:</td></tr>';
        popUpHTML += '<tr><td valign="top" > <form name="frm" method="post">';
        popUpHTML += '<table width="99%" border="0" align="center" >';
        popUpHTML += '<tr><td class="heading2" title="' + cptDescription + '">CPT : <span class="bold">' + cptCode + '&nbsp;' + shortDescription + '</span></td></tr>';
        popUpHTML += '<tr><td class="heading2" align="center"><span id="modifierList">';

        popUpHTML += '<select name="serviceModifiers" size="10" style="width:150 px" multiple id="modifierList">';
        /*		var optionElement ;
                var isSelected = '';
                for(i=0;i<frm.topModifiers.options.length;i++){
                    isSelected = '';
                    optionElement = frm.topModifiers.options[i];
                    for(j=0;j<fieldModifiers.length;j++){
                        if(optionElement.value==fieldModifiers[j]){
                            isSelected ='selected';
                            break;
                        }
                    }
                    popUpHTML += '<option value="'+optionElement.value+'" '+isSelected+'>'+optionElement.text+'</option>';
                }
        */
        popUpHTML += '<option value="-1">No Code Selected</option>';
        popUpHTML += '<option value="21">21 Prolonged Evaluation</option>';
        popUpHTML += '<option value="22">22 Unusual Procedural Services</option>';
        popUpHTML += '<option value="23">23 Unusual Anesthesia</option>';
        popUpHTML += '<option value="24">24 Unrelated Evaluation & Mgmt</option>';
        popUpHTML += '<option value="25">25 Significant, Separately Eval</option>';
        popUpHTML += '<option value="26">26 Professional Component</option>';
        popUpHTML += '<option value="32">32 Mandated Services</option>';
        popUpHTML += '<option value="47">47 Anesthesia by Surgeon</option>';
        popUpHTML += '<option value="50">50 Bilateral Procedure</option>';
        popUpHTML += '<option value="51">51 Multiple Procedures</option>';
        popUpHTML += '<option value="52">52 Reduced Services</option>';
        popUpHTML += '<option value="53">53 Discontinued Procedure</option>';
        popUpHTML += '<option value="54">54 Surgical Care Only</option>';
        popUpHTML += '<option value="55">55 Postoperative Management Only</option>';
        popUpHTML += '<option value="56">56 Preoperative Management Only</option>';
        popUpHTML += '<option value="57">57 Decision for Surgery</option>';
        popUpHTML += '<option value="58">58 Staged\Rel Pro\Ser-Same Phys</option>';
        popUpHTML += '<option value="59">59 Distinct Procedural Service</option>';
        popUpHTML += '<option value="62">62 Two Surgeons Required</option>';
        popUpHTML += '<option value="66">66 Surgical Team</option>';
        popUpHTML += '<option value="76">76 Repeat Procedure by Same Phys.</option>';
        popUpHTML += '<option value="77">77 Repeat Procedure by Diff. Phys.</option>';
        popUpHTML += '<option value="78">78 Return to O.R. for related Pro</option>';
        popUpHTML += '<option value="79">79 Unrelated Serv. During Post Op</option>';
        popUpHTML += '<option value="80">80 Assistant Surgeon</option>';
        popUpHTML += '<option value="81">81 Minimum Assistant Surgeon</option>';
        popUpHTML += '<option value="82">82 Assistant Surgeon (Resident N/A)</option>';
        popUpHTML += '<option value="99">99 Multiple Modifiers</option>';
        popUpHTML += '<option value="AJ">AJ Clinical Social Worker </option>';
        popUpHTML += '<option value="AK">AK NP-Rural Team Member</option>';
        popUpHTML += '<option value="AL">AL NP Non-Rural Team Member</option>';
        popUpHTML += '<option value="AT">AT Acute Condition</option>';
        popUpHTML += '<option value="AV">AV NP Rural Non Team Member</option>';
        popUpHTML += '<option value="BP">BP Beneficiary Purchased</option>';
        popUpHTML += '<option value="LT">LT Left Side. (Used to identify procedures performed on the left side of the body.)</option>';
        popUpHTML += '<option value="RT">RT Right Side (used to identify procedures performed on the right side of the body).</option>';
        popUpHTML += '<option value="E1">E1 Upper Left, Eyelid.</option>';
        popUpHTML += '<option value="E2">E2 Lower Left, Eyelid.</option>';
        popUpHTML += '<option value="E3">E3 Upper Right, Eyelid.</option>';
        popUpHTML += '<option value="E4">E4 Lower Right, Eyelid.</option>';
        popUpHTML += '<option value="FA">FA Left Hand, Thumb.</option>';
        popUpHTML += '<option value="F1">F1 Left Hand, Second Digit.</option>';
        popUpHTML += '<option value="F2">F2 Left Hand, Third Digit.</option>';
        popUpHTML += '<option value="F3">F3 Left Hand, Fourth Digit.</option>';
        popUpHTML += '<option value="F4">F4 Left Hand, Fifth Digit.</option>';
        popUpHTML += '<option value="F5">F5 Right Hand, Thumb.</option>';
        popUpHTML += '<option value="F6">F6 Right Hand, Second Digit.</option>';
        popUpHTML += '<option value="F7">F7 Right Hand, Third Digit.</option>';
        popUpHTML += '<option value="F8">F8 Right Hand, Fourth Digit.</option>';
        popUpHTML += '<option value="F9">F9 Right Hand, Fifth Digit.</option>';
        popUpHTML += '<option value="GV">GV Attending physician not employed or paid under arrangement by the patient\'s hospice provider.</option>';
        popUpHTML += '<option value="GW">GW Service not related to the hospice patient¿s terminal condition.</option>';
        popUpHTML += '<option value="TA">TA Left Foot, Great Toe.</option>';
        popUpHTML += '<option value="T1">T1 Left Foot, Second Digit.</option>';
        popUpHTML += '<option value="T2">T2 Left Foot, Third Digit.</option>';
        popUpHTML += '<option value="T3">T3 Left Foot, Fourth Digit.</option>';
        popUpHTML += '<option value="T4">T4 Left Foot, Fifth Digit.</option>';
        popUpHTML += '<option value="T5">T5 Right Foot, Great Toe.</option>';
        popUpHTML += '<option value="T6">T6 Right Foot, Second Digit.</option>';
        popUpHTML += '<option value="T7">T7 Right Foot, Third Digit.</option>';
        popUpHTML += '<option value="T8">T8 Right Foot, Fourth Digit.</option>';
        popUpHTML += '<option value="T9">T9 Right Foot, Fifth Digit.</option>';
        popUpHTML += '</select>';
        popUpHTML += '</span></td></tr>';

        popUpHTML += '</table>';
        popUpHTML += '</form></td>';
        popUpHTML += '</tr>';
        popUpHTML += '<tr><td valign="top" height ="7" background="../images/staffsideSeparator.gif"></td></tr>';
        popUpHTML += '<tr><td valign="middle" align="center"><a href="javascript:save();"><img src="../images/staffBSave.gif" height="24" width="86" border="0" alt="Save Service"></a>&nbsp;&nbsp;&nbsp; <a href="javascript:window.close();"><img src="../images/staffBClose.gif" width="86" height="24" alt="Close Window" border="0"></a></td></tr>';
        popUpHTML += '</table>';
        popUpHTML += '<script>';
        popUpHTML += '\n	window.onbeforeunload=function(){window.opener.popUp = null;}';
        /*if(fieldModifiers.length>0 && isNotEmpty(fieldModifiers[0])){
              popUpHTML += '\n document.forms[0].serviceModifiers.value="'+fieldModifiers[0]+'" ;' ;
          }else{
              popUpHTML += '\n document.forms[0].serviceModifiers.value="-1";' ;
          }*/

        ///////////// added for multiple modifiers, code to mark saved ServiceModifiers selected in popup window
        if (fieldModifiers.length > 0 && isNotEmpty(fieldModifiers[0])) {
            popUpHTML += '\n var serviceModifiersList = document.forms[0].serviceModifiers;';
            popUpHTML += '\n for(var serviceModifierCount=0; serviceModifierCount<serviceModifiersList.length; serviceModifierCount++) {';
            for (var fieldModifierCount = 0; fieldModifierCount < fieldModifiers.length; fieldModifierCount++) {
                popUpHTML += '\n 	if(serviceModifiersList.options[serviceModifierCount].value==' + fieldModifiers[fieldModifierCount] + ') {';
                popUpHTML += '\n		serviceModifiersList.options[serviceModifierCount].selected = true;';
                popUpHTML += '\n	}//end if serviceModifiers';
            }//end for fieldModifiers
            popUpHTML += '\n }//end for serviceModifiers';
        }//end if fieldModifiers
        else {
            popUpHTML += '\n document.forms[0].serviceModifiers.value="-1";';
        }
		//////////// end multiple modifiers
        popUpHTML += '</script>';
        popUpHTML += '</body>';
        popUpHTML += '</html>';
        doc.write(popUpHTML);
    }
    else {
        //popUp.focus();
    }
}
//var wins;
function openNewWindow(theURL,winName,features) {
   window.open(theURL,winName,features);
}



function setParentToken(formCounter) {
    return ;
    var frm ;
    if (formCounter) {
        frm = document.forms[formCounter];
    }
    else {
        frm = document.forms[0];
    }
    win = window.opener;
    while (win) {
        if (!win.closed) {
            if (win.document.forms) {
                for (i = 0; i < win.document.forms.length; i++) {
                    if (win.document.forms[i]) {
                        if (win.document.forms[i].elements["org.apache.struts.taglib.html.TOKEN"]
                                && frm.elements["org.apache.struts.taglib.html.TOKEN"]) {
                            win.document.forms[i].elements["org.apache.struts.taglib.html.TOKEN"].value = frm.elements["org.apache.struts.taglib.html.TOKEN"].value;
                        }
                    }
                }
            }
            win = win.opener
        }
        else {
            win = null;
        }
    }
}

/**
 * Javascript method added for disbling a image button. Method requires an id of the link.
 * @author M.A.Q
 * @created on 28th January 2005
 */

function disableLink(id) {

    var link = document.getElementById(id);

    if (link.onclick)
        link.oldOnClick = link.onclick;
    link.onclick = cancelLink;
    if (link.style)
        link.style.cursor = 'default';
}

/**
 * Javascript method added for enabling a image button. Method requires an id of the link.
 * @author M.A.Q
 * @created on 28th January 2005
 */

function enableLink(id) {

    var link = document.getElementById(id);

    link.onclick = link.oldOnClick ? link.oldOnClick : null;
    if (link.style)
        link.style.cursor = 'hand';

}

function cancelLink() {
    return false;
}

/**
 * Javascript method added for disabling all image buttons on whole page. Method requires an id of the link.
 * @author M.A.Q
 * @created on 28th January 2005
 */

function disableAllLinks(documentObj) {
    var objects = documentObj.getElementsByTagName("a");

    for (i = 0; i < objects.length; i++) {
        if (objects[i].id.indexOf("disableLink") != -1) {
            disableLink(objects[i].id);
        }
    }


}

/**
 * Javascript method added for enabling all image buttons on whole page. Method requires an id of the link.
 * @author M.A.Q
 * @created on 28th January 2005
 */

function enableAllLinks(documentObj) {
    var objects = documentObj.getElementsByTagName("a");

    for (i = 0; i < objects.length; i++) {
        if (objects[i].id.indexOf("disableLink") != -1) {
            enableLink(objects[i].id);
        }
    }

}

/**
 * function to move selected General Appearances into the corresponding text area. The selected values are
 * inserted into the textarea in the following format value, value, value...... and value
 * @author M.A.Q
 * @created on Feb 01, 2005
 */

function generateSentence(list, textArea) {

    if (list.options.selectedIndex <= -1)
        return;

    tArea = "";

    var selectedOptions = new Array();
    var j = 0;

    for (i = 0; i < list.options.length; i++) {
        if (list.options[i].selected)
            selectedOptions[j++] = list.options[i].value;

    }


    for (i = 0; i < selectedOptions.length; i++) {

        if (i == selectedOptions.length - 2)
            tArea += selectedOptions[i];
        else if (i == selectedOptions.length - 1 && selectedOptions.length > 1)
            tArea += " and " + selectedOptions[i];
        else if (selectedOptions.length > 1)
            tArea += selectedOptions[i] + ", ";
        else
            tArea += selectedOptions[i];

    }


    textArea.value = tArea;
}


/**
 * function to highlitght General Appearances in the select box while page load
 * @author M.A.Q
 * @created on Feb 01, 2005
 */


function selectSentences(list, tArea)
{

    var separator = ", ";
    var tokenizer = tArea.value.split(separator);
    var token = "";

    for (x = 0; x < tokenizer.length; x++) {
        token = tokenizer[x]

        if (x != tokenizer.length - 1) {
            selectSentence(token, list);
        } else { // if ends
            lastToken = token.split(" and ");

            for (j = 0; j < lastToken.length; j++) {
                selectSentence(lastToken[j], list);
            } // inner loop ends

        } // else ends

    } // outer loop ends

} // function ends

/*
helping function to move highlitght General Appearances in the select box

@author M.A.Q
*/

function selectSentence(val, list)
{

    for (i = 0; i < list.options.length; i++) {
        if (list.options[i].value == val)
            list.options[i].selected = true;

    }

}


function formatFCP(h) {

    if (h.value.length == 10) {
        var tmpPhone = h.value;
        h.value = '(' + tmpPhone.substring(0, 3) + ') ' + tmpPhone.substring(3, 6) + '-' + tmpPhone.substring(6, 10);

    }
}	//end of function

/*
Remove mask for Fax, Cell, Pager number
@author Farhan Parpia
*/
function unformatFCP(h) {

    if (h.value.length == 0) {
        return false;
    }
    if (h.value.length > 13) {
        var tmpFCP = removeChar(
                removeChar(
                        removeChar(
                                removeChar(
                                        h.value.substring(0, 14)
                                        , '(')
                                , ')')
                        , '-')
                , ' ');
   // var tmpExt = h.value.substring(20);
        if (isNaN(tmpFCP)) {
            //			alert('Characters are not allowed in phone number.');
            h.focus();
            return false;
        }
    }
    h.value = tmpFCP
}//end of function

/*
Mask Format on Fax, Cell, Pager Feild
@author Farhan Parpia
*/

function keyPressOnFCP(h) {
    if (event.keycode == 8) {
        ;
    } else if (h.value.length == 3) {
        h.value = '(' + h.value + ') ';
    } else if (h.value.length == 9) {
        h.value = h.value + '-';
    }
}//end of function

/*
Check the Format for Fax, Cell, Pager Feild
author Farhan Parpia
*/

function checkPhone(h, title, required)
{
    var errors = '';
    //alert((h.value.substring(1, 4)) + isNumeric(h.value.substring(1, 3)));
    //alert((h.value.substring(6, 8)) + isNumeric(h.value.substring(6, 8)));
    //alert((h.value.substring(10, 14)) + isNumeric(h.value.substring(10, 14)));
    if (required) {
        if(h.value.length != 0)
        {
            if ( h.value.length < 14 || h.value.charAt(0) != '(' || h.value.charAt(4) != ')'
                || h.value.charAt(5) != ' ' || h.value.charAt(9) != '-' ||
            ( !isNumeric(h.value.substring(1, 4)) || !isNumeric(h.value.substring(6, 8)) || !isNumeric(h.value.substring(10, 14)) ))
            errors += '- ' + title + '                  number is Incorrect \n';
        }else{
            errors += ('- ' + title + ' is required.\n');
        }
    }
    else {
        if (h.value.length>1 && (h.value.length < 14 || h.value.charAt(0) != '(' || h.value.charAt(4) != ')' || h.value.charAt(5) != ' ' || h.value.charAt(9) != '-')) {
            errors += '- ' + title + ' number is Incorrect \n';
        }
    }
    return errors;
}

function blurOnFCP(h, fieldName) {
    if (h.value.length == 0) {
        return false;
    }
    var message;
    if (h.value.length < 14 || h.value.charAt(0) != '(' || h.value.charAt(4) != ')' || h.value.charAt(5) != ' ' || h.value.charAt(9) != '-') {
        message = 'Incorrect ' + fieldName + ' number.'
        alert(message);
        h.focus();

        return false;
    }

    tempnum = h;
    unformatFCP(tempnum);
    tempnum1 = tempnum.value;

//alert(tempnum1);
    //	tempnum1 = removeCharAt(tempnum1,';',10);

    formatFCP(h);


//	alert(tempnum.value )
    //	alert(tempnum1 )

    if (tempnum1.length < 10 || isNaN(tempnum1) || tempnum1.indexOf('e') > -1 || tempnum1.indexOf('.') > -1) {
        h.value = "";
        h.focus();
        message = fieldName + ' number cannot contain characters.'
        alert(message);

        return false;
    }

}//end of function

/**
 * functions checks/unchecks all Checkboxes on page
 * @author M.A.Q
 * @created on Feb 10, 2005
 */

function checkUncheckAll(chkBoxes) {
    if (chkBoxes != null) {
        if (!chkBoxes.length) {
            chkBoxes.checked = event.srcElement.checked;
        } else {
            for (i = 0; i < chkBoxes.length; i++) {
                chkBoxes[i].checked = event.srcElement.checked;
            }
        } // end of if
    } // end of if
}

/**
 * functions returns next date in following format 'yyyy-mm-dd', and expects date same format
 * @author M.A.Q
 * @created on Feb 10, 2005
 */
function getNextDate(strDate) {

    return getNextPreviousDate(true, strDate);
}

/**
 * functions returns next date in following format 'yyyy-mm-dd', and expects date same format
 * @author M.A.Q
 * @created on Feb 10, 2005
 */

function getPreviousDate(strDate) {

    return getNextPreviousDate(false, strDate);
}


/**
 * functions returns next/previous date in following format 'yyyy-mm-dd', and expects date same format
 * @author M.A.Q
 * @created on Feb 10, 2005
 */

function getNextPreviousDate(bln, strDate) {
    var frm = document.forms[0];
    var tmpDate = strDate;
    var tmpMonth = 0;
    var tmpDay = 0;
    var tmpYear = 0;

    if (tmpDate.length > 0) {
        var dateParts = strDate.split("-");
        tmpYear = parseInt(dateParts[0]);
        if (dateParts[1].length == 2 && dateParts[1].charAt(0) == "0") {
            tmpMonth = parseInt(dateParts[1].charAt(1));
        }
        else {
            tmpMonth = parseInt(dateParts[1]);
        } // end of else
        tmpMonth = tmpMonth - 1;
        if (dateParts[2].length == 2 && dateParts[2].charAt(0) == "0") {
            tmpDay = parseInt(dateParts[2].charAt(1));
        }
        else {
            tmpDay = parseInt(dateParts[2]);
        } // end of else
    } // end of if
    else {
        var tmpCurrDate = new Date();
        tmpMonth = tmpCurrDate.getMonth();
        tmpDay = tmpCurrDate.getDate();
        tmpYear = tmpCurrDate.getYear();
    } // end of else

    if (bln == true) {
        tmpDay++;
    } // end of if
    else {
        tmpDay--;
    } // end of else

    var newDate = new Date(tmpYear, tmpMonth, tmpDay);
    tmpMonth = newDate.getMonth() + 1;
    tmpDay = newDate.getDate();
    tmpYear = newDate.getYear();

    if (tmpMonth < 10) {
        tmpMonth = "0" + tmpMonth;
    } // end of if
    if (tmpDay < 10) {
        tmpDay = "0" + tmpDay;
    }
    tmpDate = tmpYear + "-" + tmpMonth + "-" + tmpDay;

    return tmpDate;

} // end of function nextDate

/**
 * Helper function used in makeURL() method
 * @author M.A.Q
 */

function elementIsEmpty(frm, elem) {

    if (elem.type == "text" || elem.type == "hidden") {
        return isEmpty(elem.value);
    } else if (elem.type == "select-one" || elem.type == "select-multiple") {
        return (elem.selectedIndex == 0);
    } else if (elem.type == "radio") {        
        return (getSelectedRadioValue(frm, elem.name).length == 0);
    } else if (elem.type == "checkbox") {
        return (getSelectedCheckboxValue(frm, elem.name).length == 0);
    }

} // end of func elementIsEmpty

/**
 * Method used to generate URLs generallly for search result pages, so that search results
 * can be retained when page is revisited.
 * @param frm : form object
 * @param urlPrefix : url prefix eg:/billing/maintainLabOrderAction.do?actionType=search
 * @param elementNamesArray : names of foem elemnts to be included in the url
 * @author M.A.Q
 */

function makeURL(frm, urlPrefix, elementNamesArray) {

    var allElements = new Array();
    var elem;

    if (urlPrefix.indexOf("?") < 0)
        urlPrefix = urlPrefix + "?";

    for (i = 0; i < elementNamesArray.length; i++) {
        elem = eval("frm." + elementNamesArray[i]);

        if (!elementIsEmpty(frm, elem)) {
            allElements[allElements.length] = elem;
        } // if ends
    } // loop ends

    var url = urlPrefix;
    var urlAppender = "";

    for (i = 0; i < allElements.length; i++) {

        if (allElements[i].type == "text" || allElements[i].type == "hidden" || elem.type == "radio" || elem.type == "checkbox") {
            urlAppender = allElements[i].name + "=" + allElements[i].value;
        }
        else if (allElements[i].type == "select-one" || allElements[i].type == "select-multiple") {
            urlAppender = allElements[i].name + "=" + allElements[i].options[allElements[i].selectedIndex].value;
        }
        url += "&" + urlAppender;

    } // end of loop


    return escape(url);

}// end of func makeURL


// ------------------------------------------------------------------
// Method takes a dateString, its current date format and a new date
// format and returns date in new format
// @author Faisal Moin Khan
// @created on 11th April 2005
// ------------------------------------------------------------------
function convertDateFormat(dateString, currentFormat, newFormat) {
    if (isEmpty(dateString) || isEmpty(currentFormat) || isEmpty(newFormat)) {
        return;
    }
    var dateObject = getDateFromFormat(dateString, currentFormat);
    var formattedDateString = formatDateObject(dateObject, newFormat);
    return formattedDateString;
}
// ------------------------------------------------------------------
// formatDateObject (date_object, format)
// Returns a date string in the output format specified.
// The format string uses the same abbreviations as in getDateFromFormat()
// ------------------------------------------------------------------
function formatDateObject(date, format) {
    format = format + "";
    var result = "";
    var i_format = 0;
    var c = "";
    var token = "";
    var y = date.getYear() + "";
    var M = date.getMonth() + 1;
    var d = date.getDate();
    var E = date.getDay();
    var H = date.getHours();
    var m = date.getMinutes();
    var s = date.getSeconds();
    var yyyy,yy,MMM,MM,dd,hh,h,mm,ss,ampm,HH,H,KK,K,kk,k;
	// Convert real date parts into formatted versions
    var value = new Object();
    if (y.length < 4) {
        y = "" + (y - 0 + 1900);
    }
    value["y"] = "" + y;
    value["yyyy"] = y;
    value["yy"] = y.substring(2, 4);
    value["M"] = M;
    value["MM"] = LZ(M);
    value["MMM"] = MONTH_NAMES[M - 1];
    value["NNN"] = MONTH_NAMES[M + 11];
    value["d"] = d;
    value["dd"] = LZ(d);
    value["E"] = DAY_NAMES[E + 7];
    value["EE"] = DAY_NAMES[E];
    value["H"] = H;
    value["HH"] = LZ(H);
    if (H == 0) {
        value["h"] = 12;
    }
    else if (H > 12) {
        value["h"] = H - 12;
    }
    else {
        value["h"] = H;
    }
    value["hh"] = LZ(value["h"]);
    if (H > 11) {
        value["K"] = H - 12;
    } else {
        value["K"] = H;
    }
    value["k"] = H + 1;
    value["KK"] = LZ(value["K"]);
    value["kk"] = LZ(value["k"]);
    if (H > 11) {
        value["a"] = "PM";
    }
    else {
        value["a"] = "AM";
    }
    value["m"] = m;
    value["mm"] = LZ(m);
    value["s"] = s;
    value["ss"] = LZ(s);
    while (i_format < format.length) {
        c = format.charAt(i_format);
        token = "";
        while ((format.charAt(i_format) == c) && (i_format < format.length)) {
            token += format.charAt(i_format++);
        }
        if (value[token] != null) {
            result = result + value[token];
        }
        else {
            result = result + token;
        }
    }
    return result;
}
// ------------------------------------------------------------------
// Utility functions for parsing in getDateFromFormat()
// ------------------------------------------------------------------
function _isInteger(val) {
    var digits = "1234567890";
    for (var i = 0; i < val.length; i++) {
        if (digits.indexOf(val.charAt(i)) == -1) {
            return false;
        }
    }
    return true;
}
function _getInt(str, i, minlength, maxlength) {
    for (var x = maxlength; x >= minlength; x--) {
        var token = str.substring(i, i + x);
        if (token.length < minlength) {
            return null;
        }
        if (_isInteger(token)) {
            return token;
        }
    }
    return null;
}
function LZ(x) {
    return(x < 0 || x > 9 ? "" : "0") + x
}
var MONTH_NAMES = new Array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec');
var DAY_NAMES = new Array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat');
// ------------------------------------------------------------------
// getDateFromFormat( date_string , format_string )
//
// This function takes a date string and a format string. If the date
// string matches the format string, it returns the a date object.
// If it does not match, it returns 0.
// ------------------------------------------------------------------
// These functions use the same 'format' strings as the
// java.text.SimpleDateFormat class, with minor exceptions.
// The format string consists of the following abbreviations:
//
// Field        | Full Form          | Short Form
// -------------+--------------------+-----------------------
// Year         | yyyy (4 digits)    | yy (2 digits), y (2 or 4 digits)
// Month        | MMM (name or abbr.)| MM (2 digits), M (1 or 2 digits)
//              | NNN (abbr.)        |
// Day of Month | dd (2 digits)      | d (1 or 2 digits)
// Day of Week  | EE (name)          | E (abbr)
// Hour (1-12)  | hh (2 digits)      | h (1 or 2 digits)
// Hour (0-23)  | HH (2 digits)      | H (1 or 2 digits)
// Hour (0-11)  | KK (2 digits)      | K (1 or 2 digits)
// Hour (1-24)  | kk (2 digits)      | k (1 or 2 digits)
// Minute       | mm (2 digits)      | m (1 or 2 digits)
// Second       | ss (2 digits)      | s (1 or 2 digits)
// AM/PM        | a                  |
//
// ------------------------------------------------------------------
function getDateFromFormat(val, format) {
    val = val + "";
    format = format + "";
    var i_val = 0;
    var i_format = 0;
    var c = "";
    var token = "";
    var token2 = "";
    var x,y;
    var now = new Date();
    var year = now.getYear();
    var month = now.getMonth() + 1;
    var date = 1;
    var hh = now.getHours();
    var mm = now.getMinutes();
    var ss = now.getSeconds();
    var ampm = "";

    while (i_format < format.length) {
        // Get next token from format string
        c = format.charAt(i_format);
        token = "";
        while ((format.charAt(i_format) == c) && (i_format < format.length)) {
            token += format.charAt(i_format++);
        }
		// Extract contents of value based on format token
        if (token == "yyyy" || token == "yy" || token == "y") {
            if (token == "yyyy") {
                x = 4;
                y = 4;
            }
            if (token == "yy") {
                x = 2;
                y = 2;
            }
            if (token == "y") {
                x = 2;
                y = 4;
            }
            year = _getInt(val, i_val, x, y);
            if (year == null) {
                return 0;
            }
            i_val += year.length;
            if (year.length == 2) {
                if (year > 70) {
                    year = 1900 + (year - 0);
                }
                else {
                    year = 2000 + (year - 0);
                }
            }
        }
        else if (token == "MMM" || token == "NNN") {
            month = 0;
            for (var i = 0; i < MONTH_NAMES.length; i++) {
                var month_name = MONTH_NAMES[i];
                if (val.substring(i_val, i_val + month_name.length).toLowerCase() == month_name.toLowerCase()) {
                    if (token == "MMM" || (token == "NNN" && i > 11)) {
                        month = i + 1;
                        if (month > 12) {
                            month -= 12;
                        }
                        i_val += month_name.length;
                        break;
                    }
                }
            }
            if ((month < 1) || (month > 12)) {
                return 0;
            }
        }
        else if (token == "EE" || token == "E") {
            for (var i = 0; i < DAY_NAMES.length; i++) {
                var day_name = DAY_NAMES[i];
                if (val.substring(i_val, i_val + day_name.length).toLowerCase() == day_name.toLowerCase()) {
                    i_val += day_name.length;
                    break;
                }
            }
        }
        else if (token == "MM" || token == "M") {
            month = _getInt(val, i_val, token.length, 2);
            if (month == null || (month < 1) || (month > 12)) {
                return 0;
            }
            i_val += month.length;
        }
        else if (token == "dd" || token == "d") {
            date = _getInt(val, i_val, token.length, 2);
            if (date == null || (date < 1) || (date > 31)) {
                return 0;
            }
            i_val += date.length;
        }
        else if (token == "hh" || token == "h") {
            hh = _getInt(val, i_val, token.length, 2);
            if (hh == null || (hh < 1) || (hh > 12)) {
                return 0;
            }
            i_val += hh.length;
        }
        else if (token == "HH" || token == "H") {
            hh = _getInt(val, i_val, token.length, 2);
            if (hh == null || (hh < 0) || (hh > 23)) {
                return 0;
            }
            i_val += hh.length;
        }
        else if (token == "KK" || token == "K") {
            hh = _getInt(val, i_val, token.length, 2);
            if (hh == null || (hh < 0) || (hh > 11)) {
                return 0;
            }
            i_val += hh.length;
        }
        else if (token == "kk" || token == "k") {
            hh = _getInt(val, i_val, token.length, 2);
            if (hh == null || (hh < 1) || (hh > 24)) {
                return 0;
            }
            i_val += hh.length;
            hh--;
        }
        else if (token == "mm" || token == "m") {
            mm = _getInt(val, i_val, token.length, 2);
            if (mm == null || (mm < 0) || (mm > 59)) {
                return 0;
            }
            i_val += mm.length;
        }
        else if (token == "ss" || token == "s") {
            ss = _getInt(val, i_val, token.length, 2);
            if (ss == null || (ss < 0) || (ss > 59)) {
                return 0;
            }
            i_val += ss.length;
        }
        else if (token == "a") {
            if (val.substring(i_val, i_val + 2).toLowerCase() == "am") {
                ampm = "AM";
            }
            else if (val.substring(i_val, i_val + 2).toLowerCase() == "pm") {
                ampm = "PM";
            }
            else {
                return 0;
            }
            i_val += 2;
        }
        else {
            if (val.substring(i_val, i_val + token.length) != token) {
                return 0;
            }
            else {
                i_val += token.length;
            }
        }
    }
	// If there are any trailing characters left in the value, it doesn't match
    if (i_val != val.length) {
        return 0;
    }
	// Is date valid for month?
    if (month == 2) {
        // Check for leap year
        if (( (year % 4 == 0) && (year % 100 != 0) ) || (year % 400 == 0)) { // leap year
            if (date > 29) {
                return 0;
            }
        }
        else {
            if (date > 28) {
                return 0;
            }
        }
    }
    if ((month == 4) || (month == 6) || (month == 9) || (month == 11)) {
        if (date > 30) {
            return 0;
        }
    }
	// Correct hours value
    if (hh < 12 && ampm == "PM") {
        hh = hh - 0 + 12;
    }
    else if (hh > 11 && ampm == "AM") {
        hh -= 12;
    }
    var newdate = new Date(year, month - 1, date, hh, mm, ss);
    return newdate;
}

/**
 function for selecting/de-selecting a radio button.
 @author M.A.Q
 */

function handleRadio(frm, radio) {

    var radios = eval("frm." + radio.name);

    if (!radio.isChecked)
        radio.isChecked = true;
    else
        radio.isChecked = false;

    radio.checked = radio.isChecked;

    if (radios.length) {
        for (i = 0; i < radios.length; i++) {
            if (radio != radios[i]) {
                if (radio.isChecked) {
                    radios[i].checked = !radio.isChecked;
                    radios[i].isChecked = !radio.isChecked;
                } else {
                    radios[i].checked = radio.isChecked;
                    radios[i].isChecked = radio.isChecked;
                }
            }
        }
    }
}

/*
function to be called on double click of date controls
author Aqeela Hemani
*/
function onDbClickDate(dateControl, frmCounter) {

    if (!dateControl.readOnly && !dateControl.disabled) {
        dateControl.value = (blurOnDate(dateControl, true) ? dateControl.value : '');
        if (!frmCounter) {
            showCalendarPopup(dateControl.name, document.forms[0], false, 'mm-dd-yyyy');
        }
        else {
            showCalendarPopup(dateControl.name, document.forms[frmCounter], false, 'mm-dd-yyyy');
        }
    }
}

function onDbClickDateTime(dateControl, frmCounter) {
    if (!dateControl.readOnly && !dateControl.disabled) {
        dateControl.value = (onBlurDateTime(dateControl, true) ? dateControl.value : '');
        if (!frmCounter) {
            showCalendarPopup(dateControl.name, document.forms[0], false, 'mm-dd-yyyy');
        }
        else {
            showCalendarPopup(dateControl.name, document.forms[frmCounter], false, 'mm-dd-yyyy');
        }
    }
}

/*
returns string with trailing .. if string length is greater then specified length
author Aqeela Hemani
*/
function truncateString(str, len) {
    if (str.length <= len) {
        return str;
    }
    else {
        return str.substring(0, len) + '..';
    }
}

/*
Method strips out a subString from a given source string and
returns the source string.
@author Faisal Moin Khan
@added on 11th July 2005
*/
function removeSubstring(sourceString, subString) {
    if (isEmpty(sourceString)) {
        return '';
    }
    if (isEmpty(subString)) {
        return sourceString;
    }
    return sourceString.replace(subString, '');
}

/*
@author Aqeela Hemani
*/
function onKeyUpDateTime(control) {
    //	alert(control.value.length )
    if ((control.value.length == 2 || control.value.length == 5)) {
        control.value = control.value + "-"
    }
    else if (control.value.length == 10) {
        control.value = control.value + " "
    }
    else if (control.value.length == 13) {
        control.value = control.value + ":"
    }
    else if (control.value.length == 16) {
        control.value = control.value + " pm"
    }

}
function onBlurDateTime(control, dontShowAlert) {
    //var regex = new RegExp(/^((((([0-1]?\d)|(2[0-8]))\-((0?\d)|(1[0-2])))|(29\-((0?[1,3-9])|(1[0-2])))|(30\-((0?[1,3-9])|(1[0-2])))|(31\-((0?[13578])|(1[0-2]))))\-[1-9]\d{3})|(29\-0?2\-(((([2468][048])|([13579][26]))00)|([1-9]\d(([02468][48])|([13579][26])))))\s(([01]?\d)|(2[0-3]))(:[0-5]?\d){2}$/);
    control.value = trim(control.value);
    if (control.value.length == 0) {
        return;
    }
    var regex = new RegExp(/^((0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])-([1-9][0-9][0-9][0-9])(\s)(0[1-9]|1[012])(:[0-5]\d)(\s[AaPp][Mm]))$/);

    if (!regex.test(control.value)) {
        if (!dontShowAlert) {
            alert("Datetime is not in correct format.");
            control.focus();
        }

        return false;
    }
    else {
        var date = getDateComponent(control.value);
        var dateParts = date.split('-');
        var tmpYear = parseInt(dateParts[2]);
        if (tmpYear < 1900) {
            if (!dontShowAlert) {
                alert('Incorrect Date\n-Date should be in MM-DD-YYYY\n-Please check your Month, Day, Year range. Year should be greater then 1900.\n-Please check LEAP YEAR.');
                control.focus();
            }

            return false;

        }

        var tmpMonth = parseInt((dateParts[0].charAt(0) == '0' ? dateParts[0].charAt(1) : dateParts[0]));
        var tmpDay = parseInt((dateParts[1].charAt(0) == '0' ? dateParts[1].charAt(1) : dateParts[1]));
        var tmpDate = new Date(tmpYear, tmpMonth - 1, tmpDay);
	//	 alert(tmpYear + "  ddd  " + tmpDate.getFullYear() + " ddddd  " + tmpDate);
        if (tmpMonth != (tmpDate.getMonth() + 1) || tmpDay != tmpDate.getDate() || tmpYear != tmpDate.getFullYear()) {
            if (!dontShowAlert) {
                alert('Incorrect Date \n-Please check your Month, Day, Year range. Year should be greater then 1900.\n-Please check LEAP YEAR.');
                control.focus();

            }
            return false;
        }

    }
    /*
     regex = new RegExp(/((0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])-([1-9][0-9][0-9][0-9]))/);
     var ar = regex.exec(control.value)
     alert(ar[1])
     */
    /*regex = new RegExp(/((0[1-9]|1[012])(:[0-5]\d)(\s[AaPp][Mm]))/);
     var ar = regex.exec(control.value)
     alert(ar[1])*/

}

function getDateComponent(val) {
    var regex = new RegExp(/((0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])-([1-9][0-9][0-9][0-9]))/);
    var ar = regex.exec(val)
    return ar[1];
}

function geTimeComponent(val) {
    var regex = new RegExp(/((0[1-9]|1[012])(:[0-5]\d)(\s[AaPp][Mm]))/);
    var ar = regex.exec(val)
    return ar[1];
}

//Added By Haroon Masood 30 Sept 2005
function selectFirstRadioButton(radioButtonObject)
{
    if (radioButtonObject != null)
    {
        var objTarget;
        if (radioButtonObject.length > 0)
            objTarget = radioButtonObject[0];
        else
            objTarget = radioButtonObject;
        objTarget.click();
    }
}

//added by Haroon Masood 3 Oct 2005
function selectRadioButton(radioButtonObject, indexToSelect)
{
    if (radioButtonObject != null && indexToSelect >= 0)
    {
        var objTarget;
        if (radioButtonObject.length > 0)
            objTarget = radioButtonObject[indexToSelect];
        else
            objTarget = radioButtonObject;
        objTarget.click();
    }
}
// added by Aqeela
function getFormatedSentence(components, format) {
    if (components.length == 1) {
        return components[0];
    }

    if (format == null) {
        format = SENTENCE_FORMAT_COMMASEPARATED;
    }
    var str = "";
    for (var i = 0; i < components.length - 1; i++) {
        if (i > 0) {
            if (format == SENTENCE_FORMAT_COMMASEPARATED_AND
                    || format == SENTENCE_FORMAT_COMMASEPARATED_OR
                    || format == SENTENCE_FORMAT_COMMASEPARATED) {
                str += ", ";
            }
        }
        str += components[i];
    }
    if (format == SENTENCE_FORMAT_COMMASEPARATED_AND) {
        str += " and ";
    }
    else if (format == SENTENCE_FORMAT_COMMASEPARATED_OR) {
        str += " or ";
    }
    else if (format == SENTENCE_FORMAT_COMMASEPARATED) {
        str += ", ";
    }

    str += components[components.length - 1];
    return str;
}
var SENTENCE_FORMAT_COMMASEPARATED = 0;
var SENTENCE_FORMAT_COMMASEPARATED_AND = 1;
var SENTENCE_FORMAT_COMMASEPARATED_OR = 2;


/**
 @author:Vicky
	checkMemberId function checks the memberId TextField value according to its InsuranceTypeId
	MemberId Format: XXXXXXXXXC(X)  where X respresent number and C represents character and last X is optional.
	Another rule added: CCXXXXXXXXX

 */

function checkMemberId(memberId, insuranceTypeId, title, required) {

    var errors = ""; 
	var memberIdFilter = /\b\d{9}[a-zA-Z]{1}\w{0,1}$\b/;
	var memberIdFilter1 = /\b\D{2}\d{9}\b/;

	if(required) {
		
		if( insuranceTypeId == "MB" ) {
			if(memberId.length == 0 )
				errors += title + " is required.\n";
			else if(! ( memberIdFilter.test(memberId) || memberIdFilter1.test(memberId) )) 
				errors += title + " is invalid.\n";
			else if( memberId.indexOf(' ') != -1)
				errors += title + " is invalid.\n";
	
		}
		else if(memberId.length == 0 )
				errors += title + " is required.\n";
	}
	return errors;
}

function create_request_string(theForm)
{
    var reqStr = "";

    for (i = 0; i < theForm.elements.length; i++)
    {
        isFormObject = false;

        if (theForm.elements[i].tagName == "INPUT")
        {

            switch (theForm.elements[i].type)
                    {
                case "text":
                case "hidden":
                    reqStr += theForm.elements[i].name + "=" + theForm.elements[i].value;
                    isFormObject = true;
                    break;

                case "checkbox":
                    if (theForm.elements[i].checked)
                    {
                        reqStr += theForm.elements[i].name + "=" + theForm.elements[i].value;
                    } else {
                        reqStr += theForm.elements[i].name + "=";
                    }
                    isFormObject = true;
                    break;

                case "radio":
                    if (theForm.elements[i].checked)
                    {
                        reqStr += theForm.elements[i].name + "=" + theForm.elements[i].value;
                        isFormObject = true;
                    }
            }
        }

        if (theForm.elements[i].tagName == "SELECT")
        {
            var sel = theForm.elements[i];
            reqStr += sel.name + "=" + sel.options[sel.selectedIndex].value;
            isFormObject = true;
        }

        if ((isFormObject) && ((i + 1) != theForm.elements.length))
        {
            reqStr += "&";
        }

    }
    return reqStr;
}

function getRadioButtonValue(radioButtonObject) {
    var val;
    for( i = 0; i < radioButtonObject.length; i++ ) {
        if( radioButtonObject[i].checked )  {
            val = radioButtonObject[i].value;
            return val;
        }
    }

}

function isRadioButtonSelected(frm, controlName) {

        var i = 0;
        var elements = frm.elements[controlName];

        if (elements) {
            if (elements.length) {
                for (i = 0; i < elements.length; i++) {
                    if (elements[i].type == "radio" && elements[i].checked == true) {
                        return true;
                    } // end of if
                }// end of for
            }// end of if
            else if (elements.checked) {                
                return true;
            }
        }
       return false;
}


function isMaxLength(obj){
	var mlength=obj.getAttribute? parseInt(obj.getAttribute("maxlength")) : ""
	if (obj.getAttribute && obj.value.length>mlength)
	obj.value=obj.value.substring(0,mlength)
}

function destroySpryObj(spryObj) {

	 if(spryObj) {
      spryObj.reset();
      spryObj.destroy();
      }

}


/**
 * To make text compatible to be passed in URL as request parameter.
 * Note : spaces are converted to %20 by default when occured in a URL as text
 * Help from resource http://code.cside.com/3rdpage/us/newLine.html
 * added by MFB 
 */
function encodeTextForURL(source) {
    /* rather than manually replace character to encode for URL we should use escape method as
       described in http://www.permadi.com/tutorial/urlEncoding/
    //source = source.replace("\n","%0A");  // replace newline with its URL code
    source = source.replace(/\n/g,"%0A");   // replace all occurrences of  newline with its URL code
    //source = source.replace("\r","%0D");  // replace carriage return with its URL code
    source = source.replace(/\r/g,"%0D");   // replace all occurrences of carriage return with its URL code

    source = source.replace("%", "%25");   // % percentage character

    source = source.replace("&", "%26");   // & AND character
    source = source.replace(" ", "%20")    //   space character
    source = source.replace(";", "%3B")    //   space character
    */
    source = escape(source);
    source = source.replace("+", "%2B");   // & AND character
    source = source.replace("/", "%2F")    //   space character


    return source;
}

function encodeTextForHtml(source) {

      source = source.replace(/\n/g,"<br>");
      return source;
  }

function getFileExtension(fileName){
    var fileExt;

    if(fileName.length > 0){
        fileExt=fileName.substr(fileName.length-4,4);
    }

    return fileExt;
}

function appendSsnZeros(ssn)
{
    var ssnWithZeros = ssn;
    if(ssn.length > 0)
    {
	while (ssnWithZeros.length < 9)
	{
	    ssnWithZeros = "0"+ssnWithZeros;
	}
    }
    return ssnWithZeros;
}

/**
 * The DEBUG variable should be set true for debugging on and false for debugging off
 * at the start of jsp / html using this method
 * @param str
 */
function debug(str)
{
    if(DEBUG)
    {
	alert(str);
    }
}

function  setElemPosition (elem, x, y, refElemY){
    var obj = elem;
    obj.style.left = x;
    obj.style.top = y + refElemY;
};

