//General site scripts
//setup definative root




//Function to 'trim' whitespace from strings.
String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
	return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
	return this.replace(/\s+$/,"");
}



//Email Validation Class
function EmailCheck(email){
  this.email=email.toLowerCase();
  }

    function getEmail(){
      return this.email;
      }

    function validate(){
      var pattern=/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/;
        if(pattern.test(this.email)){
        return true;
        }
        else{
        return false;
        }
    } 

  
    EmailCheck.prototype.getEmail=getEmail;
    EmailCheck.prototype.validate=validate;
    
//End Email Validation Class


//AJAX Class
function Ajax(){
  this.handle=false;
  //Check for IE
  try{
    this.handle=new ActiveXObject("Msxml2.XMLHTTP");
    this.browser="IE7";
  }
  catch(e){
    try{
      this.handle=new ActiveXObject("Microsoft.XMLHTTP");
      this.browser="IE6";
      }
      catch(e){
        this.handle=false;
        }
      }
  if(!this.handle && typeof XMLHttpRequest!="undefined"){
    this.handle=new XMLHttpRequest();
    this.browser="Mozilla";
  }
}

//End AJAX CLASS




//Preload Images
function loadImages(){

//Define variables
var i;
var jpgs=new Array();
var gifs=new Array();
var pngs=new Array();


  if(document.images){
    var jpegs=new Array("navAbout","navContact","navGlossary","navLocator","navMedia","navProducts","navPros","navSearch","navStore","butCont","butBack","butSignIn2");
    var gfs=new Array("butCheckout","butEmail","butFavorites","butMyProfile","butProfile","butRegister","butShoppingBag","butSignIn","butSignOut","butSearch");
    var png=new Array("butAddBag","butCancel","butChargeAcc","offerUpdate","offerRemove","offerAddBag","cartUpdate","cartRemove","cartEditOffer","butUpdate","buttonEditBag","butSubscribe","butSecureCheckout","butPayCredit","butOfferCode","butMoreInfo","butFavorite","butContinue","butCont","butCheckout","butChargeAcc");
    
    
    //JPEGS
    if(jpegs.length){
      for(i=0;i<jpegs.length;i++){
        jpgs[i]=new Image();
        jpgs[i].src=defRoot+"images/"+jpegs[i]+"_over.jpg";
      }
    }
    
    //GIFS
    if(gfs.length){
      for(i=0;i<gfs.length;i++){
        gifs[i]=new Image();
        gifs[i].src=defRoot+"images/"+gfs[i]+"_over.gif";
      }
    }
    
    //PNGS
    if(png.length){
      for(i=0;i<png.length;i++){
        pngs[i]=new Image();
        pngs[i].src=defRoot+"images/"+png[i]+"_over.png";
      }
    }
    
  }
}
  
  
  
function rollOn(id,ext){
  //handles rollover for buttons
  var extn;
  if(ext=="j"){
    extn=".jpg";
  }
  if(ext=="g"){
    extn=".gif";
  }
  if(ext=="p"){
    extn=".png";
  }
  
  document.getElementById(id).src=defRoot+"images/"+id+"_over"+extn;
    
  }

function rollOff(id,ext){
  //handles rollover for buttons
  var extn;
  if(ext=="j"){
    extn=".jpg";
  }
  if(ext=="g"){
    extn=".gif";
  }
  if(ext=="p"){
    extn=".png";
  }
  
  document.getElementById(id).src=defRoot+"images/"+id+extn;
    
  }
  
function URLEncode(url) //Function to encode URL.
{
// The Javascript escape and unescape functions do not correspond
// with what browsers actually do...
var SAFECHARS = "0123456789" + // Numeric
"ABCDEFGHIJKLMNOPQRSTUVWXYZ" + // Alphabetic
"abcdefghijklmnopqrstuvwxyz" +
"-_.!~*'()"; // RFC2396 Mark characters
var HEX = "0123456789ABCDEF";

var plaintext = url;
var encoded = "";
for (var i = 0; i < plaintext.length; i++ ) {
var ch = plaintext.charAt(i);
if (ch == " ") {
encoded += "+"; // x-www-urlencoded, rather than %20
} else if (SAFECHARS.indexOf(ch) != -1) {
encoded += ch;
} else {
var charCode = ch.charCodeAt(0);
if (charCode > 255) {
alert( "Unicode Character '"
+ ch
+ "' cannot be encoded using standard URL encoding.\n" +
"(URL encoding only supports 8-bit characters.)\n" +
"A space (+) will be substituted." );
encoded += "+";
} else {
encoded += "%";
encoded += HEX.charAt((charCode >> 4) & 0xF);
encoded += HEX.charAt(charCode & 0xF);
}
}
}

return encoded;
};


 

