 /*  #################        HEADER INFORMATION        #####################
    ------------------------------------------------------------------------
    Purpose of page        : common functions
    Page Name              : function.js
    Version Information    : 1st version
    Output Page            : functional dependant
    Date & Time            : 30th June 2006
    Created By             : thaiguys.com team
    Modified               : 30th June 2006
    ------------------------------------------------------------------------
   #################        HEADER INFORMATION        ######################
  */


function addbookmark(pageurl,pagetitle)
  {
	         
			var agt=navigator.userAgent.toLowerCase();
			title="ThaiGuys.com=>"+pagetitle;
		    url="http://www.thaiguys.com/user/"+pageurl;
		   					
       if (agt.indexOf("firefox") != -1)
		   {
			  //if (window.sidebar)
			   // { 
				     window.sidebar.addPanel(title,url,"");
		       // }
			  
			}
			//if(navigator.vandor=="Apple")
		 
		else if (agt.indexOf("safari") != -1)

			{ 
			      alert(" Press(Apple-D) on your keyboard.");
                
			}
		else if((agt.indexOf("msie") != -1)&&(navigator.platform.indexOf('Mac')!=-1))
			{
				  alert(" Press(Apple-D) on your keyboard.");
			}
			
		 else if((agt.indexOf("msie") != -1)&&(navigator.platform.indexOf('Win')!=-1))
			{
			   //	if( window.external )
			    // { 
					 window.external.AddFavorite(url,title)
	    	    // }
		    }
		 
		 else if (agt.indexOf("netscape") != -1)
			{
				alert(" Press(Ctrl-D) on your keyboard.");
			}
		 else if (agt.indexOf("mozilla/5.0") != -1)
			{
				alert(" Press(Ctrl-D) on your keyboard.");
			}
		else if(agt.indexOf("opera") != -1)
			{
				if(window.opera && window.print)
		        { 
		           return true;
		        }
			}
			
}


function is_empty(obj, str)
{
  if ( (obj.type=="text") || (obj.type=="password") || (obj.type=="textarea") || (obj.type=="file"))
  {
    
     if(obj.value=="")
     {
	   alert('Please enter ' + str +'.');
	   obj.focus();
	   return true;
     }
  }
	
  if (obj.type=="select-one")
  {
	  if (obj.selectedIndex==0)
	  {
		  alert('Please select ' + str+ '.' );
		  obj.focus();
		  obj.select;
		  return true;
	  }
  }
  return false;
}


function isValidEmail(obj)
{
	if(!is_empty(obj, "Email")) 
		{
		if(! echeck(obj.value) )
		{
			alert("Please enter valid Email.");
			obj.focus();
			return false;
		}
	}
	else
	{
		return false;
	}
	return true;
}

function isValidLoginId(obj)
{
	if(!is_empty(obj, "Login Id")) {
		if(! echeck(obj.value) )
		{
			alert("Please enter valid Login Id.");
			obj.focus();
			return false;
		}
	}
	else
	{
		return false;
	}
	return true;
}




/*test*/
function Mod10(ccNumb) {  // v2.0
//alert("h!"+ccNumb);
var valid = "0123456789"  // Valid digits in a credit card number
var len = ccNumb.length;  // The length of the submitted cc number
var iCCN = parseInt(ccNumb);  // integer of ccNumb
var sCCN = ccNumb.toString();  // string of ccNumb
sCCN = sCCN.replace (/^\s+|\s+$/g,'');  // strip spaces
var iTotal = 0;  // integer total set at zero
var bNum = true;  // by default assume it is a number
var bResult = false;  // by default assume it is NOT a valid cc
var temp;  // temp variable for parsing string
var calc;  // used for calculation of each digit
 
// Determine if the ccNumb is in fact all numbers
for (var j=0; j<len; j++) {
  temp = "" + sCCN.substring(j, j+1);
  if (valid.indexOf(temp) == "-1"){bNum = false;}
}

// if it is NOT a number, you can either alert to the fact, or just pass a failure
if(!bNum){
  /*alert("Not a Number");*/bResult = false;
}

// Determine if it is the proper length 
if((len == 0)&&(bResult)){  // nothing, field is blank AND passed above # check
  bResult = false;
} else{  // ccNumb is a number and the proper length - let's see if it is a valid card number
  if(len >= 15){  // 15 or 16 for Amex or V/MC
    for(var i=len;i>0;i--){  // LOOP throught the digits of the card
      calc = parseInt(iCCN) % 10;  // right most digit
      calc = parseInt(calc);  // assure it is an integer
      iTotal += calc;  // running total of the card number as we loop - Do Nothing to first digit
      i--;  // decrement the count - move to the next digit in the card
      iCCN = iCCN / 10;                               // subtracts right most digit from ccNumb
      calc = parseInt(iCCN) % 10 ;    // NEXT right most digit
      calc = calc *2;                                 // multiply the digit by two
      // Instead of some screwy method of converting 16 to a string and then parsing 1 and 6 and then adding them to make 7,
      // I use a simple switch statement to change the value of calc2 to 7 if 16 is the multiple.
      switch(calc){
        case 10: calc = 1; break;       //5*2=10 & 1+0 = 1
        case 12: calc = 3; break;       //6*2=12 & 1+2 = 3
        case 14: calc = 5; break;       //7*2=14 & 1+4 = 5
        case 16: calc = 7; break;       //8*2=16 & 1+6 = 7
        case 18: calc = 9; break;       //9*2=18 & 1+8 = 9
        default: calc = calc;           //4*2= 8 &   8 = 8  -same for all lower numbers
      }                                               
    iCCN = iCCN / 10;  // subtracts right most digit from ccNum
    iTotal += calc;  // running total of the card number as we loop
  }  // END OF LOOP
  if ((iTotal%10)==0){  // check to see if the sum Mod 10 is zero
    bResult = true;  // This IS (or could be) a valid credit card number.
  } else {
    bResult = false;  // This could NOT be a valid credit card number
    }
  }
}
// change alert to on-page display or other indication as needed.
/*if(bResult) {
  alert("This IS a valid Credit Card Number!");
}
*/
if(!bResult){
  alert("This is NOT a valid Credit Card Number!");
}
  return bResult; // Return the results
}



function expired( month, year ) {
	//alert("hi"+month+year);
        	var now = new Date();							// this function is designed to be Y2K compliant.
        	var expiresIn = new Date(year,month,0,0,0);		// create an expired on date object with valid thru expiration date
        	expiresIn.setMonth(expiresIn.getMonth());		// adjust the month, to first day, hour, minute & second of expired month
			//alert(now.getMonth()+"month"+expiresIn.getMonth()+"hi"+expiresIn.getTime());
			//return true;
			if( now.getTime() < expiresIn.getTime() ) return false;
        	return true;									// then we get the miliseconds, and do a long integer comparison
    }

// -->
/*test*/

/*============================================================================*/

/*

This routine checks the credit card number. The following checks are made:

1. A number has been provided
2. The number is a right length for the card
3. The number has an appropriate prefix for the card
4. The number has a valid modulus 10 number check digit if required

If the validation fails an error is reported.

The structure of credit card formats was gleaned from a variety of sources on 
the web, although the best is probably on Wikepedia ("Credit card number"):

  http://en.wikipedia.org/wiki/Credit_card_number

Parameters:
            cardnumber           number on the card
            cardname             name of card as defined in the card list below

Author:     John Gardner
Date:       1st November 2003
Updated:    26th Feb. 2005      Additional cards added by request
Updated:    27th Nov. 2006      Additional cards added from Wikipedia

*/

