
// ********************************************** CHECK AND BUILD COOKIE
function testAndBuild(theString) {
	var exp = new Date();
	var oneYear = exp.getTime() + (1 * 24 *60 * 60 * 1000);
	exp.setTime(oneYear);
	
	theString = theString.replace("||", "|");
	aCheck = theString.charAt(0);
	if (aCheck == "|"){
		theString = theString.substr(1);
	}
	SetCookie(theCookieName, theString , exp, "/");
}

// ********************************************************* CALL ADD TO BASKET and GO TO CHECKOUT

function delPic(theVal) {
	theAr = GetCookie(theCookieName);
	picArray = theAr.split("|");
	delete picArray[theVal];
	newCookie = picArray.join("|");
	testAndBuild(newCookie);
	document.orderForm.method = "GET";
	document.orderForm.action = theCheckoutPage;
}

// ********************************************** GET COOKIE VALUE
function GetCookie(name) {
  var arg = name + "=";
  var alen = arg.length;
  var clen = document.cookie.length;
  var i = 0;
  while (i < clen) {
    var j = i + alen;
    if (document.cookie.substring(i, j) == arg)
      return getCookieVal (j);
    i = document.cookie.indexOf(" ", i) + 1;
    if (i == 0) break; 
  }
  return null;
}

function getCookieVal (offset) {
  var endstr = document.cookie.indexOf (";", offset);
  if (endstr == -1)
    endstr = document.cookie.length;
  return unescape(document.cookie.substring(offset, endstr));
}

// ********************************************************* GO TO BASKET
function goToCheckout(){
	theTotalItems = GetCookie(theCookieName);
	if (theTotalItems ==null) {
		alert("Cannot checkout. Basket is empty.");
	} else {
		document.orderForm.action = theCheckoutPage;
	}
}

// ********************************************************* BUTTON RETURN
function showValue(){
	theCurrent = GetCookie(theCookieName);
	alert("cookie: " + theCurrent);
}

// ********************************************************* CLEAR BASKET
function clearBasket(){
	if (confirm("Are you sure you want to empty the basket?")) {
		var exp = new Date();
		var oneYear = exp.getTime() - (365 * 24 *60 * 60 * 1000);
		exp.setTime(oneYear);
		SetCookie(theCookieName, "" , exp, "/");
		document.orderForm.method = "GET";
		document.orderForm.action = '/index.php';
	} else {
		document.orderForm.method = "GET";
		document.orderForm.action = theCheckoutPage;
	}	
}

function logOut(){
	if (confirm("Are you sure you want to logout?")) {
		var exp = new Date();
		var oneYear = exp.getTime() - (365 * 24 *60 * 60 * 1000);
		exp.setTime(oneYear);
		SetCookie("skinLogin", "" , exp, "/");
		SetCookie("loginName", "" , exp, "/");
		location.href = '/logout.php';
	} else {
	}	
}

// ********************************************************* ADD TO BASKET

function SetCookie (name,value,expires,path,domain,secure) {
  document.cookie = name + "=" + escape (value) +
    ((expires) ? "; expires=" + expires.toGMTString() : "") +
    ((path) ? "; path=" + path : "") +
    ((domain) ? "; domain=" + domain : "") +
    ((secure) ? "; secure" : "");
}

function cycleForm(bNumber){ // Cycle through all items in the form. Submit to cookie subroutine
	anItem = 0; // Begin with nothing being added. Something needs to be over 0 to change this.
	theList = document.orderForm.theList.value;
	listArray = theList.split("|");
	for (j=0; j<listArray.length-1; j++){
		addToOrder(listArray[j]);
	}
	if (anItem >0){
		document.orderForm.action = theCheckoutPage;
	} else {
		alert("No items were added to basket.\nPlease ensure quantity is \"1\" or more on at least on item.");
	}
}

function updateBasket(bNumber){ // Update the items (cycle through all of them on the checkOut page)
	anItem = 0; // Begin with nothing being added. Something needs to be over 0 to change this.
	theList = document.orderForm.theList.value;
	listArray = theList.split("|");
	for (j=0; j<listArray.length-1; j++){
		updateOrder(listArray[j]);
	}
	if (anItem >0){
		document.orderForm.method = "GET";
		document.orderForm.action = theCheckoutPage;
	} else {
		alert("No items were adjusted.");
		document.orderForm.method = "GET";
		document.orderForm.action = theCheckoutPage;
	}
}