function URLDecode(url) //function decode URL
{
// Replace + with ' '
// Replace %xx with equivalent character
// Put [ERROR] in output if %xx is invalid.
var HEXCHARS = "0123456789ABCDEFabcdef";
var encoded = url;
var plaintext = "";
var i = 0;
while (i < encoded.length) {
var ch = encoded.charAt(i);
if (ch == "+") {
plaintext += " ";
i++;
} else if (ch == "%") {
if (i < (encoded.length-2)
&& HEXCHARS.indexOf(encoded.charAt(i+1)) != -1
&& HEXCHARS.indexOf(encoded.charAt(i+2)) != -1 ) {
plaintext += unescape( encoded.substr(i,3) );
i += 3;
} else {
alert( 'Bad escape combination near ...' + encoded.substr(i) );
plaintext += "%[ERROR]";
i++;
}
} else {
plaintext += ch;
i++;
}
} // while

return plaintext;
}; 
    
    
    
//Function to set, read and delete cookies
function createCookie(name,value,days){
	if (days) {
		var date=new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires="; expires="+date.toGMTString();
	}
	else{
    var expires="";
	  document.cookie=name+"="+value+expires+"; path=/";
	  }
}

function readCookie(name){
	var nameEQ=name+"=";
	var ca=document.cookie.split(';');
	for(var i=0;i<ca.length;i++){
		var c=ca[i];
		while (c.charAt(0)==' '){
      c=c.substring(1,c.length);
    }
		  if(c.indexOf(nameEQ)==0){
       return c.substring(nameEQ.length,c.length);
      }
	}
	return null;
}


function eraseCookie(name){
	createCookie(name,"",-1);
}



//-----------------------------------CREDIT CARD VALIDATION-------------------------------------------------

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";

function checkCreditCard (cardnumber, cardname) {
  
  cardnumber = cardnumber.replace(/[^0-9]/g, '');
  // 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: "36,54,55",
               checkdigit: true};
  cards [3] = {name: "CarteBlanche", 
               length: "14", 
               prefixes: "300,301,302,303,304,305",
               checkdigit: true};
  cards [4] = {name: "AmEx", 
               length: "15", 
               prefixes: "34,37",
               checkdigit: true};
  cards [5] = {name: "Discover", 
               length: "16", 
               prefixes: "6011,622,64,65",
               checkdigit: true};
  cards [6] = {name: "JCB", 
               length: "16", 
               prefixes: "35",
               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: "12,13,14,15,16,18,19", 
               prefixes: "5018,5020,5038,6304,6759,6761",
               checkdigit: true};
  cards [11] = {name: "VisaElectron", 
               length: "16", 
               prefixes: "417500,4917,4913,4508,4844",
               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;
}

//-----------------------------------END CREDIT CARD VALIDATION-------------------------------------------------



//credit card tester
function testCreditCard () {
  myCardNo = document.getElementById('cardNumber').value;
  myCardType = document.getElementById('cardType').value;
      
  if (checkCreditCard (myCardNo,myCardType)) {
    //alert ("Credit card has a valid format");
    //check expiration date and CV Code
    var eMonth=document.getElementById('expMonth').value;
    eMonth=eMonth.replace(/[^0-9]/g, '');    
    var eYear=document.getElementById('expYear').value;
    eYear=eYear.replace(/[^0-9]/g, '');
    var cv=document.getElementById('cardCvc').value;
    cv=cv.replace(/[^0-9]/g, '');
    
    if(!eMonth.length || !eYear.length){
      alert('Please enter your credit card expiration date');
      return false;
      }
    
    eMonth=parseInt(eMonth);
    eYear=parseInt(eYear);
          
    
    var now=new Date();
    
    //alert(now.getMonth()+" "+now.getFullYear());
    //alert(eMonth+" "+eYear);
    
    //check year
    if(eYear<now.getFullYear()){
      alert("Your credit card has expired");
      return false;
      }
    if(eMonth<(now.getMonth()+1) && eYear==now.getFullYear()){
        alert("Your credit card has expired ");
        //alert(eMonth+":"+(now.getMonth()+1));
        return false;
      }
    
    
    //alert(eMonth+" : "+eYear);
         
    //check cvv code
    if(!cv.length){
      alert("Please enter the (CVC) Card Security Code");
      return false;
    }
    
    if((cv.trim()).length<3){
      alert("Please ensure you have entered the (CVC) Card Security Code correctly");
      return false;
    }
      
    
    return true;
    
  } 
  else {alert (ccErrors[ccErrorNo])};
  return false;
}






































 
        
        
