
//****************************************************************************
// Function to delete blank/white spaces Between Data Entered
//****************************************************************************
function deleteBlanks(entry) {
	var len = entry.length ;
	var foundBlank = 1;
	while(foundBlank == 1 && len > 0) {
		var indx = entry.indexOf(" ");
		if(indx == -1) 
			foundBlank = 0 ;
		else
			entry = entry.substring(0,indx) + entry.substring(indx+1,len);
		len = entry.length;
	}
	
	/* Remove Tabs */
	entry = entry.replace(/\t/, "");
	
	/* Remove Line feed */
	//entry = entry.replace(/\n\r/, "");
	return entry;
}

/************************   Alphabetic value only Writtern by vikas bhawar ****************************/
		 function isAlpha(val)
		{
			
			var val2 = val.value;			
			var regexLetter = /^[a-zA-Z\s]+$/;
			if(regexLetter.test(val2) == false)
			{				
				return false;
			}
			else
			{
					return true;
			}
		}
		
		function isValidPrice(val)
		{
			
			var val2 = val.value;
			var regexLetter = /^(\d+)\.(\d{1,2})$/;///^[1-9]+.?\d+\]$/;
			if(regexLetter.test(val2) == false)
			{				
				return false;
			}
			else
			{
				return true;
			}
		}
		

//****************************************************************************

// Function To validate expiry date of Credit Card.

//****************************************************************************


function FSfncCheckCCexpire(FormField) {
	// Check credit expiry date is in valid format
	var CCexpire=FormField.value;
	if (CCexpire=="") {alert("Please enter your credit card expiry date."); FormField.focus(); return false}
	var ArrayCCexpr=CCexpire.split("/");
	if ((ArrayCCexpr.length!=2) || (ArrayCCexpr[0]=="") || (isNaN(ArrayCCexpr[0])) || (ArrayCCexpr[1]=="") || (isNaN(ArrayCCexpr[1])) || (ArrayCCexpr[0]<1) || (ArrayCCexpr[0]>12)) {alert("Expiry date is not in correct format."); FormField.focus(); return false}
	return true;
	}


/******************************************************************************/
//****************************************************************************
// Function To Check Entered Email Is Containing Any Special Characters or Not
//****************************************************************************
function emailCheck (emailStr) {
	femailStr= emailStr;
	emailStr = emailStr.value;

/* The following pattern is used to check if the entered e-mail address
   fits the user@domain format.  It also is used to separate the username
   from the domain. */
var emailPat=/^(.+)@(.+)$/

/* The following string represents the pattern for matching all special
   characters.  We don't want to allow special characters in the address. 
   These characters include ( ) < > @ , ; : \ " . [ ]    */
var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]$&#?"

/* The following string represents the range of characters allowed in a 
   username or domainname.  It really states which chars aren't allowed. */
var validChars="\[^\\s" + specialChars + "\]"

/* The following pattern applies if the "user" is a quoted string (in
   which case, there are no rules about which characters are allowed
   and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
   is a legal e-mail address. */
var quotedUser="(\"[^\"]*\")"

/* The following pattern applies for domains that are IP addresses,
   rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
   e-mail address. NOTE: The square brackets are required. */
var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/

/* The following string represents an atom (basically a series of
   non-special characters.) */
var atom=validChars + '+'

/* The following string represents one word in the typical username.
   For example, in john.doe@somewhere.com, john and doe are words.
   Basically, a word is either an atom or quoted string. */
var word="(" + atom + "|" + quotedUser + ")"

// The following pattern describes the structure of the user
var userPat=new RegExp("^" + word + "(\\." + word + ")*$")

/* The following pattern describes the structure of a normal symbolic
   domain, as opposed to ipDomainPat, shown above. */
var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")

/* Finally, let's start trying to figure out if the supplied address is
   valid. */
/* Begin with the coarse pattern to simply break up user@domain into
   different pieces that are easy to analyze. */
var matchArray=emailStr.match(emailPat)

if (matchArray==null)
{

  /* Too many/few @'s or something; basically, this address doesn't
     even fit the general mould of a valid e-mail address. */
	alert("Invalid E-mail.")
	femailStr.focus();
	return false
}

var user=matchArray[1]
var domain=matchArray[2]

// See if "user" is valid 
if (user.match(userPat)==null) 
{
    // user is not valid
    alert("Invalid E-mail. The email address doesn't seem to be valid.")
	femailStr.focus();
    return false
}

/* if the e-mail address is at an IP address (as opposed to a symbolic
   host name) make sure the IP address is valid. */
var IPArray=domain.match(ipDomainPat)
if (IPArray!=null) 
{
    // this is an IP address
	  for (var i=1;i<=4;i++) 
	  {
	    if (IPArray[i]>255) 
		{
	        alert("Invalid E-mail. Destination IP address is invalid!")
			return false
	    }

    }

    return true

}



// Domain is symbolic name

var domainArray=domain.match(domainPat)

if (domainArray==null) {

	alert("Invalid E-mail. The domain name doesn't seem to be valid.")
	femailStr.focus();
    return false
}



/* domain name seems valid, but now make sure that it ends in a
   three-letter word (like com, edu, gov) or a two-letter word,
   representing country (uk, nl), and that there's a hostname preceding 
   the domain or country. */
