
/* ======================================== VALIDATION ROUTINE ========================================

/* Function to validate required fields */
function TValidateRequiredField(arrFieldIDs)
{

	if(arrFieldIDs.length > 0)
	{
		for(var i=0;i<arrFieldIDs.length;i++)
		{

			if(trim(document.getElementById(arrFieldIDs[i]).value) == "" || document.getElementById(arrFieldIDs[i]).value == "-1")
			{
				WarningBox('Fields marked as * are required');
				return false;
			}

		}
		return true;		
	}
}
/* Function to check valid Email Address */

function CheckEmailID(paraEmail)
{
			   
					var sEmail = document.getElementById(paraEmail).value;
			     
					var atsym = sEmail.indexOf("@");
					var period = sEmail.lastIndexOf('.');
					var space = sEmail.indexOf(' ');
					var length = sEmail.length - 1;
					
					if ((atsym < 1) || (period <= atsym+1) || (period == length ) || (space != -1)) 
					{ 
							WarningBox('Please enter a valid email address !');
						    document.getElementById(paraEmail).focus();
							return false;
					}
					return true;
}

/* Function to check special characters*/

function CheckSpecialChar(vObject,vType)
{
	var iChars;
	var AlertMsg;

	if(vType == "String")
	{

		iChars = "`!@#$%^&*()+=-[]\\\;,./{}|\":<>?1234567890";
		AlertMsg ="Special characters are not allowed!"; 
	}
	else if (vType == "Numeric")
	{
		iChars = "`!@#$%^&*()+=-[]\\\;,./{}|\:<>? ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'''";
		AlertMsg ="Invalid value";

	}
	else if (vType == "AlphaNumeric")
	{
		iChars = "`!@#$%^&*()+=[]\\\';,./{}|\":<>?";
		AlertMsg ="Special characters are not allowed!"; 
	}
	else if(vType == "SingleQuote")
	{
		iChars = "'";
		AlertMsg ="Single quote is not allowed!"; 
	}
	for (var i = 0; i < document.getElementById(vObject).value.length; i++) 
	{
		if (iChars.indexOf(document.getElementById(vObject).value.charAt(i)) != -1) 
		{

			WarningBox(AlertMsg);
			document.getElementById(vObject).focus();
			return false;
		}
	}
	return true;	
}

/* ======================================== STRING MANIPULATION ROUTINES ========================================


/*Function trim extra spaces */
function trim(inputString) 
{
	if (typeof inputString != "string") { return inputString; }
	var retValue = inputString;
	var ch = retValue.substring(0, 1);
	while (ch == " ") 
	{ // Check for spaces at the beginning of the string
		retValue = retValue.substring(1, retValue.length);
		ch = retValue.substring(0, 1);
	}
	ch = retValue.substring(retValue.length-1, retValue.length);
	while (ch == " ") 
	{ // Check for spaces at the end of the string
		retValue = retValue.substring(0, retValue.length-1);
		ch = retValue.substring(retValue.length-1, retValue.length);
	}
	while (retValue.indexOf("  ") != -1)
	{ // Note that there are two spaces in the string - look for multiple spaces within the string
		retValue = retValue.substring(0, retValue.indexOf("  ")) + retValue.substring(retValue.indexOf("  ")+1, retValue.length); // Again, there are two spaces in each of the strings
	}
	return retValue; // Return the trimmed string back to the user
} 


/* Function to format numbers*/	
function formatNumber(obj, decimal) {
	//decimal  - the number of decimals after the digit from 0 to 3
	//-- Returns the passed number as a string in the xxx,xxx.xx format.

	anynum=eval(obj);

	divider =10;
	switch(decimal){
		case 0:
			divider =1;
			break;
		case 1:
			divider =10;
			break;
		case 2:
			divider =100;
			break;
		default:  	 //for 3 decimal places
			divider =1000;
	}

	workNum=Math.abs((Math.round(anynum*divider)/divider));

	workStr=""+workNum

			if (workStr.indexOf(".")==-1){workStr+="."}

	dStr=workStr.substr(0,workStr.indexOf("."));dNum=dStr-0
		pStr=workStr.substr(workStr.indexOf("."))

			 while (pStr.length-1< decimal){pStr+="0"}

	if(pStr =='.') pStr ='';

	//--- Adds a comma in the thousands place.    
	if (dNum>=1000) {
		dLen=dStr.length
			 dStr=parseInt(""+(dNum/1000))+","+dStr.substring(dLen-3,dLen)
	}

	//-- Adds a comma in the millions place.
	if (dNum>=1000000) {
		dLen=dStr.length
			 dStr=parseInt(""+(dNum/1000000))+","+dStr.substring(dLen-7,dLen)
	}
	retval = dStr + pStr
			 //-- Put numbers in parentheses if negative.
			 if (anynum<0) {retval="("+retval+")";}

	//retval =  "$"+retval    //You could include a dollar sign in the return value.

	obj = retval;

	return obj
}	