/*
   If a credit card number is invalid, an error reason is loaded into the 
   global ccErrorNo variable. This can be be used to index into the global error  
   string array to report the reason to the user if required:
   
   e.g. if (!checkCreditCard (number, name) alert (ccErrors(ccErrorNo);
*/



function checkCreditCard (cardnumber, cardname) {


var ccErrorNo = 0;
var ccErrors = new Array ()

ccErrors [0] = "Unknown card type";
ccErrors [1] = "No card number provided";
ccErrors [2] = "Credit card number is in invalid format";
ccErrors [3] = "Credit card number is invalid";
ccErrors [4] = "Credit card number has an inappropriate number of digits";
    
  // Array to hold the permitted card characteristics
  var cards = new Array();

  // Define the cards we support. You may add addtional card types.
  
  //  Name:      As in the selection box of the form - must be same as user's
  //  Length:    List of possible valid lengths of the card number for the card
  //  prefixes:  List of possible prefixes for the card
  //  checkdigit Boolean to say whether there is a check digit
  
  cards [0] = {name: "Visa", 
               length: "13,16", 
               prefixes: "4",
               checkdigit: true};
  cards [1] = {name: "MasterCard", 
               length: "16", 
               prefixes: "51,52,53,54,55",
               checkdigit: true};
  cards [2] = {name: "DinersClub", 
               length: "14,16", 
               prefixes: "300,301,302,303,304,305,36,38,55",
               checkdigit: true};
  cards [3] = {name: "CarteBlanche", 
               length: "14", 
               prefixes: "300,301,302,303,304,305,36,38",
               checkdigit: true};
  cards [4] = {name: "AmEx", 
               length: "15", 
               prefixes: "34,37",
               checkdigit: true};
  cards [5] = {name: "Discover", 
               length: "16", 
               prefixes: "6011,650",
               checkdigit: true};
  cards [6] = {name: "JCB", 
               length: "15,16", 
               prefixes: "3,1800,2131",
               checkdigit: true};
  cards [7] = {name: "enRoute", 
               length: "15", 
               prefixes: "2014,2149",
               checkdigit: true};
  cards [8] = {name: "Solo", 
               length: "16,18,19", 
               prefixes: "6334, 6767",
               checkdigit: true};
  cards [9] = {name: "Switch", 
               length: "16,18,19", 
               prefixes: "4903,4905,4911,4936,564182,633110,6333,6759",
               checkdigit: true};
  cards [10] = {name: "Maestro", 
               length: "16", 
               prefixes: "5020,6",
               checkdigit: true};
  cards [11] = {name: "VisaElectron", 
               length: "16", 
               prefixes: "417500,4917,4913",
               checkdigit: true};
                
  // Establish card type
  var cardType = -1;
  for (var i=0; i<cards.length; i++) {

    // See if it is this card (ignoring the case of the string)
    if (cardname.toLowerCase () == cards[i].name.toLowerCase()) {
      cardType = i;
      break;
    }
  }
  
  // If card type not found, report an error
  if (cardType == -1) {
     ccErrorNo = 0;
     return false; 
  }
   
  // Ensure that the user has provided a credit card number
  if (cardnumber.length == 0)  {
     ccErrorNo = 1;
     return false; 
  }
    
  // Now remove any spaces from the credit card number
  cardnumber = cardnumber.replace (/\s/g, "");
  
  // Check that the number is numeric
  var cardNo = cardnumber
  var cardexp = /^[0-9]{13,19}$/;
  if (!cardexp.exec(cardNo))  {
     ccErrorNo = 2;
     return false; 
  }
       
  // Now check the modulus 10 check digit - if required
  if (cards[cardType].checkdigit) {
    var checksum = 0;                                  // running checksum total
    var mychar = "";                                   // next char to process
    var j = 1;                                         // takes value of 1 or 2
  
    // Process each digit one by one starting at the right
    var calc;
    for (i = cardNo.length - 1; i >= 0; i--) {
    
      // Extract the next digit and multiply by 1 or 2 on alternative digits.
      calc = Number(cardNo.charAt(i)) * j;
    
      // If the result is in two digits add 1 to the checksum total
      if (calc > 9) {
        checksum = checksum + 1;
        calc = calc - 10;
      }
    
      // Add the units element to the checksum total
      checksum = checksum + calc;
    
      // Switch the value of j
      if (j ==1) {j = 2} else {j = 1};
    } 
  
    // All done - if checksum is divisible by 10, it is a valid modulus 10.
    // If not, report an error.
    if (checksum % 10 != 0)  {
     ccErrorNo = 3;
     return false; 
    }
  }  

  // The following are the card-specific checks we undertake.
  var LengthValid = false;
  var PrefixValid = false; 
  var undefined; 

  // We use these for holding the valid lengths and prefixes of a card type
  var prefix = new Array ();
  var lengths = new Array ();
    
  // Load an array with the valid prefixes for this card
  prefix = cards[cardType].prefixes.split(",");
      
  // Now see if any of them match what we have in the card number
  for (i=0; i<prefix.length; i++) {
    var exp = new RegExp ("^" + prefix[i]);
    if (exp.test (cardNo)) PrefixValid = true;
  }
      
  // If it isn't a valid prefix there's no point at looking at the length
  if (!PrefixValid) {
     ccErrorNo = 3;
     return false; 
  }
    
  // See if the length is valid for this card
  lengths = cards[cardType].length.split(",");
  for (j=0; j<lengths.length; j++) {
    if (cardNo.length == lengths[j]) LengthValid = true;
  }
  
  // See if all is OK by seeing if the length was valid. We only check the 
  // length if all else was hunky dory.
  if (!LengthValid) {
     ccErrorNo = 4;
     return false; 
  };   
  
  // The credit card is in the required format.

  
  return true;
}

/*============================================================================*/


//**************** Credit Card Number
<!-- Original:  Simon Tneoh (tneohcb@pc.jaring.my) -->

<!-- This script and many more are available free online at -->
<!-- The JavaScript Source!! http://javascript.internet.com -->

<!-- Begin
var Cards = new makeArray(8);
Cards[0] = new CardType("MasterCard", "51,52,53,54,55", "16");
var MasterCard = Cards[0];
Cards[1] = new CardType("VisaCard", "4", "13,16");
var VisaCard = Cards[1];
Cards[2] = new CardType("AmExCard", "34,37", "15");
var AmExCard = Cards[2];
Cards[3] = new CardType("DinersClubCard", "30,36,38", "14");
var DinersClubCard = Cards[3];
Cards[4] = new CardType("DiscoverCard", "6011", "16");
var DiscoverCard = Cards[4];
Cards[5] = new CardType("enRouteCard", "2014,2149", "15");
var enRouteCard = Cards[5];
Cards[6] = new CardType("JCBCard", "3088,3096,3112,3158,3337,3528", "16");
var JCBCard = Cards[6];
var LuhnCheckSum = Cards[7] = new CardType();