/* Now we need to break up the domain to get a count of how many atoms
   it consists of. */

var atomPat=new RegExp(atom,"g")

var domArr=domain.match(atomPat)

var len=domArr.length

if (domArr[domArr.length-1].length<2 || 

    domArr[domArr.length-1].length>3) {

   // the address must end in a two letter or three letter word.

   alert("Invalid E-mail. The E-mail must end in a three-letter domain, or two letter country.")
   femailStr.focus();
   return false;
}



// Make sure there's a host name preceding the domain.

if (len<2) {

   var errStr="Invalid E-mail. This address is missing a hostname!"
   alert(errStr)
	femailStr.focus();
   return false
}



// If we've gotten this far, everything's valid!

return true;

}

//  End -->


function deleteLineBreaks(entry)
{
	var len = entry.length ;
	var foundBlank = 1;
	while(foundBlank == 1 && len > 0) 
	{
		var indx = entry.indexOf("\r\n");
		if(indx == -1) 
			foundBlank = 0 ;
		else
			entry = entry.substring(0,indx) + entry.substring(indx+2,len);
		len = entry.length;
	}
	return entry;
}


//****************************************************************************

// Function To Check Text box is empty or not

//****************************************************************************


function isEmpty(val,valName)

{

	//alert(val);

	if(!deleteBlanks(val.value))

	{

		alert( pleaseenter + valName);
		
		val.focus();

		return false;	

	}
	
	chkBlank = deleteBlanks(val.value);

	if(!deleteLineBreaks(chkBlank))

	{

		alert( pleaseenter + valName);
		
		val.focus();

		return false;	

	}

	return true;

}

//****************************************************************************

// Function To Check Telephone Number Is Valid or Not

//****************************************************************************

function checktel(tel,valname)

{

	val1=tel.value;

	if (val1!="")

	{

		for (var i=0;i<val1.length;i++)

		{

			var val = val1.charAt(i);

			if ((val1.length<12 ) || (i!=7 && i!=3 && (val<"0" || val>"9") ) || ( (i==3 || i==7) && val!="-" ))

			{

				alert(pleaseenter+ valname + " in the format 999-999-9999");
				
				tel.focus();

				tel.select();

				return false;

			}

		}

	}

	return true;

}



//****************************************************************************

// Function To Check Entered Date Is Valid or Not

//****************************************************************************

function isDate(sdd,smm,syy)

{

	day=sdd[sdd.selectedIndex].value;

	month=smm[smm.selectedIndex].value;

	year=syy[syy.selectedIndex].value;



	errflag=0;

	if (day==0 || month==0 || year==0 || year=='')

		errflag=1;

	if (errflag==0)

	{

		switch(month)

		{

    	  case '2':

	 			leap=year%4;

 				if(leap>0 && day>28)

					errflag=1;

				else if (day>29)

					errflag=1;

				break;

		  case '4':case '6':case '9':case '11':

				if(day>30)

					errflag=1;

		}

	}

	if(errflag==1)

	{

		alert(validdatemsg)

		smm.focus();

		return false;

	}

	return true;

}



function islte(day1,month1,year1,day2,month2,year2,valName1,valName2)
{
	dd1=day1[day1.selectedIndex].value;
	mm1=month1[month1.selectedIndex].value;
	yy1=year1[year1.selectedIndex].value;

	if (!isDate(day1,month1,year1,valName1))
		return false;

	dd2=day2[day2.selectedIndex].value;
	mm2=month2[month2.selectedIndex].value;
	yy2=year2[year2.selectedIndex].value;

	if(dd1<10)
		dd1="0"+dd1;
	if(mm1<10)
		mm1="0"+mm1;
	if(dd2<10)
		dd2="0"+dd2;
	if(mm2<10)
		mm2="0"+mm2;
	
	if((yy1+"-"+mm1+"-"+dd1) > (yy2+"-"+mm2+"-"+dd2))
	{
		alert(valName1 + " can only be on or before " + valName2)
		month1.focus();
		return false;
	}
	return true;
}

function isgte(day1,month1,year1,day2,month2,year2,valName1,valName2)
{
	dd1=day1[day1.selectedIndex].value;
	mm1=month1[month1.selectedIndex].value;
	yy1=year1[year1.selectedIndex].value;

	if (!isDate(day1,month1,year1,valName1))
		return false;

	dd2=day2;
	mm2=month2;
	yy2=year2;

	if(dd1<10)
		dd1="0"+dd1;
	if(mm1<10)
		mm1="0"+mm1;
	if(dd2<10)
		dd2="0"+dd2;
	if(mm2<10)
		mm2="0"+mm2;
	
	if((yy1+"-"+mm1+"-"+dd1) < (yy2+"-"+mm2+"-"+dd2))
	{
		alert(valName1 + " can only be on or after " + valName2)
		month1.focus();
		return false;
	}
	return true;
}


function isTelephone(val1,val2,val3,valName)