// Function to encode the text in textbox in the format in which it was entered //

function escapeValEnter(textarea,replaceWith)
{ 
	/* textarea is reference to that object, replaceWith is string that will replace the encoded return */
	textarea.value = escape(textarea.value) //encode textarea string's carriage returns
					 for(i=0; i<textarea.value.length; i++)//loop through string, replacing carriage return encoding with HTML break tag
	{       
		if(textarea.value.indexOf("%0D%0A") > -1)
		{ 
			textarea.value=textarea.value.replace("%0D%0A",replaceWith)  //Windows encodes returns as \r\n hex
		}
		else if(textarea.value.indexOf("%0A") > -1)
		{ 
			textarea.value=textarea.value.replace("%0A",replaceWith)  //Unix encodes returns as \n hex
		}
		else if(textarea.value.indexOf("%0D") > -1)
		{ 
			textarea.value=textarea.value.replace("%0D",replaceWith)  //Macintosh encodes returns as \r hex
		}
	}

	textarea.value=unescape(textarea.value) //unescape all other encoded characters
}

// Function to decode the encoded text //
function upescapeValEnter(textarea,replaceWith)
{ 
	//textarea is reference to that object, replaceWith is string that will replace the encoded return
	textarea.value = escape(textarea.value) //encode textarea string's carriage returns
					 for(i=0; i<textarea.value.length; i++) //loop through string, replacing carriage return encoding with HTML break tag
	{     
		if(textarea.value.indexOf(replaceWith) > -1)
		{
			textarea.value=textarea.value.replace(replaceWith,"%0D%0A") //Windows encodes returns as \r\n hex
		}
	}
	textarea.value=unescape(textarea.value) //unescape all other encoded characters
}

function SingleSelect(chkobj)
{	
	for(var item = 0; item < document.forms[0].elements.length; item++)
	{
		if (document.forms[0].elements[item].type == 'checkbox' && document.forms[0].elements[item].id != chkobj.id) 
		{
			document.forms[0].elements[item].checked = false;
		}
	}	
}

/* ======================================== ERROR/INFO/OK BOX ROUTINES ========================================

/* Note: In HTML / ASP USE BELOW FUNCTIONS. DO NOT USE SetTopStatus Function Directly */

function ErrorBox(strMessage, strCustomCtlId) {
    SetTopStatus("error", strMessage, strCustomCtlId);
}
function WarningBox(strMessage, strCustomCtlId) {
    SetTopStatus("warning", strMessage, strCustomCtlId);
}
function InfoBox(strMessage, strCustomCtlId) {
    SetTopStatus("information", strMessage, strCustomCtlId);
}
function QueryBox(strMessage, strCustomCtlId) {
    SetTopStatus("query", strMessage, strCustomCtlId);
}
function ClearTopStatus(strCustomCtlId)
{
	if(document.getElementById('divWarning') != null)
	{
		document.getElementById('divWarning').style.display='none';
	}
	else if(document.getElementById('divInformation') != null)
	{
		document.getElementById('divInformation').style.display='none';
	}
	else if(document.getElementById('divError') != null)
	{
		document.getElementById('divError').style.display='none';
	}
	else if(document.getElementById('divQuery') != null)
	{
		document.getElementById('divQuery').style.display='none';
	}

	if (strCustomCtlId == null || strCustomCtlId == '') {
	    if (document.getElementById('SpanTopStatus') != null)
	        document.getElementById('SpanTopStatus').innerHTML = "";
	}
	else {
	    if (document.getElementById(strCustomCtlId) != null)
	        document.getElementById(strCustomCtlId).innerHTML = "";
	}
}


/* NOTE: BELOW FUNCTIONS ARE PRIVATE AND NOT FOR REGULAR USE. 
MAKE SURE YOU GUYS USE RIGHT FUNCTION FOR RIGHT BOX. */
function SetTopStatus(strStatus,strMessage,strCustomCtlId) {
    window.scroll(0, 0);
    ClearTopStatus(strCustomCtlId);
	SetTopStatusExt(strStatus, strMessage, 'true', strCustomCtlId);
}