/*************************************************************************\
CheckCardNumber(form)
function called when users click the "check" button.
\*************************************************************************/
function CheckCardNumber(form) {


var tmpyear;
if (CardNumber.length == 0) {
alert("Please enter a Card Number.");
form.ccNum1.focus();
return;
}
if (form.ExpYear.value.length == 0) {
alert("Please enter the Expiration Year.");
form.ExpYear.focus();
return;
}
if (form.ExpYear.value > 96)
tmpyear = "19" + form.ExpYear.value;
else if (form.ExpYear.value < 21)
tmpyear = "20" + form.ExpYear.value;
else {
alert("The Expiration Year is not valid.");
return;
}
tmpmonth = form.ExpMon.options[form.ExpMon.selectedIndex].value;
// The following line doesn't work in IE3, you need to change it
// to something like "(new CardType())...".
// if (!CardType().isExpiryDate(tmpyear, tmpmonth)) {
if (!(new CardType()).isExpiryDate(tmpyear, tmpmonth)) {
alert("This card has already expired.");
return;
}
card = form.CardType.options[form.CardType.selectedIndex].value;
var retval = eval(card + ".checkCardNumber(\"" + CardNumber +
"\", " + tmpyear + ", " + tmpmonth + ");");
cardname = "";
if (retval)



// comment this out if used on an order form
alert("This card number appears to be valid.");


else {
// The cardnumber has the valid luhn checksum, but we want to know which
// cardtype it belongs to.
for (var n = 0; n < Cards.size; n++) {
if (Cards[n].checkCardNumber(CardNumber, tmpyear, tmpmonth)) {

cardname = Cards[n].getCardType();


break;
   }
}
if (cardname.length > 0) {
alert("This looks like a " + cardname + " number, not a " + card + " number.");
}
else {
alert("This card number is not valid.");
      }
   }
}
/*************************************************************************\
Object CardType([String cardtype, String rules, String len, int year, 
                                        int month])
cardtype    : type of card, eg: MasterCard, Visa, etc.
rules       : rules of the cardnumber, eg: "4", "6011", "34,37".
len         : valid length of cardnumber, eg: "16,19", "13,16".
year        : year of expiry date.
month       : month of expiry date.
eg:
var VisaCard = new CardType("Visa", "4", "16");
var AmExCard = new CardType("AmEx", "34,37", "15");
\*************************************************************************/
function CardType() {
var n;
var argv = CardType.arguments;
var argc = CardType.arguments.length;

this.objname = "object CardType";

var tmpcardtype = (argc > 0) ? argv[0] : "CardObject";
var tmprules = (argc > 1) ? argv[1] : "0,1,2,3,4,5,6,7,8,9";
var tmplen = (argc > 2) ? argv[2] : "13,14,15,16,19";

this.setCardNumber = setCardNumber;  // set CardNumber method.
this.setCardType = setCardType;  // setCardType method.
this.setLen = setLen;  // setLen method.
this.setRules = setRules;  // setRules method.
this.setExpiryDate = setExpiryDate;  // setExpiryDate method.

this.setCardType(tmpcardtype);
this.setLen(tmplen);
this.setRules(tmprules);
if (argc > 4)
this.setExpiryDate(argv[3], argv[4]);

this.checkCardNumber = checkCardNumber;  // checkCardNumber method.
this.getExpiryDate = getExpiryDate;  // getExpiryDate method.
this.getCardType = getCardType;  // getCardType method.
this.isCardNumber = isCardNumber;  // isCardNumber method.
this.isExpiryDate = isExpiryDate;  // isExpiryDate method.
this.luhnCheck = luhnCheck;// luhnCheck method.
return this;
}

/*************************************************************************\
boolean checkCardNumber([String cardnumber, int year, int month])
return true if cardnumber pass the luhncheck and the expiry date is
valid, else return false.
\*************************************************************************/
function checkCardNumber() {
var argv = checkCardNumber.arguments;
var argc = checkCardNumber.arguments.length;
var cardnumber = (argc > 0) ? argv[0] : this.cardnumber;
var year = (argc > 1) ? argv[1] : this.year;
var month = (argc > 2) ? argv[2] : this.month;

this.setCardNumber(cardnumber);
this.setExpiryDate(year, month);

if (!this.isCardNumber())
return false;
if (!this.isExpiryDate())
return false;

return true;
}
/*************************************************************************\
String getCardType()
return the cardtype.
\*************************************************************************/
function getCardType() {
return this.cardtype;
}
/*************************************************************************\
String getExpiryDate()
return the expiry date.
\*************************************************************************/
function getExpiryDate() {
return this.month + "/" + this.year;
}
/*************************************************************************\
boolean isCardNumber([String cardnumber])
return true if cardnumber pass the luhncheck and the rules, else return
false.
\*************************************************************************/
function isCardNumber() {
var argv = isCardNumber.arguments;
var argc = isCardNumber.arguments.length;
var cardnumber = (argc > 0) ? argv[0] : this.cardnumber;
if (!this.luhnCheck())
return false;

for (var n = 0; n < this.len.size; n++)
if (cardnumber.toString().length == this.len[n]) {
for (var m = 0; m < this.rules.size; m++) {
var headdigit = cardnumber.substring(0, this.rules[m].toString().length);
if (headdigit == this.rules[m])
return true;
}
return false;
}
return false;
}

/*************************************************************************\
boolean isExpiryDate([int year, int month])
return true if the date is a valid expiry date,
else return false.
\*************************************************************************/
function isExpiryDate() {
var argv = isExpiryDate.arguments;
var argc = isExpiryDate.arguments.length;

year = argc > 0 ? argv[0] : this.year;
month = argc > 1 ? argv[1] : this.month;

if (!isNum(year+""))
return false;
if (!isNum(month+""))
return false;
today = new Date();
expiry = new Date(year, month);
if (today.getTime() > expiry.getTime())
return false;
else
return true;
}

/*************************************************************************\
boolean isNum(String argvalue)
return true if argvalue contains only numeric characters,
else return false.
\*************************************************************************/
function isNum(argvalue) {
argvalue = argvalue.toString();

if (argvalue.length == 0)
return false;

for (var n = 0; n < argvalue.length; n++)
if (argvalue.substring(n, n+1) < "0" || argvalue.substring(n, n+1) > "9")
return false;

return true;
}

/*************************************************************************\
boolean luhnCheck([String CardNumber])
return true if CardNumber pass the luhn check else return false.
Reference: http://www.ling.nwu.edu/~sburke/pub/luhn_lib.pl
\*************************************************************************/
function luhnCheck() {
var argv = luhnCheck.arguments;
var argc = luhnCheck.arguments.length;

var CardNumber = argc > 0 ? argv[0] : this.cardnumber;

if (! isNum(CardNumber)) {
return false;
  }

var no_digit = CardNumber.length;
var oddoeven = no_digit & 1;
var sum = 0;

for (var count = 0; count < no_digit; count++) {
var digit = parseInt(CardNumber.charAt(count));
if (!((count & 1) ^ oddoeven)) {
digit *= 2;
if (digit > 9)
digit -= 9;
}
sum += digit;
}
if (sum % 10 == 0)
return true;
else
return false;
}

/*************************************************************************\
ArrayObject makeArray(int size)
return the array object in the size specified.
\*************************************************************************/
function makeArray(size) {
this.size = size;
return this;
}

/*************************************************************************\
CardType setCardNumber(cardnumber)
return the CardType object.
\*************************************************************************/
function setCardNumber(cardnumber) {
this.cardnumber = cardnumber;
return this;
}

/*************************************************************************\
CardType setCardType(cardtype)
return the CardType object.
\*************************************************************************/
function setCardType(cardtype) {
this.cardtype = cardtype;
return this;
}

/*************************************************************************\
CardType setExpiryDate(year, month)
return the CardType object.
\*************************************************************************/
function setExpiryDate(year, month) {
this.year = year;
this.month = month;
return this;
}

/*************************************************************************\
CardType setLen(len)
return the CardType object.
\*************************************************************************/
function setLen(len) {
// Create the len array.
if (len.length == 0 || len == null)
len = "13,14,15,16,19";

var tmplen = len;
n = 1;
while (tmplen.indexOf(",") != -1) {
tmplen = tmplen.substring(tmplen.indexOf(",") + 1, tmplen.length);
n++;
}
this.len = new makeArray(n);
n = 0;
while (len.indexOf(",") != -1) {
var tmpstr = len.substring(0, len.indexOf(","));
this.len[n] = tmpstr;
len = len.substring(len.indexOf(",") + 1, len.length);
n++;
}
this.len[n] = len;
return this;
}