{

   

	inv=0;

	v=val1.value+val2.value+val3.value;

	if (v!="")

	{

		if (v.length<10)

			inv=1;

		for (var i=0;i<v.length && inv==0;i++)

		{

			if ( v.charAt(i)<"0" || v.charAt(i)>"9")

				inv=1;

		}



		if (inv==1)

		{

			alert (valName + invalidmsg)

			val1.select();

			val1.focus();

			

			return false;

		}

	}

	return true;

}


/*to check the URL*/
function isUrl(val) {

	theString = val.value;

	if (isEmpty(val, "URL")) {

//		var FirstAtTheRate = theString.indexOf("http://www.");

		var StartsWith = theString.indexOf("http://");

		var Contains = theString.indexOf("//");

		var FirstAtTheRate = theString.indexOf("www.");

		var FirstPeriod = theString.indexOf(".");

		var LastPeriod = theString.lastIndexOf(".");

		var illegalChars= /[\(\)\<\>\,\;\#\$\@\^\*\[\]]/;

		var lengthip=val.value.length;

		var validaip="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.-:/";

		var ipalpha=false;



	    for (var i = 0; i < lengthip; i++) {

			if (validaip.indexOf(val.value.charAt(i)) != -1){
				if (val.value.match(illegalChars)) 	{
					ipalpha = false;
				}
				else
				 	ipalpha = true;
				}
			else 
				ipalpha =false; 
		}
		var j=0;

		for (i=0;i<val.value.length;i++)	{

			if ((val.value.charAt(i)) == ".") {
				if ((val.value.charAt(i+1)) == ".")
					j=1;
			}
		}
		if(ipalpha && j==0) {
			if(Contains >= 0 || StartsWith == 0 || FirstAtTheRate == -1 || FirstPeriod <= 0 || LastPeriod<=1  || LastPeriod == theString.length-1 ||	val.value.charAt(FirstPeriod+1) == "." || val.value.charAt(LastPeriod-1) == "." || LastPeriod == FirstPeriod) {
				alert("Invalid URL");
				val.focus();
				val.select();
				return false;	
			}	
		}
		else {
			alert("Invalid URL");		
			val.focus();
			val.select();
			return false;	
		}
	}
	return true;
}



/* to check numbers*/
function isNum(val, valName)
{	
	if(isNaN(val.value))
	{

		alert(valName + numericvaluemsg);
		val.select();
		val.focus();
		return false;

	}

	if(val.value<0)

	{

		alert(valName + notnegativemsg);

		val.select();

		val.focus();

		return false;

	}	

return 	true;

}

/* Function to check for decimal value in zip */
function isZip(frmElement) {
	var str = frmElement.value;
	for(var i=0; i < str.length; i++) {
		if(str.charAt(i) == '.') {
			alert(invalidzipmsg);
			frmElement.select();
			frmElement.focus();
			return false;
		}
	}
	return true;	
}

//****************************************************************************
// Function To get user confiremation for delete
//****************************************************************************

function confirmUserDelete(msg) {   

   if (confirm("Are you sure you want to delete " + msg +" permanently?"))
	//if (confirm("<?php echo $g_confirmdelete_msg;?> " + msg +" <?php echo $g_permanently_lable;?>"))
		return true;
	else
		return false;
}// end of function



//****************************************************************************
// Function allow a-z ,0-9 and _ only in a testbox --  Added by vineet
// object is accepted as an  parameter 
//****************************************************************************


function checkTestbox(val) {

myRegExp = new RegExp("[^a-z,0-9,_]", "i"); 

res=myRegExp.test(val.value);


 if(res)
{

		alert(onlyalphamsg);
		val.focus();
		val.select();
		return false;
}
return true;

}

//****************************************************************************
// Function To Open page in new window (Bigger Window)
//****************************************************************************
function NewWindowView(mypage, myname, w, h, scroll)
{
	var winl = (screen.width - w) / 4 ;
	var wint = (screen.height - h)/4 ;
	winprops = 'height='+h+',width='+w+',scrollbars=yes,top='+wint+',left='+winl+''
	win = window.open(mypage, myname, winprops)
	if (parseInt(navigator.appVersion) >= 4) { win.window.focus(); }
}

//****************************************************************************
// Function allows only character values to be entered from a-z and A-Z
//****************************************************************************
function characters1(str,str1)
{
	
  var str = str.value;
 if (str == "")
	{
		alert("Please specify "+str1);
		
		return false;
	}
	
	for (var i = 0; i < str.length; i++) 
	  {
		var ch = str.substring(i, i + 1);
		if ( (ch <"a" || ch>"z") && (ch <"A" || ch>"Z")  && (ch!="'")) 
		{	
			alert("Numeric values and special characters not allowed in "+str1);
			return false;
		}
     }
     
     return true;
     
}	


function ValidateEmail(email)
{
email.value=removespaces(email.value);
  if(email.value=="")
	{
		alert(specifyemailmsg);
		email.focus();
		return false;
	}
		
	else
	{
		if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email.value))
		{

		}
		else
		{
			alert(invalidemailmsg);
			email.focus();
			email.select();
			return false;
		}
		
	}
		var str=email.value;
		var flag=false;	
		var j=0;
		for(i=0;i< str.length;i++)
		{
		if(str.charAt(0)=="_" )
			{
			alert(emailbeginalphamsg);
			makeEmpty(email);
			email.focus();
			return false;
			}
		if(str.charAt(i)=="@" )	
		{
		flag=true;
		j=i-1;
		}
		if(flag==true && str.charAt(i)=="_")
		{
		alert(invalidurlinemailmsg);
		email.focus();
		email.select();
		return false;
		}
		if(flag==true && str.charAt(j)=="_")
		{
		alert(invalidemailmsg);
		email.focus();
		email.select();
		return false;
		}
	   	}
	   	return true;
}
		