function SetTopStatusExt(strStatus, strMessage, tShow, strCustomCtlId)
{
	var ctldivGenMessage;
	var ctlSpanTopStatus;
	var strClassName="";
	var strdivId="";

	switch(strStatus.toLowerCase())
	{
		case "warning":
			strClassName = "warning";
			strdivId = "divWarning"
					   break;
		case "information":
			strClassName = "information";
			strdivId = "divInformation"
					   break;
		case "error":
			strClassName = "error";
			strdivId = "divError"
					   break;   
		case "query":
			strClassName = "query";
			strdivId = "divQuery"
					   break;
		default:
			strdivId = "divQuery"
    }
	if(strCustomCtlId == null || strCustomCtlId == '')
	    ctlSpanTopStatus = document.getElementById('SpanTopStatus');
	else
	    ctlSpanTopStatus = document.getElementById(strCustomCtlId);
	    
	if(ctlSpanTopStatus != null)
	{
		ctldivGenMessage = document.createElement("div");
		ctldivGenMessage.id=strdivId;
		ctldivGenMessage.className = strClassName;
		ctldivGenMessage.innerHTML=strMessage;
		(tShow == 'true') ?  (ctldivGenMessage.style.display='block') : (ctldivGenMessage.style.display='none');

		ctlSpanTopStatus.appendChild(ctldivGenMessage);
	}
	else
	{
		alert('SpanTopStatus element not found in page! Create this element to show messages');
	}
}



function TValidateControlWithMessage(objCtrlToValidate, strMessage, astrValidation) {

    var objControl = null;
    if (document.getElementById(objCtrlToValidate) == null)
        alert(objCtrlToValidate + " not found!");

    objControl = document.getElementById(objCtrlToValidate);

    if (astrValidation.length > 0) {

        for (var i = 0; i < astrValidation.length; i++) {

            if (objControl.value == astrValidation[i]) {
                ControlUIDesignValidator(objControl.id, strMessage, true);
                return false;
            }
        }

        ControlUIDesignValidator(objControl.id, strMessage, false);
        return true;
    }
}


function ControlUIDesignValidator(objCtrlToValidate, strMessage, tControlValidated) {

    var objControl = null;

    var strDivId = "";
    var objDivError = null;

    strDivId = "div_" + objCtrlToValidate;

    objControl = document.getElementById(objCtrlToValidate);

    if (document.getElementById(strDivId) != null && tControlValidated)
        return;
    else if (document.getElementById(strDivId) != null && !tControlValidated) {
    var objParentNode = document.getElementById(strDivId).parentNode;

    objParentNode.removeChild(document.getElementById(strDivId));
    objControl.className = "";
    }
    else if (document.getElementById(strDivId) == null && tControlValidated) {
        CreateControlInUI(objControl, "div", strDivId, strMessage);
    }
    return;
}

function CreateControlInUI(objControl, strElementType, strElementId, strMessage) {
    var iCurLeftPos = 0;
    var iCurTopPos = 0;
    var objDivError = document.createElement(strElementType);
    var objCtrl = objControl;

    objDivError.id = strElementId;
    objDivError.className = "diverrormsg";
    objDivError.style.display = "block";
    objDivError.innerHTML = strMessage;

    objDivError.style.left = objControl.offsetWidth + iCurLeftPos + "px";
    objDivError.style.top = objControl.offsetHeight + iCurTopPos + "px";

    objControl.className = "ctrlerror";

    if (objControl.offsetParent) {

        do {
            iCurLeftPos += objControl.offsetLeft;
            iCurTopPos += objControl.offsetTop;
        } while (objControl = objControl.offsetParent);
    }

    insertAfter(objDivError, objCtrl);

}

//create function, it expects 2 values.
function insertAfter(newElement, targetElement) {
    //target is what you want it to go after. Look for this elements parent.
    var parent = targetElement.parentNode;

    //if the parents lastchild is the targetElement...
    if (parent.lastchild == targetElement) {
        //add the newElement after the target element.
        parent.appendChild(newElement);
    } else {
        // else the target has siblings, insert the new element between the target and it's next sibling.
        parent.insertBefore(newElement, targetElement.nextSibling);
    }
}