/*************************************************************************\
CardType setRules()
return the CardType object.
\*************************************************************************/
function setRules(rules) {
// Create the rules array.
if (rules.length == 0 || rules == null)
rules = "0,1,2,3,4,5,6,7,8,9";
  
var tmprules = rules;
n = 1;
while (tmprules.indexOf(",") != -1) {
tmprules = tmprules.substring(tmprules.indexOf(",") + 1, tmprules.length);
n++;
}
this.rules = new makeArray(n);
n = 0;
while (rules.indexOf(",") != -1) {
var tmpstr = rules.substring(0, rules.indexOf(","));
this.rules[n] = tmpstr;
rules = rules.substring(rules.indexOf(",") + 1, rules.length);
n++;
}
this.rules[n] = rules;
return this;
}
//  End -->

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




/// Email Checking Pass
function echeck(str) {

   var at="@"
   var dot="."
   var lat=str.indexOf(at)
   var lstr=str.length
   var ldot=str.indexOf(dot)

   if (str.indexOf(at)==-1){
       return false
   }

   if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
       return false
   }

   if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
       return false
   }

   if (str.indexOf(at,(lat+1))!=-1){
      return false
   }

   if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
      return false
   }

   if (str.indexOf(dot,(lat+2))==-1){
   return false
   }

   if (str.indexOf(" ")!=-1){
      return false
   }
   return true
}// End Function

function textarealimit(obj,limit)
{
	if(obj.value.length > limit)
	{
		alert("Maximum limit of textarea is "+limit);
		return true
	}

}
//removes the trailing spaces
function trim(pstrString)
{
  var intLoop=0;
  for(intLoop=0; intLoop<pstrString.length; )
  {
      if(pstrString.charAt(intLoop)==" ")
         pstrString=pstrString.substring(intLoop+1, pstrString.length);
      else
         break;
  }

  for(intLoop=pstrString.length-1; intLoop>=0; intLoop=pstrString.length-1)
  {
      if(pstrString.charAt(intLoop)==" ")
         pstrString=pstrString.substring(0,intLoop);
      else
         break;
  }
  return pstrString;
}


//Validation for Phone numbers