// ********************************************************* CALL ADD TO BASKET
function addToOrder(bNumber) {
	numSelected = eval("document.orderForm." + bNumber + ".value"); // field # must be legit
	numSelected = parseInt(numSelected); // turn to an integer.
	if (numSelected >0 && numSelected <9999){ // if it is good, we go! (FIRST LOOP)
		anItem = 1; // Make a mark to let the loop know something was actually over 0!
		theOrder = bNumber + "*" + numSelected; // this is what we might add (e.g  b_1*3)
		theCurrent = GetCookie(theCookieName); // let us see if this cookie even exists.
		if (theCurrent != null ){// Already are bands, so ADD (SECOND LOOP)
			theCurrentArray = theCurrent.split("|"); // Split up the cookie
			task = 0;
			for (i=0; i<theCurrentArray.length; i++){ // Cycle through that cookie pieces
				theItem = theCurrentArray[i]; 
				theUnits = theItem.split("*"); // Even further, we split the piece up
				theBand = theUnits[0]; // Here is the BAND number already stored
				theNumber = theUnits[1]; // Here is the NUMBER of those bands.
				// With that in mind, we check if a LIKE band has been added.
				// If so, we ADD the new number to the old number.
				if (bNumber == theBand){ // A match? Let us add the numbers.
					theNumber = parseFloat(theNumber) + parseFloat(numSelected);
					theCurrentArray[i] = bNumber + "*" + theNumber;
					task = 1;
				}
			}
			if (task == 1) {
				theCurrent = theCurrentArray.join("|");
				theCookie = theCurrent;
			} else {
				theCookie = theCurrent + "|" + theOrder;
			}
			testAndBuild(theCookie);
		} else { // (fork SECOND) SET a NEW cookie!
			testAndBuild(theOrder);
		} // (END SECOND LOOP) whether bands were already set.
	} // (END FIRST LOOP) had to have been legit; otherwise nothing is done.
}

// ********************************************************* CALL ADD TO BASKET
function updateOrder(bNumber) {
	numSelected = eval("document.orderForm." + bNumber + ".value"); // field # must be legit
	numSelected = parseInt(numSelected); // turn to an integer.
	if (numSelected >0 && numSelected <9999){ // if it is good, we go! (FIRST LOOP)
		anItem = 1;
		var exp = new Date(); // todays date
		var oneYear = exp.getTime() + (1 * 24 *60 * 60 * 1000); // cookie expires in...
		exp.setTime(oneYear); // a time has been set!
		theOrder = bNumber + "*" + numSelected; // this is what we might add (e.g  b_1*3)
		theCurrent = GetCookie(theCookieName); // let us see if this cookie even exists.
		if (theCurrent != null ){// Already are bands, so ADD (SECOND LOOP)
			theCurrentArray = theCurrent.split("|"); // Split up the cookie
			task = 0;
			for (i=0; i<theCurrentArray.length; i++){ // Cycle through that cookie pieces
				theItem = theCurrentArray[i]; 
				theUnits = theItem.split("*"); // Even further, we split the piece up
				theBand = theUnits[0]; // Here is the BAND number already stored
				theNumber = theUnits[1]; // Here is the NUMBER of those bands.
				// With that in mind, we check if a LIKE band has been added.
				// If so, we ADD the new number to the old number.
				if (bNumber == theBand){ // A match? Let us add the numbers.
					theNumber = parseFloat(numSelected);
					theCurrentArray[i] = bNumber + "*" + theNumber;
					task = 1;
				}
			}
			if (task == 1) {
				theCurrent = theCurrentArray.join("|");
				theCookie = theCurrent;
			} else {
				theCookie = theCurrent + "|" + theOrder;
			}
			SetCookie(theCookieName, theCookie , exp, "/");
		} else { // (fork SECOND) SET a NEW cookie!
			SetCookie(theCookieName, theOrder , exp, "/");
		} // (END SECOND LOOP) whether bands were already set.
	}// (END FIRST LOOP) had to have been legit; otherwise nothing is done.
}

// ********************************************************* END ORDER
function MM_callJS(jsStr) { //v2.0
  return eval(jsStr)
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_findObj(n, d) { //v3.0
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}


function testCreditCard () {
  myCardNo = document.form1.ccNumber.value;
  myCardType = document.form1.ccType.value;
  if (checkCreditCard (myCardNo,myCardType)) {
		return "valid";
	} 
	else {
		return ccErrors[ccErrorNo];
		//alert (ccErrors[ccErrorNo])
	};
}

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

/*


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
    http://www.blackmarket-press.net/info/plastic/check_digit.htm 
where the details of other cards may also be found.

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

Author:     John Gardner
Date:       1st November 2003

*/

/*
   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);
*/

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) {

     
  // 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: "AmEx", 
               length: "15", 
               prefixes: "34,37",
               checkdigit: true};
			   
  cards [3] = {name: "Discover",
  				length: "16",
				prefixes: "6011", 
				checkdigit: true};
               
  // Establish card type
  var cardType = -1;
  for (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; 
  }
  
  // Check that the number is numeric, although we do permit a space to occur  
  // every four digits. 
  var cardNo = cardnumber
  var cardexp = /^([0-9]{4})\s?([0-9]{4})\s?([0-9]{4})\s?([0-9]{1,4})$/;
  if (!cardexp.exec(cardNo))  {
     ccErrorNo = 2;
     return false; 
  }
    
  // Now remove any spaces from the credit card number
  cardexp.exec(cardNo);
  cardNo = RegExp.$1 + RegExp.$2 + RegExp.$3 + RegExp.$4;
       
  // 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
    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;
}