//****************************************************************************
// Function Trims the leading AND trailing Spaces --  Added by Mir
// object is accepted as an  parameter 
//****************************************************************************

function removespaces(test)
{ 
  size = test.length
 
 while (test.slice(0,1) == " ") //Strip leading spaces
  {test = test.substr(1,size-1);size = test.length
  }
 while(test.slice(size-1,size)== " ") //Strip trailing spaces
  {test = test.substr(0,size-1);size = test.length
  }
  return test;
  }
  
  //Compares date
  
  function compareDates (theMonth,theDay,theYear,mal1,mal2,mal3) {

   var date1, date2;
   var month1, month2;
   var year1, year2;

   month1 = theMonth;
   date1 = theDay;
   year1 = theYear;


   month2 = mal1;
   date2 = mal2;
   year2 = mal3;


   if (year1 > year2) return 1;
  else if (year1 < year2) return -1;
   else if (month1 > month2) return 1;
  else if (month1 < month2) return -1;
   else if (date1 > date2) return 1;
   else if (date1 < date2) return -1;
   else return 0;
} 

//****************************************************************************
// Function allows only character values to be entered from a-z and A-Z in 
//otherthan name fields -pooja
//****************************************************************************
function characters2(str,str1)
{
 
 if (str == "")
	{
		alert("\nPlease Specify " +str1 );
		
		return false;
	}
	if((str.substring(0,1)<"a" || str.substring(0,1)>"z") && (str.substring(0,1)<"A" || str.substring(0,1)>"Z"))
	{
		alert(str1+" should begin with an alphabet");
		return false;
	}
	for (var i = 1; i < str.length; i++) 
	  {
		var ch = str.substring(i, i + 1);
		if ( (ch <"a" || ch>"z") && (ch <"A" || ch>"Z")) 
		{
			alert("Numeric values and special characters not allowed in "+str1);
			return false;
		}
     }
     
     return true;
     
}	

//alows only A-Z, 0-9 and spaces
/* Modified by Kedar on 06022004 */
function isValidText(frmElement, fieldName) {
	myRegExp = new RegExp("[^a-z,0-9,\\s]", "i"); 
	//alert(res);
	if(myRegExp.test(frmElement.value)) {
		alert(specialCharactersNotAllowedIn + fieldName);
		frmElement.focus();
		frmElement.select();
		retVal = false;
	}
	else {
		retVal = true;
	}
	return retVal;
}

function checkPassword(val,valname) {
	var passwordValue = val.value;
	// This is a set of characters other than these characters all r invalid 
	testPattern = /[^A-Z,0-9,_]/i;
	// It checks for the occurance of special cha
	if(!testPattern.test(passwordValue)) {
		blnErrorFound = false;
	}
	else {
		blnErrorFound = true;
	}
	if (blnErrorFound==true) {
		msg=valname+" cannot contain special characters"
		alert(msg);
	}
	return blnErrorFound;
}

/* Fucntion to check the difference between two dates */
function checkDateDiff(startDate, endDate){
	return Date.parse(startDate) > Date.parse(endDate) ? false : true;
}

/* Fucntion to check whethere start date is same or greater than end date */
function checkSameOrLessDate(startDate, endDate) {
	return Date.parse(startDate) >= Date.parse(endDate) ? false : true;
}

// Function to check for valid User Name
function isValidUserName(userNameObj, userNameField) {
	while(1) {
		var retVal = false;
		
		// Check for spaces in the User Name
		if (userNameObj.value != deleteBlanks(userNameObj.value)) {
			alert(theUserNameShouldNotHaveSpaces);
			userNameObj.focus();
			userNameObj.select();
			break;
		}
		
		// Checks for blank User Name
		if(!isEmpty(userNameObj, userNameField)) {
			break;
		}
		else {
			var userNameValue = userNameObj.value;

			// This is a set of valid characters 
			var testPattern = /[^A-Z,0-9,_]/i;

			// It checks for the occurance of special characters
			if(!testPattern.test(userNameValue)) {
				blnErrorFound = false;
			}
			else {
				blnErrorFound = true;
			}
			if (blnErrorFound == true) {
				alert(userNameCannotContainSpecialCharacters);
				userNameObj.focus();
				break;
			}
			
			// To test if User Name starts with number.
			testPattern = /^\D/i;
			if(!testPattern.test(userNameValue)) {
				alert(userNameCannotStartWithNumber);
				userNameObj.focus();
				break;
			}
			
			// Check for length of User Name. It should be between 4 - 10
			if(userNameValue.length < 4 || userNameValue.length > 10) {
				alert(userNameMustBeBetweeb4to10Characters);
				userNameObj.select();
				userNameObj.focus();
				break;
			}
		}
		retVal = true;
		break;
	}
	return retVal;
}

