/************************************************************************
************************************************************************

--------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 Only
NU1-Y/N (+ and -) Both NUMERIC
STN-Y/N Stict 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 ; T - Text(.txt,.csv)
URL-Y/N - For Url

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 :")

var MESS_URL = new String("Invalid format for the field :")
//x

var RE_NUM = /^\-?\d+$/;
// if two digit year input dates after this year considered 20 century.
var NUM_CENTYEAR = 30;

//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 IsValidUrl(value) {
    var s = trim(value);
    if (IsBlank(s) == true) { return true; }

    // var tomatch = /^(https?):\/\/(www\.)?[a-z0-9\-\.\/]{2,}$/;
    // var tomatch = /(ht|f)tp(s?)\:\/\/[0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*(:(0-9)*)*(\/?)([a-zA-Z0-9\-\.\?\,\'\/\\\+&amp;%\$#_]*)?$/;
    var strREg = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
    if (strREg.test(s)) {
        return true;
    }
    else {
        return false;
    }
}

function IsListBoxSelected(objListBox)
{
	if(objListBox.options.length == 0)
		return false;
	if (objListBox.options[objListBox.selectedIndex].value==0 || objListBox.options[objListBox.selectedIndex].value == "")
	{
		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";
	}
	if(type.toUpperCase()=='T')//Text and csv files
	{
		fileExt[0]="TXT";		
		fileExt[1]="CSV";
	}

	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 URL;								//URL 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");
		NU1			= GetCommand(COMMAND_STRING,"NU1");
		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")
		URL			= GetCommand(COMMAND_STRING,"URL")
		
		//= Added new line by ashok,removing all trailing space and blank line before checking constraints =====================				
		if(COMMAND_STRING != "" && (obj.type == "text" || obj.type == "textarea"))
		{		    		    
		    Trimmer(obj);
		}
		if(obj.style.display.toLowerCase() == "none")
		{
		    MESSAGE_ARRAY[i]="";
		    continue;
		}
		//===========================================================================================================

		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 numeric
		if (NU1==YES)
		{
			if (CONTROL_VALUE != "" && isNaN(CONTROL_VALUE)==true && 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 Url
		
		if (URL==YES && MESSAGE_ARRAY[i].length == 0)
		{			
			if (IsValidUrl(CONTROL_VALUE) == false)
			{
				MESSAGE_ARRAY[i] = MESS_URL+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")}
				if (TFP=='T') { var e = new String("TXT,CSV")}
				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) { 
	var i=0;
	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); 
} 
//function to ltrim a string and remove double space to single space
function Trimmer1(ctrl)
{ 
    ctrl.value = LTrim(ctrl.value);
    ctrl.value = replaceAll(ctrl.value,"  "," "); 
} 
//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,chkTime)
{
	var strDate = val.split(' ');
	var tmpDate = strDate[0].split('-');		
	//var rtnDate = new Date(tmpDate[2],tmpDate[1],tmpDate[0]);
	//Javascript months starts from 0 // parseInt(tmpDate[1]) gives an error,so always use second parameter also
	var rtnDate = new Date(tmpDate[2],tmpDate[1]-1,tmpDate[0]);
	
	//======= Check for time also ===========
	if(chkTime && strDate.length > 1)
	{		
		var tmpTime = strDate[1].split(':');
		var strTime = [0,0,0];
		if(tmpTime.length > 0 && isNaN(tmpTime[0]) == false)
			strTime[0] = tmpTime[0];
		if(tmpTime.length > 1 && isNaN(tmpTime[1]) == false)
			strTime[1] = tmpTime[1];
		if(tmpTime.length > 2 && isNaN(tmpTime[2]) == false)
			strTime[2] = tmpTime[2];
			
		rtnDate.setHours(strTime[0],strTime[1],strTime[2]);		
	}
	//========================================
	return rtnDate;
}

//Select/Unselect all checkboxes array
function SelectAll(cntrl,flag) 
{		
	if(! cntrl)
		return;	
		
	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);				
		j =(j < 10 ? "0" : "" ) + j;
		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);	
		j =(j < 10 ? "0" : "" ) + j;	
		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;
	}	
}

function SelectAllChkBoxList(strId,length,flag) 
{			
	var i=0,chkId
	for(i=0; i<length; i++)
	{
		chkId = document.getElementById(strId + "_" + i);
		chkId.checked=flag;	
	}				
}

//------ Check radiobutton or checkbox list that atleast one record should selected
function CheckBoxList(strId,length)
{
	var flag = false;	
	var i=0,chkId;		
	for(i=0; i<length; i++)
	{				
		chkId = document.getElementById(strId + "_" + i);			
		if(chkId.checked == true)
		{
			flag = true;
			break;
		}
	}		
	return flag;	
}
//------------------------------------------------------------------------------

//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(lstId,dirUp)
{	
	var obj = document.getElementById(lstId);
	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 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 "";
}

// date parsing function
function ValidateDate(ctlDate) {       
    str_date = ctlDate.value;
	if(str_date == "")
		return "";
			
	var arr_date = str_date.split('-');

	if (arr_date.length != 3) return ("Invalid date format: '" + str_date + "'.\nFormat accepted is dd-mm-yyyy.");
	if (!arr_date[0]) return ("Invalid date format: '" + str_date + "'.\nNo day of month value can be found.");
	if (!RE_NUM.exec(arr_date[0])) return ("Invalid day of month value: '" + arr_date[0] + "'.\nAllowed values are unsigned integers.");
	if (!arr_date[1]) return ("Invalid date format: '" + str_date + "'.\nNo month value can be found.");
	if (!RE_NUM.exec(arr_date[1])) return ("Invalid month value: '" + arr_date[1] + "'.\nAllowed values are unsigned integers.");
	if (!arr_date[2]) return ("Invalid date format: '" + str_date + "'.\nNo year value can be found.");
	if (!RE_NUM.exec(arr_date[2])) return ("Invalid year value: '" + arr_date[2] + "'.\nAllowed values are unsigned integers.");	
	
	var dt_date = new Date();
	dt_date.setDate(1);

	if (arr_date[1] < 1 || arr_date[1] > 12) return ("Invalid month value: '" + arr_date[1] + "'.\nAllowed range is 01-12.");
	dt_date.setMonth(arr_date[1]-1);
	 
	if (arr_date[2] < 100) arr_date[2] = Number(arr_date[2]) + (arr_date[2] < NUM_CENTYEAR ? 2000 : 1900);
	dt_date.setFullYear(arr_date[2]);

	var dt_numdays = new Date(arr_date[2], arr_date[1], 0);
	dt_date.setDate(arr_date[0]);
	if (dt_date.getMonth() != (arr_date[1]-1)) return ("Invalid day of month value: '" + arr_date[0] + "'.\nAllowed range is 01-"+dt_numdays.getDate()+".");

	ctlDate.value = dt_date.getDate() + "-" + (dt_date.getMonth() + 1) + "-" + dt_date.getFullYear();
	return "";
}

var DateDiff = { 
    inDays: function(d1, d2) {
        var t2 = d2.getTime();
        var t1 = d1.getTime();
 
        return parseInt((t2-t1)/(24*3600*1000));
    },
    inWeeks: function(d1, d2) {
        var t2 = d2.getTime();
        var t1 = d1.getTime();
 
        return parseInt((t2-t1)/(24*3600*1000*7));
    }, 
    inMonths: function(d1, d2) {
        var d1Y = d1.getFullYear();
        var d2Y = d2.getFullYear();
        var d1M = d1.getMonth();
        var d2M = d2.getMonth();
 
        return (d2M+12*d2Y)-(d1M+12*d1Y);
    }, 
    inYears: function(d1, d2) {
        return d2.getFullYear()-d1.getFullYear();
    }
}
//--------------------------------------------------------------------------------------

function checkfext(file1)
{						 
	Trimmer(file1);
	if(file1.value != '')
	{					
		var dotpos = file1.value.lastIndexOf(".");
		var ext = file1.value.substr(dotpos+1);
		if (ext.toUpperCase()== 'TXT' || ext.toUpperCase()== 'PDF' || ext.toUpperCase()== 'DOC' || ext.toUpperCase()== 'GIF' || ext.toUpperCase()== 'JPG' || ext.toUpperCase()== 'JPEG')
		{
			return true;
		}
		else
		{
			alert("Upload File type is TXT,PDF,DOC,GIF & JPEG");
			file1.focus();
			return false;
		}
	}
}

//========== Highlight current row color for given id table=========================
//blid = Table Id
function tableRuler(tblId,bgColor) 
{				
	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='#FFF7E1';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)
{ 
	if(lstId)
	{
		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 ========================
//used for intranet area
function OpenPsnWindow(val,userType,popup)
{							
	var path="customers/createSession.aspx?uFlag=1&id="+val+"&userType=" + userType;	
	if(popup)
	{
		showWindow(path,800,600,100);
	}
	else
	{
		location.href = path;	
	}				
}

//-- used for customers area
function OpenPsnWindow1(val,userType)
{							
	var path="createSession.aspx?uFlag=1&id="+val;	
	if(userType)
		path += "&userType=" + userType;				
	
	location.href = path;			
}
//=====================================================					
		
function commitFlashObject(_obj, _container){
	_output=""
	_paramoutput=""
	_src=""
	_ver=""
	for(_cO in _obj){
		_output+=_cO+"=\""+_obj[_cO]+"\" "
		_paramoutput+="<param name="+_cO+" value=\""+_obj[_cO]+"\">";
		if(_cO=="movie")_src="src=\""+_obj[_cO]+"\"";
		if(_cO=="version")_ver=_obj[_cO];
	}
	if(_ver=="")_ver="8,0,0,0"
	ihtm="<object classid=clsid:D27CDB6E-AE6D-11cf-96B8-444553540000 codebase=http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version="+_ver+" "+_output+">\n"
	ihtm+=_paramoutput+"\n"
	ihtm+="<embed "+_src+" pluginspage=http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash type=application/x-shockwave-flash "+_output+">\n";
	ihtm+="</embed>\n";
	ihtm+="</object>\n";
	document.getElementById(_container).innerHTML=ihtm	
}
//=============== HightLight Current Menu =============
function PageName(strPage)
{
	var sPage = strPage.substring(strPage.lastIndexOf('/') + 1);
	return sPage.toLowerCase();
}
function highlightMenu(pageName,activeClass)
{
    var strClass='highlightMenu';
    if(activeClass && activeClass != "")
        strClass = activeClass;
	var i;		
	try
	{
		var totLinks = document.links.length;
		for(i=0; i< totLinks ; i++)
		{						    
			if(PageName(document.links[i].href) == pageName)
			//if(pageName.indexOf( PageName(document.links[i].href)) != -1)
			{								
				document.links[i].className = strClass;
				break;
			}
		}
	}
	catch(ex)
	{
//		alert(ex.description);
	}		
}
//=====================================================

//=============== Copy data into clipboard -===========
function CopyUrl(data)
{
	window.clipboardData.setData("text",data);
	alert("URL is successfully copied.");				
}	
//=====================================================

function closeWindow(flagRefersh)
{			
	try
	{
		if(flagRefersh)
			window.opener.location.reload();		
	}
	catch(ex)
	{		
	}	
	window.close();
}
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,"");			
	//----------------------------------------------
	
	var win = window.open(page,winName,str);	
	if (win && !win.closed)
	{
		try
		{
			 win.focus();
		}
		catch(ex)
		{
			//alert("Page has already opened.");
		}		
	}		 
}	

function bigimage(image,title,wid,hgt)
{	
	
	var winWidth = wid + 18;
	var winHeight = hgt + 5;
	if(winWidth > 1000)
	{
		winWidth = 1000;
	}
	if(winHeight > 710)
	{
		winHeight = 710;
	}		
	var sw=(screen.width-winWidth)/2 ;
	var sh=((screen.height-winHeight)/2) - 20;		
		
	newwin=window.open('','newwin','width='+winWidth+',height='+winHeight+',scrollbars=1,menubars=0,toolbars=0,loca tion=0,directories=0,status=0,top='+sh+',left='+sw+'');
	newwin.document.open();
	newwin.document.write('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"\n');
	//newwin.document.write('"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">');
	newwin.document.write('\n<html>\n<head>\n<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />\n');
	newwin.document.write('<meta http-equiv="Imagetoolbar" content="no" />\n');
	newwin.document.write('<title>'+title+'</title>\n');
	newwin.document.write('</head>');
	newwin.document.write('<body style="margin:0;padding:0">\n<img border=0 hspace=0 vspace=0 src="'+image+'" width="'+wid+'" height="'+hgt+'" />');
	newwin.document.write('\n</body></html>');
	newwin.document.close();
	newwin.focus();
}

function AddFormElement(eleName,eleType,eleValue,eleParent)
{
        var ele = document.createElement(eleType);
        ele.setAttribute("type", "hidden");
        ele.name = eleName;
        ele.value = eleValue;   
        if(eleParent)
             eleParent.appendChild(ele);  
        
        return ele;   
}
function SetFieldTitle(id,strAlign) {
    var fld = document.getElementById(id);
    if (fld && fld.title != "") {
        Trimmer(fld);
        if (fld.value == "") {
            fld.value = fld.title;
            fld.className = "tt1";
            if(strAlign)
                fld.style.textAlign=strAlign;
        }
       
        fld.onfocus = function () {
            if (this.value.toLowerCase() == this.title.toLowerCase()) {
                this.value = '';
                this.className = "tt1";
                this.style.textAlign='left';                
            }
        };

        fld.onblur = function () {
            Trimmer(this);
            if (this.value == '') {
                this.value = this.title; // $(this).attr('title');
                this.className = "tt1";
                if(strAlign)
                    this.style.textAlign=strAlign;                
            }
        };
    }
}

function fnMoveItems(lstbxFrom,lstbxTo)
{
    var varFromBox = document.getElementById(lstbxFrom);
    var varToBox = document.getElementById(lstbxTo); 

    if ((varFromBox != null) && (varToBox != null)) 
    { 
        if(varFromBox.length < 1) 
        {
            alert('There are no items in the source ListBox');
            return false;
        }
        if(varFromBox.options.selectedIndex == -1) // when no Item is selected the index will be -1
        {
            alert('Please select an Item to move');
            return false;
        }
        while (varFromBox.options.selectedIndex >= 0 ) 
        { 
            var newOption = new Option(); // Create a new instance of ListItem 
            newOption.text = varFromBox.options[varFromBox.options.selectedIndex].text; 
            newOption.value = varFromBox.options[varFromBox.options.selectedIndex].value; 
            varToBox.options[varToBox.length] = newOption; //Append the item in Target Listbox
            varFromBox.remove(varFromBox.options.selectedIndex); //Remove the item from Source Listbox 
        } 
    }
    return false; 
}

function CountMaxChar(val,fldCount,maxChars)
{    
   
     fldCount.innerHTML = maxChars - parseInt(val.value.length);   
}

function ShareOnFb(Url,ImageUrl,title,summary,size)
{

    var str ='http://www.facebook.com/sharer.php?p[url]=' + encodeURIComponent(Url );
    if(ImageUrl && ImageUrl != "")
    {
        str += '&p[images][0]=' +encodeURIComponent(ImageUrl);
    }
     if(size && size > 0)
    {
        str += '&s=' + encodeURIComponent(size);
    }
     if(title && title != "")
    {
        str += '&p[title]=' + encodeURIComponent(title);
    }
     if(summary && summary != "")
    {
        str += '&p[summary]=' + encodeURIComponent(summary) ;
    }    
    return  str;
}
