/************************************************************************
Validation funcs written by arv@10aug2k3
************************************************************************

--------GUIDELINES FOR USAGE OF FUNCTIONS ----------------------
set the id of form elements as directed here and 
call the CheckEntireForm(objForm) in the form submit evet
i.e. <form onSubmit = "return CheckEntireForm(MyFormName)" ... >

RQ-Y/N REQUIRED(SHOULD NOT BE BLANK)
NM-Y/N NAME
NU-Y/N NUMERIC
FN-Y/N FLOAT NUMERIC
NUR-Y/N NUMERIC RANGE
NURMX-n MAX NUMERIC RANGE
NURMN-n MIN NUMERIC RANGE
NRC-Y/N CHECK NUMEIC RANGE
PH-Y/N PHONE
EM-Y/N EMAIL
CMX-n CONTROL HAS n AS MAX RANGE
CMN-n CONTROL HAS n AS MIN RANGE
CRC - Y/N CHECK CONTROL LENGTH RANGE
LBC-Y/N- CONTROL IS A LIST BOX CONTROL AND CHECK THAT A SELECTON IS MADE
MSS - XYZ... MESSAGE TO THROW IF VALIDATION FAILED
SPA - Y/N space is not allowed
FUP - Y/N if a file upload comp
TFP - P/C p=picture ; c = cv

A SAMPLE ID IS SHOWN HERE
RQ-Y|NU-Y|CMN-3|CMX-8|MSS-EMPLYOEE_INCOME_LEVEL
this field is a required field, it can only accept
numeric data and can contain only 3 to 8 char length number
it is EMPLYOEE INCOME LEVEL (notice underscore as space is not allowwd)
***********************************************************************************
*/


//Global constants for message throwing
var MESS_BLANK = new String("Please specify a value for the field: ")
var MESS_RANGE = new String("Please specify a value in the valid range for the field: ")
var MESS_NUMERIC = new String("Please specify a valid numeric value for the field: ")
var MESS_NAME = new String("Please specify a valid name for the field: ")
var MESS_NUMERIC_RANGE = new String("Please specify a numeric value in the given range for the field: ")
var MESS_PHONE = new String("Please specify a valid phone number in the format xxx-xxx-xxxxxxxx for the field: ")
var MESS_EMAIL = new String("The email address you have entered seems to be invalid. Please enter a valid email address. If you believe you got this message in an error, please call us and someone will assist you personally : ")
var MESS_CHAR_DATA = new String("Please specify a value with the specified min/max length for the field: ")
var MESS_LIST = new String("Please select an option from the list : ")
var MESS_START =new String("PLEASE FILL THIS FORM AS SPECIFIED HERE :\n--------------------------------------------------------------------")
var MESS_FUP=new String("The file you have selected for upload is not a valid file for the field: ")
var MESS_STRICTNUMERIC = new String("Please enter a whole number for the field : ")
//var MESS_PASSWORD = new String("Please enter a valid value (Alphabets,numbers, _ are allowed) for the field :")
var MESS_PASSWORD = new String("Space,single and double quotes characters are not allowed for the field :")
//x



//Function to search  through an entire select list and highlight a specific option value based on passed arguement ObjList = Name of select list
function SelectListOption(ObjList,StrOptionValue)
{
	for(i=0;i<ObjList.length;i++)
	{
		if (ObjList.options[i].text==StrOptionValue)
		{
			ObjList.options[i].selected="1";
			return true;
		}
	}
	return false;		
}

//Function to check / uncheck checkbox form control
function SelectCheckBox(ObjCheckBox,boolCheck)
{
	if(boolCheck){
		ObjCheckBox.checked=true;
		return true;
		}
	else
	{
		ObjCheckBox.checked=false;
		return false;
	}
}

//get ascii char code of arg
function GetAsciiCode(argChar)
{
	var s = new String(argChar);
	return parseInt(s.charCodeAt(0));
}