/* To check whole numbers */
function isWholeNum(frmElement, fieldName) {	
	var retVal = false;
	while(1) {
		if(isNaN(frmElement.value)) {
			alert(fieldName + numericvaluemsg);
			frmElement.select();
			frmElement.focus();
			break;
		}
		if(frmElement.value < 0) {
			alert(valName + notnegativemsg);
			frmElement.select();
			frmElement.focus();
			break;
		}
		if(parseInt(frmElement.value) != parseFloat(frmElement.value)) {
			alert(fieldName + isNotAWholeNumber);
			frmElement.select();
			frmElement.focus();
			break;
		}
		retVal = true;
		break;
	}
	return retVal;
}

/* Check whethere number is in proper number format - 12345.12 */
function isValidDecimalNumber(fmElement, separator, fieldName) {
	var retVal = true;
	var num = fmElement.value;
	re = /[^0-9,\.]/;
	if(re.test(num)) {
		alert(fieldName + " " + numericvaluemsg);
		fmElement.focus();
		fmElement.select();
		retVal = false;
	}
	else {
		if (separator == ".") {
			re = /^([0-9]*\.?[0-9]+|[0-9]+\.?[0-9]*)$/;
		}
		else {
			re = /^([0-9]*,?[0-9]+|[0-9]+,?[0-9]*)$/;
		}
		if(!re.test(num)) {
			alert(invalidNumberAtBegin + " '" + separator + "'");
			fmElement.focus();
			fmElement.select();
			retVal = false;
		}
		else {
			if (separator == ".") {
				re = /^\d{1,5}(\.\d{1,2})?$/;
			}
			else {
				re = /^\d{1,5}(,\d{1,2})?$/;
			}
			if(!re.test(num)) {
				alert(invalidNumberFormat);
				fmElement.select();
				fmElement.focus();
				retVal = false;
			}
		}
	}
	return retVal;
}

function checkphoto(val) {
	if(val.value != "") {
		var fil = val.value;
		var ext = fil.substr(fil.lastIndexOf(".")+1).toLowerCase();
		
		if(ext != "jpg" && ext != "jpeg" && ext != "gif") {
			alert("Invalid Image Format");
			val.focus();
			return false;
		}
	}
	return true;
}

//****************************************************************************
// Function To make a list of unchcked checkbox which are previously checked
//****************************************************************************
function chkStatus(chkbox, frm1)
{
        frm1 = document.forms[frm1];
          for(j=0;j<frm1.farmer.length;j++)
        {
            if(frm1.farmer[j].value==chkbox.value && frm1.farmer[j].checked)
                {
                        value = frm1.UnChkArr.value;
                        frm1.newVal.value="";
                        pieces=explodeArray(value,",");
                        count = pieces.length;
                        for(i=0;i<count;i++)
                        {
//alert("Pieces = " + pieces[i]);
                                if (pieces[i]!=chkbox.value)
                                {
                                        if (frm1.newVal.value!="")
                                                frm1.newVal.value = frm1.newVal.value + "," + pieces[i];
                                        else
                                                frm1.newVal.value= pieces[i];
                                }
                                else
                                {
                                        if (i==0 && count==1)
                                                frm1.newVal.value= "";
                                }
//                                alert("newVal.value" + frm1.newVal.value);
                        }

//                        alert("New VAl = " + frm1.newVal.value);
                        frm1.UnChkArr.value = frm1.newVal.value;
//                        alert("Chk Array on Check=" + frm1.UnChkArr.value);
                }
                else if(frm1.farmer[j].value==chkbox.value && !frm1.farmer[j].checked)
                {
//                        alert("unckeck = " + chkbox.value);
                        value = frm1.UnChkArr.value;
                        if (value!="")
                                frm1.UnChkArr.value = frm1.UnChkArr.value + "," + chkbox.value;
                        else
                                frm1.UnChkArr.value = chkbox.value;
//                        alert("UnChk Array =" + frm1.UnChkArr.value);
                }
        }
}

//Function to deselect "Select All" once any of the checkbox is clicked
function deSelect(entry)	{
	for(i=1; i<entry.length; i++)	{
		if((entry[i].checked==false) && (entry[0].checked == true))	{
			entry[0].checked = false;
			break;
		}
	}
	return true;
}

/* Function to check valid document file */
function checkValidDocFile(fileNameObj) {
	while(1) {
		try {
			var retVal = true;
			if(fileNameObj.value != "") {
				retVal = false;
				var fileName = fileNameObj.value;
				var fileExtention = fileName.substr(fileName.lastIndexOf(".")+1).toLowerCase();
				//new RegExp("ab+c", "i") 
				//var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
				//var fileExtentionRegExp = new RegExp("^\[\.doc|\.txt|\.rtf|\.pdf\]$");
				//var fileExtentionRegExp = new RegExp("\w[\.doc,\.txt,\.rtf,\.pdf]$");
				var fileExtentionRegExp = /[\.doc,\.txt,\.rtf,\.pdf]$/;
				//re = /[^0-9,a-z,A-z,_,\/,(),\s]/;
				var ipAddressRE = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/;
				//var fileExtentionRegExp = /\.doc$|\.txt$|\.rtf$|\.pdf$/;
				if(!fileExtentionRegExp.test(fileName)){
					fileNameObj.focus();
					alert("Invalid file Format");
					break;
				}
				/* if(fileExtention != "doc" && fileExtention != "txt" && fileExtention != "rtf" && fileExtention != "pdf") {
					alert("Invalid file Format");
					fileNameObj.focus();
					break;
				} */
			}
		}
		catch(e) {
			/* for (var each in e) {
				alert(e +" is " +e[each]);
			} */
			break;
		}
		retVal = true;
		break;
	}
	alert("RetVal is "+retVal);
	return retVal;
}