// Navigation functions for firstpage,next page, etc

			function setNavigationLinks(strGridNo)
			{
					var iCurPageIndex=1;
				    iCurPageIndex=document.getElementById('hdnCurPageIndex'+strGridNo).value*1;
				   
					
				   if((iCurPageIndex*1) == (1*1))
				    {
				      
				       if((iCurPageIndex*1) == (document.getElementById('hdnLastPageIndex'+strGridNo).value*1))
				       {
				       			          
				          document.getElementById('ButtonFirst'+strGridNo).disabled=true;
					      document.getElementById('ButtonPrev'+strGridNo).disabled=true;
					      document.getElementById('ButtonNext'+strGridNo).disabled=true;
					      document.getElementById('ButtonLast'+strGridNo).disabled=true;
					      
					      document.getElementById('ButtonFirst'+strGridNo).src='images/icon_firstpage_disabled.gif';
					      document.getElementById('ButtonPrev'+strGridNo).src='images/icon_prepage_disabled.gif';
					      document.getElementById('ButtonNext'+strGridNo).src='images/icon_nextpage_disabled.gif';
					      document.getElementById('ButtonLast'+strGridNo).src='images/icon_lastpage_disabled.gif';
					      
					      
					      document.getElementById('ButtonFirst'+strGridNo).style.cursor="default";
					      document.getElementById('ButtonPrev'+strGridNo).style.cursor="default";
					      document.getElementById('ButtonNext'+strGridNo).style.cursor="default";
					      document.getElementById('ButtonLast'+strGridNo).style.cursor="default";
					      
				       }
				       else
				       {
				          document.getElementById('ButtonFirst'+strGridNo).disabled=true;
				          document.getElementById('ButtonPrev'+strGridNo).disabled=true;
				          document.getElementById('ButtonNext'+strGridNo).disabled=false;
				          document.getElementById('ButtonLast'+strGridNo).disabled=false;
				          
				          document.getElementById('ButtonFirst'+strGridNo).style.cursor="default";
					      document.getElementById('ButtonPrev'+strGridNo).style.cursor="default";
					      document.getElementById('ButtonNext'+strGridNo).style.cursor="pointer";
					      document.getElementById('ButtonLast'+strGridNo).style.cursor="pointer";
					      
					      document.getElementById('ButtonFirst'+strGridNo).src='images/icon_firstpage_disabled.gif';
					      document.getElementById('ButtonPrev'+strGridNo).src='images/icon_prepage_disabled.gif';
					      document.getElementById('ButtonNext'+strGridNo).src='images/icon_nextpage.gif';
					      document.getElementById('ButtonLast'+strGridNo).src='images/icon_lastpage.gif';
				      }
				      
				      
				    }
					else if((iCurPageIndex*1) == (document.getElementById('hdnLastPageIndex'+strGridNo).value*1))
					{
					    
					      document.getElementById('ButtonFirst'+strGridNo).disabled=false;
					      document.getElementById('ButtonPrev'+strGridNo).disabled=false;
					      document.getElementById('ButtonNext'+strGridNo).disabled=true;
					      document.getElementById('ButtonLast'+strGridNo).disabled=true;
					      
					      document.getElementById('ButtonFirst'+strGridNo).style.cursor="pointer";
					      document.getElementById('ButtonPrev'+strGridNo).style.cursor="pointer";
					      document.getElementById('ButtonNext'+strGridNo).style.cursor="default";
					      document.getElementById('ButtonLast'+strGridNo).style.cursor="default";
					      
					      document.getElementById('ButtonFirst'+strGridNo).src='images/icon_firstpage.gif';
					      document.getElementById('ButtonPrev'+strGridNo).src='images/icon_prepage.gif';
					      document.getElementById('ButtonNext'+strGridNo).src='images/icon_nextpage_disabled.gif';
					      document.getElementById('ButtonLast'+strGridNo).src='images/icon_lastpage_disabled.gif';
					      
					      
					    
					}
					else if ((iCurPageIndex*1) > (1*1) && (iCurPageIndex*1) < (document.getElementById('hdnLastPageIndex'+strGridNo).value*1))
					{
					      document.getElementById('ButtonFirst'+strGridNo).disabled=false;
					      document.getElementById('ButtonPrev'+strGridNo).disabled=false;
					      document.getElementById('ButtonNext'+strGridNo).disabled=false;
					      document.getElementById('ButtonLast'+strGridNo).disabled=false;
    					  
				          document.getElementById('ButtonFirst'+strGridNo).style.cursor="pointer";
				          document.getElementById('ButtonPrev'+strGridNo).style.cursor="pointer";
				          document.getElementById('ButtonNext'+strGridNo).style.cursor="pointer";
				          document.getElementById('ButtonLast'+strGridNo).style.cursor="pointer";
				          
				          document.getElementById('ButtonFirst'+strGridNo).src='images/icon_firstpage.gif';
					      document.getElementById('ButtonPrev'+strGridNo).src='images/icon_prepage.gif';
					      document.getElementById('ButtonNext'+strGridNo).src='images/icon_nextpage.gif';
					      document.getElementById('ButtonLast'+strGridNo).src='images/icon_lastpage.gif';
					}
			}
			
			
			function goFirst(strGridNo)
			{
			    document.getElementById('hdnCurPageIndex'+strGridNo).value=1*1;
			}
				
			function goPrev(strGridNo)
			{
 			    var iCurPageIndex;
                iCurPageIndex= document.getElementById('hdnCurPageIndex'+strGridNo).value*1;			
				iCurPageIndex=(iCurPageIndex*1)-(1*1);
				document.getElementById('hdnCurPageIndex'+strGridNo).value=iCurPageIndex*1;
			
			}
			  
			function goNext(strGridNo)
			{
	    	    var iCurPageIndex;
                iCurPageIndex= document.getElementById('hdnCurPageIndex'+strGridNo).value*1;			
		        iCurPageIndex=(iCurPageIndex*1)+(1*1);
		        document.getElementById('hdnCurPageIndex'+strGridNo).value=iCurPageIndex*1;

			}	
			
			function goLast(strGridNo)
			{
			      document.getElementById('hdnCurPageIndex'+strGridNo).value=(document.getElementById('hdnLastPageIndex'+strGridNo).value*1);
			}



			/*===================== AJAX GET XML HTTP OBJECT ======================= */

			var XMLHttpRequestHandler = {
			    ExecuteXMLHttpRequest: function(method, uri, callback, postData, formular) {
			        var xmlHttp = XMLHttpRequestHandler.GetXmlHttpObject();
			        if (xmlHttp == null) {
			            alert("Your browser does not support AJAX!");
			            return;
			        }
			        xmlHttp.open(method, uri, true);
			        if (formular)
			            xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
			        XMLHttpRequestHandler.ManageReadyState(xmlHttp, callback);
			        xmlHttp.send(postData || null);
			        return xmlHttp;
			    },
			    ManageReadyState: function(xmlHttp, callback) {
			        xmlHttp.onreadystatechange = function() {
			            if (xmlHttp && xmlHttp.readyState == 4 && xmlHttp.status == 200) {
			                if (callback) {
			                    callback(xmlHttp);
			                }
			            }
			        };
			    },
			    GetXmlHttpObject: function() {
			        var xmlHttp;
			        try {
			            xmlHttp = new XMLHttpRequest;
			            XMLHttpRequestHandler.GetXmlHttpObject = function() {
			                return new XMLHttpRequest;
			            }
			        } catch (e) {
			            var msxml = [
				"MSXML2.XMLHTTP.5.0",
				"MSXML2.XMLHTTP.4.0",
				"MSXML2.XMLHTTP.3.0",
				"MSXML2.XMLHTTP",
				"Microsoft.XMLHTTP"
			];
			            for (var i = 0, len = msxml.length; i < len; i++) {
			                try {
			                    xmlHttp = new ActiveXObject(msxml[i]);
			                    XMLHttpRequestHandler.GetXmlHttpObject = function() {
			                        return new ActiveXObject(msxml[i]);
			                    }
			                    break;
			                } catch (e) { }
			            }
			        }
			        return xmlHttp;
			    }
			}
			