// Declaring required variables
var digits = "0123456789";
// non-digit characters which are allowed in phone numbers
var phoneNumberDelimiters = "()- ";
// characters which are allowed in international phone numbers
// (a leading + is OK)
var validWorldPhoneChars = phoneNumberDelimiters + "+";
// Minimum no of digits in an international phone no.
var minDigitsInIPhoneNumber = 10;

 function isInteger(s)
 {
   var i;
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag)
{   var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function checkInternationalPhone(strPhone)
{
 var s=stripCharsInBag(strPhone,validWorldPhoneChars);
 return (isInteger(s) && s.length >= minDigitsInIPhoneNumber);
}

//function zipcode validations
 function validatezip(zip)
 {
	 var valid = "0123456789-";
	 var hyphencount = 0;
	 var field=zip;
	 
	 if(field.length!=5 && field.length!=10) 
	  {
	   alert("Please Enter your 5 digit or 5 digit+4 zip code.");
	   return false;
	  }
	 for(var i=0; i < field.length; i++)
	 {
	  temp = "" + field.substring(i, i+1);
	   if(temp == "-") hyphencount++;
	   if(valid.indexOf(temp) == "-1") 
		   {
			 alert("Invalid zip code.");
			 return false;
		   }
	  if((hyphencount>1) || ((field.length==10) && ""+field.charAt(5)!="-"))
	   { 
		alert("Invalid Zip code");
		return false;
	   }
	 return true;
	 }
 }

//function zipcode validations
 function validatezip1(zip)
 {
	 var valid = "0123456789-";
	 var hyphencount = 0;
	 var field=zip;
	 
	for(var i=0; i < field.length; i++)
	 {
	  temp = "" + field.substring(i, i+1);
	   if(temp == "-") hyphencount++;
	   if(valid.indexOf(temp) == "-1") 
		   {
			 alert("Invalid zip code.");
			 return false;
		   }
		if((hyphencount>1) || ((field.length>10) ))
	   { 
		alert("Invalid Zip code");
		return false;
	   }
	 return true;
	 }
 }






 //function  validate date
function testdate(day,month,year)
{ 
	 var myDayStr = day;
	 var myMonthStr = month;
	 var myYearStr = year;
	 		 
	var myMonth = new Array('January','February','March','April','May','June','July','August','September','October','November','December');

	var myDateStr = myDayStr + ' ' + myMonth[myMonthStr] + ' ' + myYearStr;

	/* Using form values, create a new date object
	using the setFullYear function */
	var myDate = new Date();
	myDate.setFullYear( myYearStr, myMonthStr, myDayStr );
	//alert(myDate.getMonth());
	//alert(myMonthStr);
	if ( myDate.getMonth() != myMonthStr )
	{
		 alert( 'Sorry, "' + myDateStr + '" is NOT a valid date.' );
	}
	else
	{
	  //alert( 'Congratulations! "' + myDateStr + '" IS a valid date.' );
	   return true;
	}
  
}



//perfect email validation
function emailCheck(s)
{
    // email text field.
    var sLength = s.length;
    var denied_chars = new Array(" ", "\n", "\t", "\r", "%", "$", "#", "!", "~", "`", "^", "&", "*", "(", ")", "=", "+", "{", "}", "[", "]", ",", ";", ":", "'", "\"", "?", "<", ">", "/", "\\", "|");

    // look for @
    if (s.indexOf("@") == -1) return false;

    // look for more than one @ sign
    if (s.indexOf("@") != s.lastIndexOf("@")) return false;

    // look for any special character
    for (var z = 0; z < denied_chars.length; z++) {
        if (s.indexOf(denied_chars[z]) != -1) return false;
    }

    // look for .
    if (s.indexOf(".") == -1) return false;

    // no two dots alongside each other
    if (s.indexOf("..") != -1) return false;

    // you can't have and @ and a dot
    if (s.indexOf("@.") != -1) return false;

    // the last character cannot be a .
    if ((s.charAt(sLength-1) == ".") || (s.charAt(sLength-1) == "_")) return false;

    return true;
}



//URL validation Script
function validateurl(urlstr)
{
document.frm.txturl.value=trim(document.frm.txturl.value);
var b=document.frm.txturl.value;
if(b.match(/^http:\/\/\w+(\.\w+)*\.(\w{2}|com|net|org|mil|int|edu|gov|info|biz|coop|aero|pro|name|museum)(\/[\w\-\.])*$/) == null)
  {
       alert("Invalid URL.");
       return false;
  }
  else
 {
	  return true;
 }
}

//RAHUL
/* Following 2 routines set the color of the input boxes */
function fnCFocus(obj) 
{
	obj.style.backgroundColor = '#f2faff';
	obj.style.borderColor = '#116aaa';
	obj.style.color = '#000000';
}

function fnCBlur(obj) 
{
	obj.style.backgroundColor = '#ffffff';
	obj.style.borderColor = '#6caad6';
	obj.style.color = '#000000';
}

function jsIsNull(obj,objname)	{   ///    Abhishek
try{
	if (trim(obj.value) == "" || trim(obj.value) == " ")	{
			output = display('EMPTY_TEXT',objname);
			//obj.style.borderColor = _ERROR_COLOR_;
			return output;
	}
			return;
	}catch(e){}
}

//functions from jsfunction.js from recs and rips
_ERROR_COLOR_ = '#86b262';
_SELECT_CRITERIA_ = 'You have not selected any criteria.';
var dateseperator = '-';
var whitespace =" \t\n\r ";




function MM_goToURL() { //v3.0
  var i, args=MM_goToURL.arguments; document.MM_returnValue = false;
  for (i=0; i<(args.length-1); i+=2) eval(args[i]+".location='"+args[i+1]+"'");
}
function changedate_todbformat(obj)
{
	arr = obj.value.split(dateseperator);
	obj.value=arr[2]+dateseperator+arr[0]+dateseperator+arr[1];
}
function newwindow(page,companyname,combo,group,extra)
{
	var cname,ccombo,group;
		cname = companyname;
	if(combo!=0)
		ccombo = combo;
	if(group!=0)
		group = group;	
	if(extra!=0)
	window.open(page+'?companygroup='+group+'companycombo='+ccombo+extra+'&selcompany='+cname,'','scrollbars=1,left=10,height=700,width=1000,top=1')
	//document.frm.submit();
}

 function pointswindow(fileName)
{
  window.open(fileName,"NewWindow","toolbar=no,left=100,top=100,width=400,height=300,resizable=yes,scrollbars=no");
}

function redirect(page,companyname,combo,group,extra)
{
	document.frm.selcompany.value=companyname;
	if(combo!=0)
		document.frm.companycombo.value=combo;
	if(group!=0)
		document.frm.companygroup.value=group;	
	if(page!=0)
	document.frm.action = page;
	if(extra!=0)
	document.frm.action += extra;
//	alert(document.frm.companycombo.value);
	document.frm.submit();
}

function isEmpty(str) {  
	return ((str == null) || (str.length == 0) || (str == " "));
}

function isWhitespace(str) {
	var i;
	var flag
	if (isEmpty(str)) return true;		
	for (i = 0; i < str.length; i++) {   
		var c = str.charAt(i);
		if (whitespace.indexOf(c) == -1)
		return false
	}	
		return true;
}

function datedifference(obj1,obj2)
{	
	//convert to mm/dd/yy  from 
	arr=obj1.split(dateseperator);
//	obj1=arr[1]+"/"+arr[0]+"/"+arr[2];
	arr=obj2.split(dateseperator);
//	obj2=arr[1]+"/"+arr[0]+"/"+arr[2];
	date1 = new Date(obj1);
	date2 = new Date(obj2);
	diff = date1 - date2;
//	alert(obj1+' '+obj2+' '+diff);
	return diff;
}

function display(statement,obj_name)	{
	switch (statement)
	{
		//statement="Check the following information \n";
		case "EMPTY_TEXT":
			//statement="Enter "+obj_name.substr(0)+".";    //eg. Enter <<text box Name>>.    Abhishek
		      statement="- "+obj_name+".";    //eg. Enter <<text box Name>>.    Preetam
			break;
		case "UNSELECTED_COMBOBOX":
			statement="Select "+obj_name.substr(0)+".";   //eg. Select <<Combo box name>>.    Abhishek
			break;			
		case "INVALID_PHONE_FAX":
			statement="- Valid "+obj_name+" ( Only numeric characters with - + ( ) ).";   //eg. Select <<Combo box name>>.    Abhishek
			break;			
				case "INVALID_PHONE":
			statement="Invalid "+obj_name+". Only numeric characters with - + ( ) allowed." ;   //eg. Select <<Combo box name>>.    Abhishek
			break;			
		case "INVALID_NUMERIC":
			statement="- Valid "+obj_name+" ( Only numeric characters ).";   //eg. Select <<Combo box name>>.    Abhishek
			break;			
		case "INVALID_EMAIL":
			statement="- Valid "+obj_name+".";   //eg. Select <<Combo box name>>.    Abhishek
			break;			
		case "INVALID_URL":
			statement="- Valid "+obj_name+".";   //eg. Select <<Combo box name>>.    Abhishek
			break;
		case "INVALID_FROM_DATE":
			statement=obj_name+" should be greater than or equal to today's date";		
			break;
		case "INVALID_TO_DATE":
			statement=obj_name+" should be greater than or equal to Dispaly from";		
			break;
		case "INVALID_FROMTO_DATE":
			statement="- Valid "+obj_name+".";   //eg. Select <<Combo box name>>.    Abhishek
			break;
		case "INVALID_INPUT":
			statement="- Valid "+obj_name+".";   //eg. Select <<Combo box name>>.    Abhishek			break;			
			break;
		case "INVALID_CONFIRMPASSWORD":
			statement="- "+obj_name+" and confirm password should be same.";
			break;
		case "INVALID_AGELIMIT":
			statement="should be grater than 18 years old";
			break;
		case "INVALID_ANNI_DATE":
			statement=obj_name+" should be greater than or equal to Birth Date";		
			break;
	    case "INVALID_FROMLEAVE_DATE":
			statement=obj_name+" should be greater than or equal to From Date";		
			break;
		case "INVALID_PHOTO_TYPE":
			statement=obj_name+" Only.jpg/.jpeg/.gif/.bmp images allowed";		
			break;

		case "BACKSLASH_DOUBLEQUOTE":
			statement = "Backslash is not allowed in "+obj_name+"."
			break;	

		default:
				alert('[Error: jfunction.js] check the display function.');
		
	}//switch
	return statement+'\n';
}
function validateURL(obj)
{
	var objValue=obj.value;
	//var characters="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZáéíóñúüæoå'#!¤ Å^ Æüæå»«øØ.-#:\\_()&%$@?=^~.+/ "
	var characters="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZáéíóñúüæoå#!¤Å^Æüæå»«øØ.-#:\_()&%$@?=^~.+/"
	var tmp
	var lTag
	lTag = 0
	temp = (objValue.length)
	for (var i=0;i<temp;i++)
	{
			tmp=objValue.substring(i,i+1)
			if (characters.indexOf(tmp)==-1)
			{
					lTag = 1
			}
	}
	if(lTag == 1)
		//alert("Invalid website url");
		//	document.frm[obj.name].focus();
			return false
	else
			return true

}

//URL Validation
/*function isValidateURL(obj,msg)
{				
	var strurl= trim(obj.value);
	if (urlRegxp.test(strurl) != true)
	 {
	     alert('Unvalid URL');
	     return false;
	 }
	 else
	 	return true;
}*/


function isValidatechar(characters,obj,msg)
{
				var objValue=obj.value;
                var tmp
                var lTag
                lTag = 0
                temp = (objValue.length)
                for (var i=0;i<temp;i++)
                {
                        tmp=objValue.substring(i,i+1);
                        if(characters.indexOf(tmp)>=0)
                        {
                                lTag = 1
                                break;
                        }
                }
                if(lTag == 1)
				{
       				output = display('INVALID_EMAIL',msg)
					//obj.style.backgroundColor = _ERROR_COLOR_;//document.frm[obj.name].focus();		
                    return output;
				}				
                else
				{
			        return;
				}		
}


// function to check valid email
function IsEmail(InString) {
  //alert(InString)
	var left, right;
	if(InString.length==0) return(false);
	for(Count=0;Count<InString.length;Count++) {
		TempChar = InString.substring(Count,Count + 1);
		if("1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.@_-".indexOf(TempChar,0)==-1) return(false); 
	}
	if(InString.indexOf('@')< 1) return(false);
	if(InString.lastIndexOf('@')!= InString.indexOf('@')) return(false);
	left = InString.substring(0,InString.indexOf('@'));
	right = InString.substring(InString.indexOf('@') + 1,InString.length);
	if((!isDotExpression(left,0))||(!isDotExpression(right,1))) return(false);
	return(true);
}

function isDotExpression(InString,NeedsDot) {
	var dots,index,tmpNeedDot;
	dots=0;
	for(index=0;index<InString.length;index++) {
		if(InString.substring(index,index+1)==".") {
		if((index==0)||(index==InString.length-1)) return(false);
			dots ++;
			if(dots>1)tmpNeedDot=1;
			else tmpNeedDot=0;
			if(!isDotExpression(InString.substring(0,index),tmpNeedDot)) return(false);	
		}      
	}
	if((NeedsDot==1)&&(dots<1)) return (false);
	if(InString.length < dots * 2+1) return (false);
	return (true);
}


function sendemail()
{
	//Email.location.href= '../includes/mail.php';
	window.open('../includes/mail1.php','mail','width=400,height=200,left=300,top=250');
}

function IsEmailValid(obj,msg)
{
if(get = isValidatechar("\"'~`!#$%^&*()+=|\\:;<>,?/{}[]",obj,"E-mail address ( ''~`!#$%^&*()+=|\\:;<>,?/{}[]' not allowed )"))
	return get;
var lEmailId=obj.value;        var c1;        var c2;        var c3;        var c4;        var c5;        var c6;        var varlast;
        emlchar =lEmailId //.value;
        emlchar = emlchar.toLowerCase() ;
       /* if(trimstr(lEmailId)==-1) {
                return false;
        }*/

        c1 = emlchar.indexOf("@");
        c2 = emlchar.indexOf(".");
        c3 = occurs("@", lEmailId) ;
        c4 = emlchar.indexOf("-");
        c5 = occurs(" ", lEmailId) ;
        varlast = emlchar.lastIndexOf(".");
        //alert (emlchar.length);
        //alert (varlast);
                if (varlast+1 == emlchar.length ){
                        c6 = 0;
        }

// Explanation..
// c1== -1        @ must be present
// c2== -1        . must be present
// c1== 0        @ cannot come as first character
// c2== 0        . cannot come as first character
// c1==c2-1        @. back-to-back not allowed
// c1==c2+1        .@ back-to-back not allowed
// c3!=1        @ can occur only once
// (c4 != -1 && c4 < c1)                if hyphen present & comes before @ not allowed
// (c4 != -1 && c4 == emlchar.length-1) if hyphen present & comes as a last character not allowed

        if (c1==-1 || c2==-1 || c1== 0 || c2==0 || c1==c2-1 || c1==c2+1 || c3!=1 || (c4 != -1 && c4 == emlchar.length-1) || c5 >= 0 || c6 == 0)
        {
               // lEmailId.focus();
				output = display('INVALID_EMAIL',msg);
				//document.frm[obj.name].focus();		
				//obj.style.backgroundColor = _ERROR_COLOR_;
                return output;
        }

        if (emlchar.length < 5 || c1==emlchar.length - 1 || c2==emlchar.length - 1 )
        {
                //lEmailId.focus();
				output = display('INVALID_EMAIL',msg);
				//obj.style.backgroundColor = _ERROR_COLOR_;//document.frm[obj.name].focus();		
                return output;
        }

        tmpStr = "0123456789_-abcdefghijklmnopqrstuvwxyz" ;
        cnt = 0;
        i = emlchar.indexOf(".", cnt);

        while (true) {
                ch1 = emlchar.charAt(i-1) ;
                ch2 = emlchar.charAt(i+1) ;
                if (tmpStr.indexOf(ch1) == -1 || tmpStr.indexOf(ch2) == -1)
				{
      					output = display('INVALID_EMAIL',msg);
						//obj.style.backgroundColor = _ERROR_COLOR_;//document.frm[obj.name].focus();		
				        return output;
				}
                cnt = cnt + 1 ;
                i = emlchar.indexOf(".", cnt);
                if (i == -1)
                        break;
        }

        return;
}

/*function datedifference(obj1,obj2)
{
	date1 = new Date(obj1.value);
	date2 = new Date(obj2.value);
	diff = date1 - date2;
	return diff;
}*/

/*
FUNCTION CHECKS FOR NUMERIC DATA
Description:
			Fuction for checkin all numeric characters 
			so if the string contains characters from this set ,this function will return true
			else
			it will return false and call Display() fn for genetrating error message.
Paramters:	1: obj : form object		
			2: msg : control name which will be displayed at the time of error . 
*/
function jsIsAllNumeric(obj,msg)
{
				var objValue=obj.value;
                        lTempLength = objValue.length
                        lTempCounter = 0
                        lTempString = trim(objValue)
                        flag = false

                        do
                        {
                        if(lTempString.charAt(lTempCounter) == " ")
                        {
                                flag = false
                                break
                        }
                        else if(lTempString.charAt(lTempCounter) > 0 || lTempString.charAt(lTempCounter) < 9)
                                flag = true
                        else
                                {
                                        flag = false
                                        break
                                }
                                lTempCounter = lTempCounter + 1
                        }
                        while(lTempCounter <= lTempLength)

                        if(flag == true)
                                return;
                        else
						{
	                  			output = display('INVALID_NUMERIC',msg);
								//obj.style.backgroundColor = _ERROR_COLOR_;								
								return output;
						}		
}


/*
FUNCTION CHECKS FOR VALID PHONE NO.	
Description:
			Phone no or fax can contains all numeric characters with + - ( )
			so if the string contains characters from this set ,this function will return true
			else
			it will return false and call Display() fn for genetrating error message.
Paramters:	1: obj : form object		
			2: msg : control name which will be displayed at the time of error . 
*/
function jsValidatePhoneFax(obj,msg)
{
				var objValue=obj.value;
				//alert(objValue);
                var characters=" -()+1234567890"
                var tmp
                var lTag
                lTag = 0
                temp = (objValue.length)
                for (var i=0;i<temp;i++)
                {
                        tmp=objValue.substring(i,i+1)
                        if (characters.indexOf(tmp)==-1)
                        {
                                lTag = 1
                        }
                }
                if(lTag == 1)
				{
					 output = display('INVALID_PHONE',msg);
					 	alert(output);
						//obj.style.backgroundColor = _ERROR_COLOR_;//document.frm[obj.name].focus();		
                        return output;
				}		
                else
                        return ;
}

/*function fnCFocus(obj) { // abhishek
		obj.style.borderColor = '#86b262';
}// function */

function jsHasBackSlash_DoubleQuote(obj,objname)	{    /// Abhishek
//	if (obj.value.indexOf ("\\") > -1 ||  obj.value.indexOf ("\"")> -1) 	{		
	if (obj.value.indexOf ("\\") > -1 ) 	{		
			output = display('BACKSLASH_DOUBLEQUOTE',objname);
			//obj.style.backgroundColor = _ERROR_COLOR_;
		return output;
	}
	return;
}

function jsIsNull(obj,objname)	{   ///    Abhishek
try{
	if (trim(obj.value) == "" || trim(obj.value) == " ")	{
			output = display('EMPTY_TEXT',objname);
			//obj.style.borderColor = _ERROR_COLOR_;
			return output;
	}
			return;
	}catch(e){}
}

function jsIsNullTinyText(obj,objname)	{   
	if (trim(tinyMCE.getContent()) == "" || trim(tinyMCE.getContent()) == " ")	{
			output = display('EMPTY_TEXT',objname);
			obj.style.borderColor = _ERROR_COLOR_;
			return output;
	}
			return;
}

function change_date(obj)
{
	// from  mm dd yy to yy mm dd 
	arr = obj.value.split("/");
	obj.value = arr[2]+"-"+arr[0]+"-"+arr[1];	
	return;
}

function jsIsComboUnselected(obj,objname)	{  
	if (trim(obj.value) == "" || trim(obj.value) == " " || trim(obj.value) == "0" || trim(obj.value) == 0)	{
			output = display('UNSELECTED_COMBOBOX',objname);
			//obj.style.backgroundColor = _ERROR_COLOR_;
			return output;
	}
			return;			
}

function trim(pstrString)
{
        var intLoop=0;
        for(intLoop=0; intLoop<pstrString.length; )
        {
			if(pstrString.charAt(intLoop)==" ")
				pstrString=pstrString.substring(intLoop+1, pstrString.length);
			else
				break;
        }

        for(intLoop=pstrString.length-1; intLoop>=0; intLoop=pstrString.length-1)
        {
                if(pstrString.charAt(intLoop)==" ")
                        pstrString=pstrString.substring(0,intLoop);
                else
                        break;
        }
        return pstrString;
}

function occurs(ch, fieldname) {
        cnt         = 0
        flag        = 0
        for (i=0; i < fieldname.length; ++i) {
                if (fieldname.substring(i,i+1) == ch) {
                        cnt = cnt + 1 ;
                        flag= 1;
                }
        }
        if (flag == 1)
                return (cnt) ;
        else
                return (-1) ;
}

function jsChangeCity(value)
{
	document.frm.cmbcity.length = 1;
	index = 1;
	for(i=0;i<cityarray.length;i++)
	{
		if(cityarray[i][2] == value)
			document.frm.cmbcity.options[index++] = new Option(cityarray[i][1],cityarray[i][0]);
	}
}

 function isValidFirstDate(firstyr,firstmn,firstdt,secyr,secmn,secdt) {
   if(firstyr < secyr)
   {
     return false;
   }
     else if (firstyr > secyr)
     {
       return true;
     }
     else if (firstyr==secyr)
     {
			if(firstmn<secmn)
			{
			   return false;
			}
			else if (firstmn > secmn)
			{
				return true;
			}
            else
			{
			  if(firstdt < secdt)
			  {
				return false;
			  }
			  else if (firstdt >= secdt)
			  {
				return true;
			  }
        }//same month
    }//else yr same
}//Function To check whether First Greater Than Secojnd Ends Here

function isValidatePhone(phone)
{
	
				var objValue=phone;
                        lTempLength = objValue.length
                        lTempCounter = 0
                        lTempString = trim(objValue)
                        flag = false

                        do
                        {
                        if(lTempString.charAt(lTempCounter) == " ")
                        {
                                flag = false
                                break
                        }
                        else if(lTempString.charAt(lTempCounter) > 0 || lTempString.charAt(lTempCounter) < 9)
                                flag = true
                        else
                                {
                                        flag = false
                                        break
                                }
                                lTempCounter = lTempCounter + 1
                        }
                        while(lTempCounter <= lTempLength)

						return flag;
}


function jsFormsubmit(val)
{
	document.write("<form name='frmgen' method='post'>");
	document.write("<input type='hidden' name='lvid' value="+val+">");
	document.write("</form>");

	document.frmgen.action = "leave.php";
	document.frmgen.submit();
}

function jsFormsubmit1(val,filename)
{
	
	document.write("<form name='frmgen' method='post'>");
	document.write("<input type='hidden' name='genvar' value="+val+">");
	document.write("</form>");
	document.frmgen.action = filename;
	document.frmgen.submit();
	
}


function fneditnews(pagename,id,val)
{
    eval("document.frm."+id+".value="+val+";");
    document.frm.action=pagename+".php";
    document.frm.submit();
}

function fndeletenews(id)
{
  if (confirm("Do you want to delete the record?"))
	{
	   document.frm.page_action.value="newsdelete";
	   document.frm.delid.value=id;	
	   document.frm.submit();
	}
}

function fnchangestatus(status,id)
{
	if(status==1)
	{
	 if (!confirm("Do you want to deactivate the record?"))
	  return false;
	}
	else
	{
	 if (!confirm("Do you want to activate the record?"))
	   return false;
	}
	if(status==1)
		var changedstatus=0;
	else
		var changedstatus=1;
	document.frm.delid.value=id;	
	document.frm.hidstatus.value=changedstatus;	
	document.frm.page_action.value="newsstatus";
	document.frm.submit();

}
function CheckBlank(objname,alertmsg)
{
	for(var i=1;1;i++)
	{
		try
		{ 
			var obj = document.getElementById(objname+i);
			//alert(obj.id);
			if(obj.value=="")
			{
				alertMessage += "-"+alertmsg;
				obj.focus();
			}
		}
		catch(e)
		{
			break;
		}
	}
}

function openNewWindow(fileName)
{
  window.open(fileName,"NewWindow","toolbar=no,left=100,top=100,width=570,height=360,resizable=yes,scrollbars=yes");
}


function IsValidUsername(sText)
{
   var ValidChars="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_"
   var charflag=true;
   var Char; 
   for (i = 0; i < sText.value.length; i++) 
   { 
      Char = sText.value.charAt(i); 
      if (ValidChars.indexOf(Char) == -1) 
              charflag = false;
   }
   return charflag;
    
   }

/*function ChkUrl(obj)
{
	s=obj.value;
	if(s.substr(0,11)!="http://www.")
			return false;
	else
		return true;
}*/
function showresult(file,page,querystring){
	if(querystring.length> 1) 	{
		if (querystring.indexOf("&page") >1)
				querystring = querystring.substr(0,querystring.indexOf("&page"));
		document.frm.action+="?"+querystring;
	}				
	document.frm.pageno.value=page;
	document.frm.submit();
	}


function CheckURL(obj)
{
	url=obj.value;

	var v = new RegExp(); 
	v.compile("^[A-Za-z]+://[A-Za-z0-9-_]+\\.[A-Za-z0-9-_%&\?\/.=]+$"); 
	if(!v.test(url))
		return false;
	else
		return true;

}

function CreateBookmark() 
{ 
	title = "Recs & Rips.com";   
	// Blogger - Replace with <$BlogItemTitle$>   
	// MovableType - Replace with <$MTEntryTitle$> 
	url = "http://www.recsandrips.com";  
	// Blogger - Replace with <$BlogItemPermalinkURL$>   
	// MovableType - Replace with <$MTEntryPermalink$>  
	// WordPress - <?php bloginfo('url'); ?>	
	
	if (window.sidebar) 
	{ // Mozilla Firefox Bookmark		
		window.sidebar.addPanel(title, url,"");	
	} else 
	if( window.external ) 
	{ // IE Favorite		
		window.external.AddFavorite( url, title); 
	} else 
	if(window.opera && window.print) 
	{ // Opera Hotlist		
		return true; 
	} 
}

function getFileType(str)
{
	  
		if(str.match(".gif")||str.match(".jpeg")||str.match(".jpg"))
				{
			      return true;
				}
		else 
	   	{
			   return false;
			}

 }

function getResumeType(str)
{
	if(str.match(".pdf")||str.match(".doc")||str.match(".txt")||str.match(".rtf"))
	{
		return true;
	}
	else 
	{
		return false;
	}
}


function checknumeric(obj)
{
	var str;
	var id=parseInt(obj.value);
	if(isNaN(id))
		return true;
	else
		return false;
}


function openUploadFiles()
{
	//alert("Coming Soon...!!!");
//	return false;
			obj = document.frm;	
			flgchk=obj.flg_local_main.value;	
			if(flgchk==0)
			{
			file_path=obj.cgi_path.value;
			}
			
			else{
			if (obj.purl.value=='www')
			{
				file_path=obj.cgi_path.value;
			}
			else	file_path=obj.cgi_path.value;
			}
			//alert(file_path);
			//file_path=obj.
			newwindow = window.open(file_path, 'Upload', 'resizable=no,scrollbars=yes,screenX=0,screenY=0,menubar=no,status=no,width=500,height=340,left=440,top=250,dependent');
			return ;
	
}

function openUploadFiles2(txtid)
{
	//alert("Coming Soon...!!!");
//	return false;
			obj = document.frm;	
			flgchk=obj.flg_local_main.value;	
			if(flgchk==0)
			{
			file_path=obj.cgi_path.value;
			}
			
			else{
			if (obj.purl.value=='www')
			{
				file_path=obj.cgi_path.value;
			}
			else	file_path=obj.cgi_path.value;
			}
			
			newwindow = window.open(file_path, 'Upload', 'resizable=no,scrollbars=yes,screenX=0,screenY=0,menubar=no,status=no,width=500,height=340,left=440,top=250,dependent');
			return ;
	
}


function openUploadFiles3()
{
	//alert("Coming Soon...!!!");
//	return false;
			obj = document.frm;	
			flgchk=obj.flg_local_main.value;	
			if(flgchk==0)
			{
			file_path=obj.cgi_path3.value;
			}
			
			else{
			if (obj.purl.value=='www')
			{
				file_path=obj.cgi_path3.value;
			}
			else	file_path=obj.cgi_path3.value;
			}
			//alert(file_path);
			
			//file_path=obj.
			newwindow = window.open(file_path, 'Upload', 'resizable=no,scrollbars=yes,screenX=0,screenY=0,menubar=no,status=no,width=500,height=340,left=440,top=250,dependent');
			return ;
	
}


//URL Validation
function isValidateURL(obj,msg)
{				
	var urlRegxp =   /^(((ht|f)tp(s?))\:\/\/)?(www.|[a-zA-Z].)[a-zA-Z0-9\-\.]+\.(com|edu|gov|mil|net|org|biz|info|name|museum|us|ca|uk|[a-zA-Z]{2,7})(\:[0-9]+)*(\/($|[a-zA-Z0-9\.\,\;\?\'\\\+&amp;%\$#\=~_\-]+))*$/; 
	
	var strurl= trim(obj.value);
	if (urlRegxp.test(strurl) != true)
	 {
	     alert('Invalid URL');
	     return false;
	 }
	 else
	 	return true;
}
//check special character
function IsValidUsername(sText)
{
   var ValidChars="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_"
   var charflag=true;
   var Char; 
   for (i = 0; i < sText.value.length; i++) 
   { 
      Char = sText.value.charAt(i); 
      if (ValidChars.indexOf(Char) == -1) 
              charflag = false;
   }
   return charflag;
}

function isValidDateDiff(smalldate,bigdate)
{
  var smalldatearr =smalldate.split("-");
  var bigdatearr   =bigdate.split("-");  
      
  if((parseInt(bigdatearr[2])) > (parseInt(smalldatearr[2],10)))
     return true;
  else if((parseInt(bigdatearr[2],10)) == (parseInt(smalldatearr[2],10)))
  {
  	if((parseInt(bigdatearr[0],10)) > (parseInt(smalldatearr[0],10)))
  	 	  return true;
  	else if((parseInt(bigdatearr[0],10)) == (parseInt(smalldatearr[0],10)))
  	{	
       if((parseInt(bigdatearr[1],10)) >= (parseInt(smalldatearr[1],10)))    
     				return true;
    		else 
    			  return false;   
     }
     else
     	 return false;
  }  
  else
  		return false;
}

function IsDateGreater(newdt)
{
	var datearr =newdt.split("-");
	thedate = new Date();
		y=parseInt(datearr[2]);
		m=parseInt(datearr[0]);
		d=parseInt(datearr[1]);
		thedate.setFullYear(y,m-1,d);
		today=new Date();
		if(thedate > today)
			return false;
		else
			return true;	
}

function IsDateLess(newdt)
{
	var datearr =newdt.split("-");
	thedate = new Date();
		y=parseInt(datearr[2]);
		m=parseInt(datearr[0]);
		d=parseInt(datearr[1]);
		thedate.setFullYear(y,m-1,d);
		today=new Date();
		if(thedate < today)
			return false;
		else
			return true;	

}

function extractNumber(obj, decimalPlaces, allowNegative)
{
	var temp = obj.value;
	
	// avoid changing things if already formatted correctly
	var reg0Str = '[0-9]*';
	if (decimalPlaces > 0) {
		reg0Str += '\\.?[0-9]{0,' + decimalPlaces + '}';
	} else if (decimalPlaces < 0) {
		reg0Str += '\\.?[0-9]*';
	}
	reg0Str = allowNegative ? '^-?' + reg0Str : '^' + reg0Str;
	reg0Str = reg0Str + '$';
	var reg0 = new RegExp(reg0Str);
	if (reg0.test(temp)) return true;

	// first replace all non numbers
	var reg1Str = '[^0-9' + (decimalPlaces != 0 ? '.' : '') + (allowNegative ? '-' : '') + ']';
	var reg1 = new RegExp(reg1Str, 'g');
	temp = temp.replace(reg1, '');

	if (allowNegative) {
		// replace extra negative
		var hasNegative = temp.length > 0 && temp.charAt(0) == '-';
		var reg2 = /-/g;
		temp = temp.replace(reg2, '');
		if (hasNegative) temp = '-' + temp;
	}
	
	if (decimalPlaces != 0) {
		var reg3 = /\./g;
		var reg3Array = reg3.exec(temp);
		if (reg3Array != null) {
			// keep only first occurrence of .
			//  and the number of places specified by decimalPlaces or the entire string if decimalPlaces < 0
			var reg3Right = temp.substring(reg3Array.index + reg3Array[0].length);
			reg3Right = reg3Right.replace(reg3, '');
			reg3Right = decimalPlaces > 0 ? reg3Right.substring(0, decimalPlaces) : reg3Right;
			temp = temp.substring(0,reg3Array.index) + '.' + reg3Right;
		}
	}
	
	obj.value = temp;
}
function blockNonNumbers(obj, e, allowDecimal, allowNegative)
{
	var key;
	var isCtrl = false;
	var keychar;
	var reg;
		
	if(window.event) {
		key = e.keyCode;
		isCtrl = window.event.ctrlKey
	}
	else if(e.which) {
		key = e.which;
		isCtrl = e.ctrlKey;
	}
	
	if (isNaN(key)) return true;
	
	keychar = String.fromCharCode(key);
	
	// check for backspace or delete, or if Ctrl was pressed
	if (key == 8 || isCtrl)
	{
		return true;
	}

	reg = /\d/;
	var isFirstN = allowNegative ? keychar == '-' && obj.value.indexOf('-') == -1 : false;
	var isFirstD = allowDecimal ? keychar == '.' && obj.value.indexOf('.') == -1 : false;
	
	return isFirstN || isFirstD || reg.test(keychar);
}

// ajax function by narendra
function showUser(str)
			{ 
				alert("hi ajax");
			xmlHttp=GetXmlHttpObject()
			if (xmlHttp==null)
				 {
				 alert ("Browser does not support HTTP Request")
				 return
				 } 
			var url="includes/swatch_swap.php"
			url=url+"?q="+str
			alert(url);
			xmlHttp.onreadystatechange=stateChanged 
			xmlHttp.open("GET",url,true)
			xmlHttp.send(null)
			}

		function stateChanged() 
				{ 
				if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
					 { 
					 document.getElementById("txtHint").innerHTML=xmlHttp.responseText 
					  checkafter();
					} 
					//else
					//{
						//alert("no respond");
					//}
				
				}

		function GetXmlHttpObject()
					{
					var xmlHttp=null;
					try
									 {
									 // Firefox, Opera 8.0+, Safari
									 xmlHttp=new XMLHttpRequest();
									 }
					catch (e)
									 {
									 //Internet Explorer
									 try
									  {
									  xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
									  }
									 catch (e)
									  {
									  xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
									  }
									 }
					return xmlHttp;
					}