//check if arg is pure numeric and a +ive whole number 
function IsNumeric(sText)
{
   var ValidChars = "0123456789.";
   var IsNumber=true;
   var Char;

	if(isNaN(sText) == true)
		return false;
	
   for (i = 0; i < sText.length && IsNumber == true; i++) 
      { 
      Char = sText.charAt(i); 
      if (ValidChars.indexOf(Char) == -1) 
         {
         IsNumber = false;
         }
      }
   return IsNumber;
   
}
//check valid password
//------Space,single and double quotes will not allowed -------------------------   
function IsPassword(sText)
{ 
   if(sText.match(/\s|\"|\'/g) == null)
		return true;
	else
		return false
}
//check if arg is pure numeric and a +ive whole number 
function IsStrictNumeric(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;
   
}
//func for char checking 
function IsValid(argValue,argValidChars)
{
   var ValidChars = argValidChars;
   var ret=true;
   var Char;
 
   for (i = 0; i < argValue.length && ret == true; i++) 
      { 
      Char = argValue.charAt(i); 
      if (ValidChars.indexOf(Char) == -1) 
         {
         ret = false;
         }
      }
   return ret;
}
//check if arg is  numeric and a +ive decimal number
function IsFloatOrNumeric(argStr)
{
	var s = new String(argStr);
	var cnt=0;
	len = s.length;
	if (IsBlank(argStr)) { return false;}
	for(i=0;i<len;i++)
	{
		intCh = GetAsciiCode(s.charAt(i));
		
		if (intCh==46) //there can't be more than one decimal
		{
			cnt++;
			if(cnt>1)
				return false;
		}
		
		if (intCh==46&&(i==0||i==len-1))//first char and last char cannot be decimal
		{
			 return false;
		}
		
		if(!((intCh>=48&&intCh<=57)||(intCh==46)))
		{
			return false;
		}
	}
	return true;
}

//check if a string contains whitespaces or nothing ...
function IsBlank(argStr)
{
	var s = new String(argStr);
	var cnt=0;
	len = s.length;
	
	for(i=0;i<len;i++)
	{
		intCh = GetAsciiCode(s.charAt(i));
		if(intCh==32)
		{
			cnt++;
		}
	}
	if ((cnt==len)||(cnt==0&&len==0))
	{
		return true;
	}
	return false;
}

//check if a string contains special characters
function IsSpecialCharacter(argStr)
{
	var s = new String(argStr);
	var cnt=0;
	len = s.length;
	if (IsBlank(argStr)) { return false;}
	
	for(i=0;i<len;i++)
	{
		intCh = GetAsciiCode(s.charAt(i));
		if ((intCh>=0&&intCh<=31) || (intCh>=127&&intCh<=255))
		{
			return true;
		}
	}
	return false;
}

//check if a string abides to a min , max range rule for an input field
function IsLengthBetweenRange(argStr,MIN,MAX)
{
	var s = new String(argStr)
	len = s.length;
	if (len<MIN||len>MAX)
	{
		return false;
	}
	return true;
}

//check valid international phone number xxx-xxx-xxxxxxxx
function IsValidInternationalPhoneFaxNumber(argStr)
{
	var s = new String(argStr);
	var cnt=0;
	len = s.length;
	
	if (IsThereAnyWhiteSpace(argStr)==true)
	{
		return false;
	}
		
	if (!(s.indexOf("-")>=0))
	{
		return false;
	}
		
	arr = s.split("-")
	
	if (arr.length!=3)
	{
		return false;
	}
	
	var countrycode=new String(arr[0]);
	var statecode=new String(arr[1]);
	var localcode=new String(arr[2]);
	
	if (IsNumeric(countrycode)==false||IsNumeric(statecode)==false||IsNumeric(localcode)==false)
	{
	return false;
	}
	
	if (IsLengthBetweenRange(countrycode,2,3)==false||IsLengthBetweenRange(statecode,2,3)==false||IsLengthBetweenRange(localcode,4,8)==false)
	{
		return false;
	}
	
	return true;
}

//check if arg contains no white spaces
function IsThereAnyWhiteSpace(argStr)
{
	var s = new String(argStr);
	var cnt=0;
	len = s.length;
	if (IsBlank(argStr))
	{
	return false;
	}
	
	if(s.indexOf(" ")>=0)
	{
		return true;
	}
	return false;
}
//check if number is between given range
function CheckNumericRange(argStr,MIN,MAX)
{
	if (IsNumeric(argStr)==true)
	{
		var n = new Number(argStr);
		
		if (n<MIN||n>MAX)
		{
			return false;
		}
		else
		{
			return true;
		}
	}
	else
	{
		return false;
	}
}
function IsValidName(argStr)
{
	var s = new String(argStr);
	var cnt=0;
	len = s.length;
	
	for(i=0;i<len;i++)
	{
		intCh = GetAsciiCode(s.charAt(i));
		if(!((intCh>=48&&intCh<=57) ||  (intCh==32)||(intCh>=65&&intCh<=90)||(intCh>=97&&intCh<=122)||(intCh==46)||(intCh==39)))
		{
			return false;
		}	
	}
	return true;
}
function IsValidEmail(argStr)
{
	var s = new String(argStr);
	s = trim(s);
	if(IsBlank(s)==true) {return true;}
	/*if(IsThereAnyWhiteSpace(s)==true) { return false;}
	if(IsValid(s,"qwertyuiopasdfghjklzxcvbnm0123456789-@_.QWERTYUIOPASDFGHJKLZXCVBNM")==false) return false;
	if(s.indexOf('@')<1) { return false;}
	
	var dotCount;
	var id = new String();
	var dom = new String();
	
	arr=s.split('@')
	
	id  = arr[0];
	dom = arr[1];
		
	if (id.length<1) { return false;}
	if (dom.length<4) { return false;}
	if (dom.indexOf('.')<1) { return false;}
	return true;*/
	
	//--------First break string by ; then check each value	----	
	var i=0;
	var arr = s.split(";");
	var errFlag = false;	
	for(i=0;i<arr.length;i++)
	{		
		arr[i] = trim(arr[i]);		
		if(IsBlank(arr[i]) !=true)
		{
			if(CheckEmail(arr[i]) == false)				
				return false;			
			else			
				errFlag = true;			
		}		
	}
	return errFlag;
	//----------------------------------------------------------
}

function CheckEmail(val) 
{
	if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(val))	
		return (true);
	else
		return (false);
}

function IsListBoxSelected(objListBox)
{
	if(objListBox.options.length == 0)
		return false;
	if (objListBox.options[objListBox.selectedIndex].value==0)
	{
		return false;
	}
	return true;
}
//resolve extra data passed with a control to the form and get name - value pairs 
function GetCommand(CONTROL_DATA,MKEY)
{	
	arr = CONTROL_DATA.split("|")
	for(i=0;i<arr.length;i++)
	{
		arr2=arr[i].split("-");
		if (arr2[0]==MKEY)
		{
			return arr2[1];
		}
	}
}
/*fn :: restrict the user to select only gif,jpe,png files for photo uploading */
function IsValidFile(argStr,type)
{
	var fileExt=new Array();
	if(type.toUpperCase()=='P')//picture
	{
		fileExt[0]="GIF";
		fileExt[1]="JPEG";
		fileExt[2]="PNG";
		fileExt[3]="JPG";
		fileExt[4]="BMP";
	}
	if(type.toUpperCase()=='C')//cv
	{
		fileExt[0]="TXT";
		fileExt[1]="DOC";
		fileExt[2]="XLS";
		fileExt[3]="ZIP";
		fileExt[4]="HTM";
		fileExt[5]="HTML";
	}

	dt=argStr;
	if(dt.length>0)
	{
		dotpos = dt.lastIndexOf(".");
		ext = dt.substr(dotpos+1);
		for(i=0;i<fileExt.length;i++)
		{
			if (ext.toUpperCase()==fileExt[i])
			{
				return true;				
			}
		}
	return false;
	}
	else
	{
		//if no file is selected then return true as there is nothin to check
		return true;
	}
	return false;
}
//***********************************************************************************************
//This function takes the form obj as arg and processes all it's elements by the ids passed to it
//***********************************************************************************************

function CheckEntireForm(objForm)
{
	var intFormElements=new Number();		//number of form elements
	var obj;								//pointer to particular object of form
	var i;									//loop var
	var COMMAND_STRING = new String();		//command string of form control
	var FINAL_MESSAGE = new String();		//message to throw if validation fails
	
	
	var RQ;									//required field
	var NM;									//name field
	var NU;									//numeric fiels
	var FN;									//float numeric
	var NUR;								//numeric range
	var NURMX;								//if nur then max numeric range
	var NURMN;								//if nur then min numeric range
	var PH;									//phone field
	var EM;									//email field
	
	var CMX;								//field max length
	var CMN;								//field min length
	var LBC;								//control is a list box select
	var MSS_CONTROL;						//mss associated with a control(message)
	var SPA;								//spaces not allowed
	
	var NRC;
	var CRC;
	var FUP;
	var TFP;
	var STN;								//STRICT NUMERIC NO DECIMALS
	var PWD;								//password field
	
	var YES="Y";							//constants for the ease of distinguishing
	var NO="N";								//constants for the ease of distinguishing
	
	var CONTROL_VALUE;
	var m;
	
	//get number of form elements
	intFormElements= objForm.elements.length;
	
	//seperate messages for all elements
	var MESSAGE_ARRAY = new Array(intFormElements)
	
	//Add new field for focus by ashok kumar
	var focusField = "";
	
	//loop through all elements
	for(i=0;i<intFormElements;i++)
	{
		obj = objForm.elements[i]
		
		COMMAND_STRING = obj.lang;
		//alert(COMMAND_STRING);
		COMMAND_STRING = COMMAND_STRING.toUpperCase();
		
		//get custom validation
	
		RQ			= GetCommand(COMMAND_STRING,"RQ");
		NM			= GetCommand(COMMAND_STRING,"NM");
		NU			= GetCommand(COMMAND_STRING,"NU");
		FN			= GetCommand(COMMAND_STRING,"FN");
		NUR			= GetCommand(COMMAND_STRING,"NUR");
		NURMX		= GetCommand(COMMAND_STRING,"NURMX");
		NURMN		= GetCommand(COMMAND_STRING,"NURMN");
		PH			= GetCommand(COMMAND_STRING,"PH");
		EM			= GetCommand(COMMAND_STRING,"EM");
		CMX			= GetCommand(COMMAND_STRING,"CMX");
		CMN			= GetCommand(COMMAND_STRING,"CMN");
		LBC			= GetCommand(COMMAND_STRING,"LBC");
		MSS_CONTROL = GetCommand(COMMAND_STRING,"MSS");
		SPA			= GetCommand(COMMAND_STRING,"SPA");
		NRC			= GetCommand(COMMAND_STRING,"NRC");
		CRC			= GetCommand(COMMAND_STRING,"CRC");
		FUP			= GetCommand(COMMAND_STRING,"FUP")
		TFP			= GetCommand(COMMAND_STRING,"TFP")
		STN			= GetCommand(COMMAND_STRING,"STN")
		PWD			= GetCommand(COMMAND_STRING,"PWD")
		
		CONTROL_VALUE = obj.value
		MESSAGE_ARRAY[i]=""
		
		//check required
		if (RQ==YES)
		{
			if (IsBlank(CONTROL_VALUE)==true)
			{
				MESSAGE_ARRAY[i] = MESS_BLANK+MSS_CONTROL
			}
		}
		//check name
		if (NM==YES)
		{
			if (IsValidName(CONTROL_VALUE)==false&&MESSAGE_ARRAY[i].length==0)
			{
				MESSAGE_ARRAY[i] = MESS_NAME+MSS_CONTROL;
			}
		}
		//check strict numeric
		if (STN==YES)
		{
			if (IsStrictNumeric(CONTROL_VALUE)==false&&MESSAGE_ARRAY[i].length==0)
			{
				MESSAGE_ARRAY[i] = MESS_STRICTNUMERIC+MSS_CONTROL;
			}
		}
		//check numeric
		if (NU==YES)
		{
			if (IsNumeric(CONTROL_VALUE)==false&&MESSAGE_ARRAY[i].length==0)
			{
				MESSAGE_ARRAY[i] = MESS_NUMERIC+MSS_CONTROL;
			}
		}
		//check float numeric
		if (FN==YES)
		{
			if (IsFloatOrNumeric(CONTROL_VALUE)==false&&MESSAGE_ARRAY[i].length==0)
			{
				MESSAGE_ARRAY[i] = MESS_NUMERIC+MSS_CONTROL;
			}
		}
		//check password
		if (PWD==YES)
		{
			if (IsPassword(CONTROL_VALUE)==false&&MESSAGE_ARRAY[i].length==0)
			{
				MESSAGE_ARRAY[i] = MESS_PASSWORD+MSS_CONTROL;
			}
		}
		//check numeric with range
		if (NUR==YES)
		{
			if(STN==YES)
			{
				if (IsStrictNumeric(CONTROL_VALUE)==false&&MESSAGE_ARRAY[i].length==0)
				{
					MESSAGE_ARRAY[i] = MESS_NUMERIC+MSS_CONTROL;
				}		
			}
			else
			{
				if (IsNumeric(CONTROL_VALUE)==false&&MESSAGE_ARRAY[i].length==0)
				{
					MESSAGE_ARRAY[i] = MESS_NUMERIC+MSS_CONTROL;
				}
			}
		}
		
		if (NRC==YES&&MESSAGE_ARRAY[i].length==0)
		{
			if (CheckNumericRange(CONTROL_VALUE,NURMN,NURMX)==false&&MESSAGE_ARRAY[i].length==0)
			{
				MESSAGE_ARRAY[i] = MESS_NUMERIC_RANGE+MSS_CONTROL+"[Range: "+NURMN+" to "+NURMX+ " ]";
			}
		}
		
		//check phone number
		if (PH==YES&&MESSAGE_ARRAY[i].length==0)
		{
			if (IsValidInternationalPhoneFaxNumber(CONTROL_VALUE)==false&&MESSAGE_ARRAY[i].length==0)
			{
				MESSAGE_ARRAY[i] = MESS_PHONE+MSS_CONTROL;
			}
		}
		
		//check email
		if (EM==YES&&MESSAGE_ARRAY[i].length==0)
		{
			if (IsValidEmail(CONTROL_VALUE)==false&&MESSAGE_ARRAY[i].length==0)
			{
				MESSAGE_ARRAY[i] = MESS_EMAIL+MSS_CONTROL;
			}
		}
		//check length for character data
		if (CRC==YES&&MESSAGE_ARRAY[i].length==0)
		{
			if (IsLengthBetweenRange(CONTROL_VALUE,parseInt(CMN),parseInt(CMX))==false&&MESSAGE_ARRAY[i].length==0)
			{
				MESSAGE_ARRAY[i] = MESS_CHAR_DATA+MSS_CONTROL+ " Range ("+CMN + " to " + CMX+ " )";
			}
		}
		//check if value  from a list is selectd
		if (LBC==YES&&MESSAGE_ARRAY[i].length==0)
		{
			if(IsListBoxSelected(obj)==false&&MESSAGE_ARRAY[i].length==0)
			{
				MESSAGE_ARRAY[i] = MESS_LIST+MSS_CONTROL;
			}
		}
		//check file upload is havin a valid file upload
		
		if (FUP==YES&&MESSAGE_ARRAY[i].length==0)
		{
			if (IsValidFile(CONTROL_VALUE,TFP)==false)
			{
				if (TFP=='P') { var e = new String("GIF,JPG,PNG,BMP")}
				if (TFP=='C') { var e = new String("TXT,DOC,HTM,CSV,ZIP,XLS")}
				MESSAGE_ARRAY[i] = MESS_FUP+MSS_CONTROL+" Valid file formats are : " + e;
			}
		}
		
	}
	
	//end checking form controls
	m="";
	for(i=0;i<intFormElements;i++)
	{
		m+=MESSAGE_ARRAY[i];
	}
	
	if(m!="")
	{
		FINAL_MESSAGE+=MESS_START + "\n\n"
		
		for(i=0;i<intFormElements;i++)
		{
			if (MESSAGE_ARRAY[i]!="")
			{
				//FINAL_MESSAGE+="("+parseInt(i+1)+") "+MESSAGE_ARRAY[i]+"\n";
				FINAL_MESSAGE+='» '+MESSAGE_ARRAY[i]+"\n";
				
				//Focus handling
				if(focusField == "")
				{					
					focusField = objForm.elements[i];
				}	
			}
		}
		alert(FINAL_MESSAGE);
		try
		{
			focusField.focus();
		}
		catch(ex)
		{
		}		
		return false;
	}
	else
	{
		return true;
	}
}
// Removes leading whitespaces
function LTrim( value ) {	
	var re = /\s*((\S+\s*)*)/;
	return value.replace(re, "$1");
	
}

// Removes ending whitespaces
function RTrim( value ) {	
	var re = /((\s*\S+)*)\s*/;
	return value.replace(re, "$1");
	
}

// Removes leading and ending whitespaces
function trim( value ) {	
	return LTrim(RTrim(value));
	
}

//function to trim a string
function Trimmer(controlName) { 
	pVal = controlName.value;
    TRs=0; 
    for (i=0; i<pVal.length; i++) 
	{ 
        if (pVal.substr(i,1)==" ") 
		{
			TRs++;
		} 
		else 
			{break;} 
    } 

    TRe=pVal.length-1; 
    for (i=TRe; i>TRs-1;i--)
	{ 
        if (pVal.substr(i,1)==" ") 
		{
			TRe--;
		}
		else 
			{break;} 
    } 

    controlName.value=pVal.substr(TRs, TRe-TRs+1); 
} 
//end trim function

function isAlphaNum(str)
{
	if(str != "")
	{
		var regex=/^[0-9a-z]+$/i; 
		return regex.test(str);	
	}	
}
//--------Take into into dd-MM-yyyy format and give a date object.
function cDate(val)
{
	var tmpDate = val.split('-');
	var rtnDate = new Date(tmpDate[2],tmpDate[1],tmpDate[0]);
	return rtnDate;
}


//Select/Unselect all checkboxes array
function SelectAll(cntrl,flag) 
{				
	if(cntrl.length == undefined)	
		cntrl.checked=flag;	
	else
	{
		for(i=0;i<cntrl.length;i++)
		{
			cntrl[i].checked = flag;
		}
	}	
}

//Select-Unselect all checkboxes In Datagrid
function SelectDgAll(dgName,chkId,start,length,flag) 
{		
	var i=0,Id,j=0;
	for(i=0; i<length; i++)
	{
		j = i + parseInt(start);
		Id = document.getElementById(dgName + "__ctl" + j + "_" + chkId);
		Id.checked=flag;	
	}			
}
//Atleast one check box should be checked in Datagrid
function checkDgAll(dgName,chkId,start,length) 
{			
	var flag = false;	
	var i=0,Id,j=0;
	for(i=0; i<length; i++)
	{
		j = i + parseInt(start);		
		Id = document.getElementById(dgName + "__ctl" + j + "_" + chkId);
		if(Id.checked == true)
		{
			flag = true;
			break;
		}
	}		
	return flag;		
}

//Atleast one check box should be checked in checkbox Array
function checkAll(cntrl,flag) 
{			
	var error=0;	
	if(cntrl.length == undefined)
	{
		if(cntrl.checked==true)	
			error=1;
	}
	else
	{
		for(i=0;i<cntrl.length;i++)
		{
			if(cntrl[i].checked==true)
			{
				error=1;
				break;
			}
		}
	}
	if(error==0)
	{
		alert("Please select atleast one record.");
		return false
	}	
	else
	{
		if(flag == 'D')
			return confirm ('Do you really want to delete the selected coupons ?')
		else
			return true;
	}	
}

//Confirm deletion
function confirmDel()
{
	if(confirm("Do you really want to delete the record ?"))
		return true;
	else
		return false;	
}

function showDelete(pageType,infId)
{
	if(confirmDel())
	{
		var path = "confirmDelete.aspx?cmd="+pageType+ "&pk="+infId.toString() ;
		window.open(path,'winopen','width=600,height=300,menubar=no,scrollbars=yes,toolbar=no,location=no,directories=no,resizable=1,top=50,left=80');
	}	
}

//------------- Menu ordering -----------------------------------------------------
function move(dirUp)
{	
	var obj = document.all.lstMenu;
	var idx = obj.selectedIndex
	var nidx 
	if (idx!== -1)
	{
		if (dirUp) //move up 
		{
			if (idx>0)
			{
				nidx = idx-1;
			}
			else
			{
				nidx = idx;
			}
		}
		else   //move down 
		{
			if (idx<obj.length-1)
			{
				nidx = idx+1;
			}
			else
			{
				nidx = idx;
			}
		}
		
		if (nidx !== idx)
		{
			var oldVal ,oldText;
			oldVal  = obj[idx].value;
			oldText  = obj[idx].text;
			obj[idx].value =  obj[nidx].value;
			obj[idx].text = obj[nidx].text;
			obj[nidx].value =  oldVal;
			obj[nidx].text = oldText;
			obj.selectedIndex=nidx;	
		}
	}	
	else
		alert("Please selecr an item from the list.");
}

//<!-- ==========Show only first 200 chars from tour details ===================================-->
function GetTourDetails(divId,totalChars)
{
	var totChars = 200;
	if(totalChars)
		totChars = totalChars;
		
	if(document.all)
		var mainStr = document.getElementById(divId).innerText;
	else
		var mainStr = document.getElementById(divId).textContent;
	
	var txt= "";
	var val = document.getElementById(divId);
	if(mainStr != "")
	{
		var startIndex = totChars;
		var pos = mainStr.indexOf(" ",totChars)
		if(pos > startIndex)
			startIndex = pos;
			
		txt = mainStr.substring(0,startIndex);
		if(txt.length < mainStr.length)
				txt += ' ...'
	}		
	val.innerHTML = txt;				
}


// ----------- Validate time values ----------------------------------------------
function ValidateTime (ctlTime) 
{	
	var str_time = ctlTime.value;
	var rtnTime = "";
	var RE_NUM = /^\-?\d+$/;
	var arr_time = String(str_time ? str_time : '').split(':');
	
	if (RE_NUM.exec(arr_time[0]))
		if (arr_time[0] < 24) 
			rtnTime = arr_time[0];
		else 
			return ("Invalid hours value: '" + arr_time[0] + "'.\nAllowed range is 00-23.");
	else
		 return ("Invalid hours value: '" + arr_time[0] + "'.\nAllowed values are unsigned integers.");
	
	if (!arr_time[1]) 
		rtnTime += ":0";
	else if (RE_NUM.exec(arr_time[1]))
		if (arr_time[1] < 60) 
			rtnTime += ":" + arr_time[1]			
		else 
			return ("Invalid minutes value: '" + arr_time[1] + "'.\nAllowed range is 00-59.");
	else 
		return ("Invalid minutes value: '" + arr_time[1] + "'.\nAllowed values are unsigned integers.");

	if (!arr_time[2]);		
	else if (RE_NUM.exec(arr_time[2]))
		if (arr_time[2] < 60) 
			rtnTime += ":" + arr_time[2]			
		else 
			return ("Invalid seconds value: '" + arr_time[2] + "'.\nAllowed range is 00-59.");
	else
		 return ("Invalid seconds value: '" + arr_time[2] + "'.\nAllowed values are unsigned integers.");

	ctlTime.value = rtnTime;
	return "";
}

//--------------------------------------------------------------------------------------

function checkfext(frm)
{						 
	Trimmer(frm.file1);
	if(frm.file1.value != '')
	{					
		var dotpos = frm.file1.value.lastIndexOf(".");
		var ext = frm.file1.value.substr(dotpos+1);
		if (ext.toUpperCase()== 'PDF' || ext.toUpperCase()== 'DOC' || ext.toUpperCase()== 'GIF' || ext.toUpperCase()== 'JPG' || ext.toUpperCase()== 'JPEG')
		{
			return true;
		}
		else
		{
			alert("Upload File type is PDF,DOC,GIF & JPEG");
			frm.file1.focus();
			return false;
		}
	}
}

//========== Highlight current row color for given id table=========================
//blid = Table Id
function tableRuler(tblId) 
{				
	if (document.getElementById && document.createTextNode)
	{				
		var tables=document.getElementById(tblId);
		if(tables)
		{
			var trs=tables.getElementsByTagName('tr');												
			for(var j=0;j<trs.length;j++)
			{
				if(trs[j].parentNode.nodeName=='TBODY' && trs[j].className.indexOf("dgh") == -1) 
				{
					trs[j].onmouseover=function(){this.oldClass=this.className;this.style.backgroundColor='green';return false}
					trs[j].onmouseout=function(){this.className=this.oldClass;this.style.backgroundColor='';return false}
				}
			}
		}										
	}
}

//-------- Calucalte two date difference in years -------------
function CalculateAge(fromDate,toDate)
{
	var age = toDate.getFullYear() - fromDate.getFullYear();
	if (fromDate.getMonth() > toDate.getMonth() || (fromDate.getMonth() == toDate.getMonth() && fromDate.getDate() > toDate.getDate() ))
            age -= 1
        
	return age;        
}
//-------------------------------------------------------------

//=================================================================================
// Show user details in intranet --------------------------------------------- //
function ShowUserDetails(val,userType)
{									
	var path="userDetails.aspx?id="+val+"&userType=" + userType;					
	showWindow(path,600,500);				
}
//---------------------------------------------------------------------------- //
//<!----================================================================================================-->
function replaceAll (str, find, replace)
{ 	
	if (str.length == 0)
		return str;
	var idx = str.indexOf(find);
	while (idx >= 0)        
	{  
		str = str.replace(find,replace)
		idx = str.indexOf(find);
	}
	return str;
}

//============= Ajax Functions ==================================================
AjaxInit=function() 
{ 
	if (window.XMLHttpRequest) { // Non-IE browsers 
		_req = new XMLHttpRequest(); 
	} 
	else if (window.ActiveXObject){ // IE 
		_req = new ActiveXObject("Microsoft.XMLHTTP"); 
	} 
} 

processStateChange=function()
{ 	
	if (_req.readyState == 4)
	{
		if (_req.status == 200) 
		{ 
			if(_req.responseText=="") 
				return false; 
			else
			{                
				eval(_req.responseText);             
			} 
		} 
	} 
} 

clearSelection=function(lstId,type)
{ 
	var _ddl = lstId; 
	while (_ddl.childNodes.length >0)
	{ 
		_ddl.removeChild(_ddl.childNodes[0]); 
	} 
	if(!type)
	{
		var o = document.createElement("Option"); 
		o.innerHTML = "Select"; 
		o.value =""; 
		_ddl.appendChild(o);
	}	
} 
//===============================================================================

//========= Show Customers Area ========================
function OpenPsnWindow(val,userType,uflag,popup)
{							
	var path="customers/createSession.aspx?id="+val+"&userType=" + userType;	
	if(uflag && isNaN(uflag) == true && parseInt(uflag) > 0)
		path += "&uFlag=1";				
	if(popup)
	{
		showWindow(path,800,600,100);
	}
	else
	{
		location.href = path;	
	}				
}
//=====================================================					
			
function showWindow(page,width,height,left,top,isScroll)
{
	var winWidth = 500;
	var winHeight = 200;	
	var winLeft =280;
	var scroll = "yes";
	var winTop=50;
	//----Set width height,top and bottom position ----------------
	if(width)	
		winWidth = width;
	if(height)	
		winHeight = height;	
		
	if(left)	
		winLeft = left;
	if(top)	
		winTop = top;	
	if(isScroll)
		scroll = "no";	
	//------------------------------------------------------------	
	var str ="width="+ winWidth + ",height="+ winHeight +",menubar=no,scrollbars=" + scroll + ",toolbar=no,location=no,directories=no,resizable=1,top=" + winTop + " ,left=" + winLeft + "";	
			
	//---------- Unique window name ---------------
	//---Replace all non character data
	var exp = new RegExp(/[^a-z]/gi);
	var winName = page.replace(exp,"");			
	//----------------------------------------------
	
	win = window.open(page,winName,str);	
	if (win && !win.closed) win.focus();
}	