//***********************************************************************************
// Function To check entered password is valid or not.
//***********************************************************************************
function ispassword(entry,passsize,min,max) {
	retVal = false;
	
	while(true) {
		if(!isEmpty(entry,"Password")) {
   		break;
		}

	   if(passsize == 'Y') {
			if((entry.value.length < min) || (entry.value.length > max)) {
				alert("Password should be 6 to 10 characters in length");
            entry.select();
            break;
        	}
     	}
	 
		if(!checkSpecialCharTestbox(entry,"Password")) {
			break;
		}
		retVal = true;
		break;
	}
	return retVal;
}


//Function to check for only special characters
function checkSpecialCharTestbox(val,str) {
	retVal = true;
	
	testPattern = /[^A-Z,0-9,_,.,-]/i;
	res=testPattern.test(val.value);
	if(res) {
		alert("Please enter only a-z, A-Z, 0-9, - and _ for " +str);
		val.focus();
		val.select();
		retVal = false;
	}
	return retVal;
}

//Function to check for html or pdf files
function checkhtmlpdffile(val) {
	if(val.value != "") {
		var fil = val.value;
		var ext = fil.substr(fil.lastIndexOf(".")+1).toLowerCase();
		
		if(ext != "html" && ext != "pdf" && ext != "htm") {
			alert("Invalid file Format");
			val.focus();
			return false;
		}
	}
	return true;
}

// Function to open a Help file in a pop-up window
function openHelpWindow(target)
{
	mywin=window.open(target,'a','scrollbars=1,WIDTH=470');
	return false;
}

function checkimagefile(val) {
	if(val.value != "") {
		var fil = val.value;
		var ext = fil.substr(fil.lastIndexOf(".")+1).toLowerCase();
		
		if(ext != "gif" && ext != "jpg" && ext != "jpeg") {
			alert("Uploaded file must be in .gif/.jpg/.jpeg format");
			val.focus();
			return false;
		}
	}
	return true;
}

function isValidDate(dateStr) {
	
var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{2}|\d{4})$/;
var matchArray = dateStr.match(datePat); // is the format ok?
if (matchArray == null) {
alert("Please Enter Date in MM/DD/YYYY Format");
return false;
}
month = matchArray[1]; // parse date into variables
day = matchArray[3];
year = matchArray[4];
if (month < 1 || month > 12) { // check month range
alert("Month must be between 1 and 12.");
return false;
}
if (day < 1 || day > 31) {
alert("Day must be between 1 and 31.");
return false;
}
if ((month==4 || month==6 || month==9 || month==11) && day==31) {
alert("Month "+month+" doesn't have 31 days!")
return false
}
if (month == 2) { // check for february 29th
var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
if (day>29 || (day==29 && !isleap)) {
alert("February " + year + " doesn't have " + day + " days!");
return false;
   }
   
   
}


return true;  // date is valid
}



////////////////////////MOUSE MOVE IMAGE DISPLAY


	
var dom = (document.getElementById) ? true : false;
var ns5 = (!document.all && dom || window.opera) ? true: false;
var ie5 = ((navigator.userAgent.indexOf("MSIE")>-1) && dom) ? true : false;
var ie4 = (document.all && !dom) ? true : false;
var nodyn = (!ns5 && !ie4 && !ie5 && !dom) ? true : false;

var origWidth, origHeight;

if (nodyn) { event = "nope" }


var tipFollowMouse= true;	
// Be sure to set tipWidth wide enough for widest image
var tipWidth= 170;
var offX= 20;	// how far from mouse to show tip
var offY= 12; 
var tipFontFamily= "Verdana, arial, helvetica, sans-serif";
var tipFontSize= "8pt";
// set default text color and background color for tooltip here
// individual tooltips can have their own (set in messages arrays)
// but don't have to
var tipFontColor= "#000000";
var tipBgColor= "#DDECFF"; 
var tipBorderColor= "#000080";
var tipBorderWidth= 3;
var tipBorderStyle= "ridge";
var tipPadding= 4;

// tooltip content goes here (image, description, optional bgColor, optional textcolor)
var messages = new Array();

var startStr = '<table width="' + tipWidth + '"><tr><td align="center" width="100%"><img src="';
var midStr = '" border="0"></td></tr><tr><td valign="top">';
var endStr = '</td></tr></table>';