/* ============================== USAGE OF AJAX FUNCTION =============================================
    XMLHttpRequestHandler.ExecuteXMLHttpRequest("GET", url, function(strXMLHttpResponse) { NameofTheFunction(strXMLHttpResponse) });
============================== USAGE OF AJAX FUNCTION =============================================*/
			
			
/* ======================================== ENCODE/DECODE ROUTINE ======================================== */

function StrEncode(strPlainText) {
	var unencoded = strPlainText;
	return escape(unencoded);
}
function StrDecode(strEncodedText) {
	var encoded = strEncodedText;
	return unescape(encoded.replace(/\+/g,  " "));
}


/* ========================== FUNCTION TO LIMIT TEXTAREA LENGTH ================================ */
/* ============== USE THE BELOW FUNCTION ON KEYUP EVENT OF TEXTAREA ==================== */

function canAddCharacter(objtextarea, maxChars)
{
    var text = objtextarea.value;
    var iLen = ctlTextArea.length;
    if(iLen > maxChars)
    {
            text = text.substring(0,maxChars);
            objtextarea.value =text;
            return false;
    }
    //document.myform.limit.value = count-len;
}

/* ============== USE THE BELOW FUNCTION WHILE VALIDATING CONTROLS  ==================== */
function TValidateTextAreaLength(objTextArea, iLength, strFieldName) // function returns boolean.
{
        if(objTextArea.value.length > (iLength-1))
        {
            alert(strFieldName + ' exceeds maximum length.\nMaximum allowed length is '+ iLength + ' characters.')
            return false;   
        }
    return true;
}