////////////////////////////////////////////////////////////
//  initTip	- initialization for tooltip.
//		Global variables for tooltip. 
//		Set styles
//		Set up mousemove capture if tipFollowMouse set true.
////////////////////////////////////////////////////////////
var tooltip, tipcss;
function initTip() {
	if (nodyn) return;
	tooltip = (ie4)? document.all['tipDiv']: (ie5||ns5)? document.getElementById('tipDiv'): null;
	tipcss = tooltip.style;
	if (ie4||ie5||ns5) {	// ns4 would lose all this on rewrites
		tipcss.width = tipWidth+"px";
		tipcss.fontFamily = tipFontFamily;
		tipcss.fontSize = tipFontSize;
		tipcss.color = tipFontColor;
		tipcss.backgroundColor = tipBgColor;
		tipcss.borderColor = tipBorderColor;
		tipcss.borderWidth = tipBorderWidth+"px";
		tipcss.padding = tipPadding+"px";
		tipcss.borderStyle = tipBorderStyle;
	}
	if (tooltip&&tipFollowMouse) {
		document.onmousemove = trackMouse;
	}
}

window.onload = initTip;

/////////////////////////////////////////////////
//  doTooltip function
//			Assembles content for tooltip and writes 
//			it to tipDiv
/////////////////////////////////////////////////
var t1,t2;	// for setTimeouts
var tipOn = false;	// check if over tooltip link
function doTooltip(evt,num,img,content) {

messages[0] = new Array(img,content,"#FFFFFF");

	if (document.images) {
	var theImgs = new Array();
	for (var i=0; i<messages.length; i++) {
  	theImgs[i] = new Image();
		theImgs[i].src = messages[i][0];
  }
}
	if (!tooltip) return;
	if (t1) clearTimeout(t1);	if (t2) clearTimeout(t2);
	tipOn = true;
	// set colors if included in messages array
	if (messages[num][2])	var curBgColor = messages[num][2];
	else curBgColor = tipBgColor;
	if (messages[num][3])	var curFontColor = messages[num][3];
	else curFontColor = tipFontColor;
	if (ie4||ie5||ns5) {
		var tip = startStr + messages[num][0] + midStr + '<span style="font-family:' + tipFontFamily + '; font-size:' + tipFontSize + '; color:' + curFontColor + ';">' + messages[num][1] + '</span>' + endStr;
		tipcss.backgroundColor = curBgColor;
	 	tooltip.innerHTML = tip;
	}
	if (!tipFollowMouse) positionTip(evt);
	else t1=setTimeout("tipcss.visibility='visible'",100);
}

var mouseX, mouseY;
function trackMouse(evt) {
	standardbody=(document.compatMode=="CSS1Compat")? document.documentElement : document.body //create reference to common "body" across doctypes
	mouseX = (ns5)? evt.pageX: window.event.clientX + standardbody.scrollLeft;
	mouseY = (ns5)? evt.pageY: window.event.clientY + standardbody.scrollTop;
	if (tipOn) positionTip(evt);
}


function positionTip(evt) {
	if (!tipFollowMouse) {
		mouseX = (ns5)? evt.pageX: window.event.clientX + standardbody.scrollLeft;
		mouseY = (ns5)? evt.pageY: window.event.clientY + standardbody.scrollTop;
	}
	// tooltip width and height
	var tpWd = (ie4||ie5)? tooltip.clientWidth: tooltip.offsetWidth;
	var tpHt = (ie4||ie5)? tooltip.clientHeight: tooltip.offsetHeight;
	// document area in view (subtract scrollbar width for ns)
	var winWd = (ns5)? window.innerWidth-20+window.pageXOffset: standardbody.clientWidth+standardbody.scrollLeft;
	var winHt = (ns5)? window.innerHeight-20+window.pageYOffset: standardbody.clientHeight+standardbody.scrollTop;
	// check mouse position against tip and window dimensions
	// and position the tooltip 
	if ((mouseX+offX+tpWd)>winWd) 
		tipcss.left = mouseX-(tpWd+offX)+"px";
	else tipcss.left = mouseX+offX+"px";
	if ((mouseY+offY+tpHt)>winHt) 
		tipcss.top = winHt-(tpHt+offY)+"px";
	else tipcss.top = mouseY+offY+"px";
	if (!tipFollowMouse) t1=setTimeout("tipcss.visibility='visible'",100);
}

function hideTip() {
	if (!tooltip) return;
	t2=setTimeout("tipcss.visibility='hidden'",100);
	tipOn = false;
}

document.write('<div id="tipDiv" style="position:absolute; visibility:hidden; z-index:100" style="height:80 width:50"></div>')

/*********************************************************************
SERVERSIDE PROCESSING
**********************************************************************/

   var url = "http://localhost/qlico/admin/processfile.php"; 
   function handleHttpResponse() 
   {      
		if (http1.readyState == 4) 
		{    
			  if(http1.status==200) 
			  {   
				  var results=http1.responseText;
				  alert(results);
				  var id = new Array();
				  var catid = new Array(); 
				  var addnewproduct = new Array();
				
				  id=results.split("&");
				 
					//alert('http://localhost/qlico/pics/images/'+id[5]);
				  if(id[0]==01)
				  {
					   document.getElementById('schedule_product_cost').value =id[1];
					   //document.getElementById('image_thumb').innerHTML = "<IMG SRC='http://qlico/pics/images/'+id[2]+>";
					   document.createschedule.imgthumb.src='http://localhost/qlico/pics/images/'+id[2];
					   document.getElementById('mfg_name').innerHTML = id[3];
					   document.getElementById('product_weight').innerHTML = id[4];
					   document.getElementById('product_quantity').innerHTML = id[5];
					   document.getElementById('is_free_shipping').innerHTML = id[6];
					   document.getElementById('sku_no').innerHTML =id[7];
					   
				  }
				
				  if(id[0]==03)
				  {
					  document.getElementById('hours').innerHTML = id[1]+" Hrs -";
					  document.getElementById('minits').innerHTML= id[2]+" Min -";
					  document.getElementById('seconds').innerHTML = id[3]+" Sec";
					  document.getElementById('counter').innerHTML = id[4];
				  }

				  if(id[0]==04)
				  {
					 // document.getElementById('remainig_hours').innerHTML = id[1]+" Hrs - "+id[2]+" Min - "+id[3]+" Sec";
					  document.getElementById('schedule_counter').value =id[4];
					  document.getElementById('second_counter').value =id[5];
					  document.getElementById('schedule_end_time').value =id[6];
					 
					 
					  if(id[9]==05)
					  { 
						  alert("Selected date and time is already scheduled , Please try another.!");
						  return false;
					  }
					  if(id[9]==06)
					  { 
						  alert("Selected date should be greater than or equal to current date.");
						  return false;
					  }
					  if(id[9]==07)
					  { 
						  alert("Selected time should be greater than current time.");
						  return false;
					  }

					  else
					  {
						  document.createschedule.submit.disabled=false;
						   //alert("test");
						  // document.createschedule.submit_button.value ="submit_mode";
						   //document.createschedule.action="http://localhost/qlico/gateway.php?m=admin&p=createschedule";
						//   document.createschedule.method="POST";
						   //document.createschedule.submit();
						   
					  }
 
				  }

				  if(id[0]==08)
				  {
					 
					   id1=id.split("&");
					   alert(id1);
					  
				  }

				  

				 
			  }
		}
   }	



	function funproductdetails(val) 
	{
		//alert(val);
		/*var  category= document.getElementById("txtNewCategory").value;*/
		
		
		var params = 'task=product_details&product_id='+val;
		//alert(params)
		//alert(url)
		http1.open("POST", url, true);
		http1.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		http1.setRequestHeader("Content-length", params.length);
		http1.setRequestHeader("Connection", "close");
		http1.onreadystatechange = handleHttpResponse;
		
		http1.send(params);
		alert(params);
		
		
		var now = new Date();
		var exitTime = now.getTime() + 10;

		while(true)
		{
			now = new Date();
			if(now.getTime() > exitTime) return;
		}
	}

	function funCalculateSecond() 
	{
		//alert(val);
		var  hour= document.createschedule.hour.value;
		var  minute= document.createschedule.minute.value;
		var  schedule_date_time= document.createschedule.schedule_date_time.value;
		var  schedule_product_cost= document.getElementById("schedule_product_cost").value;
		
		if(hour!="" && minute!="" && schedule_date_time!="" && schedule_name!="" && schedule_product_id!="")
		{
			var params = 'task=secon_calc&schedule_product_cost='+schedule_product_cost+'&hour='+hour+'&minute='+minute+'&schedule_date_time='+schedule_date_time;
			//alert(params)
			//alert(url)
			http1.open("POST", url, true);
			http1.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			http1.setRequestHeader("Content-length", params.length);
			http1.setRequestHeader("Connection", "close");
			http1.onreadystatechange = handleHttpResponse;
			
			http1.send(params);
			//alert(params);
			
			
			var now = new Date();
			var exitTime = now.getTime() + 10;

			while(true)
			{
				now = new Date();
				if(now.getTime() > exitTime) return;
			}
		}
		else
		{
			alert("Please Insert or Select Compulsary Fields.");
			return false;
		}
	}
	

		var secs
		var timerID = null
		var timerRunning = false
		var delay = 100

		function InitializeTimer()
		{
			// Set the length of the timer, in seconds
			secs = 500
			StopTheClock()
			StartTheTimer()
		}

		function StopTheClock()
		{
			if(timerRunning)
				clearTimeout(timerID)
			timerRunning = false
		}

		function StartTheTimer()
		{
			if (secs==0)
			{
				StopTheClock()
				// Here's where you put something useful that's
				// supposed to happen after the allotted time.
				// For example, you could display a message:
				//alert("You have just wasted 10 seconds of your life.")
			}
			else
			{
				self.status = secs
				secs = secs - 1
				timerRunning = true
				timerID = self.setTimeout("StartTheTimer()", delay)

				var params = 'task=time_id';
				http1.open("POST", url, true);
				http1.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
				http1.setRequestHeader("Content-length", params.length);
				http1.setRequestHeader("Connection", "close");
				http1.onreadystatechange = handleHttpResponse;
				
				http1.send(params);
				
				
			}
		}



function getHTTPObject() 
{
  var xmlhttp;

  if(window.XMLHttpRequest)
  {
    xmlhttp = new XMLHttpRequest();
  }
  else if (window.ActiveXObject)
  {
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    if (!xmlhttp)
	{
        xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
    }
   
  }
  return xmlhttp;

 
}
var http1 = getHTTPObject(); // We create the HTTP Object
