// Global.js - Replaces FormChek.js
//
// Credit card validation provided by Eric Krock (c) 1997 Netscape Communications Corporation
//
// (c) 2000 Management Systems Modelling

// VARIABLE DECLARATIONS

var whitespace = " \t\n\r";

function isCreditCard(sCCnum) {
  	
    var iTotal = 0;
    var iNumLen = sCCnum.length;
    var lastno = 0;
    var double = 1;
   
	if (iNumLen >= 13 && iNumLen <= 19){    
    	for (x = (iNumLen-1); x > 0; x--){
      		intValue = sCCnum.substr(x-1,1)
      		if (double == 1){
        		intValue = intValue * 2;
        		if (intValue > 9){
          			intValue = intValue - 9;
        		}
        		double = 0;
      		}else{
        		double = 1;
      		}
      		//alert(intValue);
      		iTotal = iTotal + parseInt(intValue);
    	}

		iTotal = iTotal + parseInt(sCCnum.substr(iNumLen-1,1))
	    if(iTotal % 10 == 0){
	        return true
	    }else{
	    	return false
	    }
    }else{
		return false;
	}
}

function isVisa(cc)
{
  if (((cc.length == 16) || (cc.length == 13)) &&
      (cc.substring(0,1) == 4))
    return isCreditCard(cc);
  return false;
}

function isMasterCard(cc)
{
  firstdig = cc.substring(0,1);
  seconddig = cc.substring(1,2);
  if ((cc.length == 16) && (firstdig == 5) &&
      ((seconddig >= 1) && (seconddig <= 5)))
    return isCreditCard(cc);
  return false;
}

function isAmericanExpress(cc)
{
  firstdig = cc.substring(0,1);
  seconddig = cc.substring(1,2);
  if ((cc.length == 15) && (firstdig == 3) &&
      ((seconddig == 4) || (seconddig == 7)))
    return isCreditCard(cc);
  return false;
}

function isDinersClub(cc)
{
  firstdig = cc.substring(0,1);
  seconddig = cc.substring(1,2);
  if ((cc.length == 14) && (firstdig == 3) &&
      ((seconddig == 0) || (seconddig == 6) || (seconddig == 8)))
    return isCreditCard(cc);
  return false;
}

function isCarteBlanche(cc)
{
  return isDinersClub(cc);
}

function isAnyCard(cc)
{
  if (!isCreditCard(cc))
    return false;
  if (!isMasterCard(cc) && !isVisa(cc) && !isAmericanExpress(cc) && !isDinersClub(cc)) {
    return false;
  }
  return true;
}

function isCardMatch(cardType, cardNumber)
{

	//cardType = cardType.toUpperCase();
	var doesMatch = true;

	//check the number
	if(!isCreditCard(cardNumber)){
		doesMatch = false;
	}

	if ((cardType == "VI") && (!isVisa(cardNumber)))
		doesMatch = false;
	if ((cardType == "MA") && (!isMasterCard(cardNumber)))
		doesMatch = false;
	if ( ( (cardType == "AX") || (cardType == "AMEX") )
                && (!isAmericanExpress(cardNumber))) doesMatch = false;
	if ((cardType == "DN") && (!isDinersClub(cardNumber)))
		doesMatch = false;
	if ((cardType == "CB") && (!isCarteBlanche(cardNumber)))
		doesMatch = false;
	return doesMatch;
}

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 stripCharsNotInBag(s, bag)
{   var i;
    var returnString = "";

    // Search through string's characters one by one.
    // If character is 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 stripWhitespace(s)
{   return stripCharsInBag(s, whitespace);
}

function RemoveBad(InStr){
	InStr = InStr.replace(/\</g,"");
	InStr = InStr.replace(/\>/g,"");
	InStr = InStr.replace(/\"/g,"");
	InStr = InStr.replace(/\'/g,"");
	InStr = InStr.replace(/\%/g,"");
	InStr = InStr.replace(/\;/g,"");
	InStr = InStr.replace(/\(/g,"");
	InStr = InStr.replace(/\)/g,"");
	InStr = InStr.replace(/\&/g,"");
	InStr = InStr.replace(/\+/g,"");
	return InStr;
}
function cleanInput(input) {
	var s = input.value;
	input.value = RemoveBad(s);
	return true;
}
	
function OldFormatCurrency(f) {
	s = f.value;
	o = s;
	p = s.search(/[.]/);
	switch (p) {
		case -1: 
			s += '.00'; 
			break;
		case 0: 
			s = '0.' + o; 
			break;
		default: 
			sa = s.split('.'); 
			if (sa[1].length < 2) { 
				s += '0'; 
			} 
			break;
	}
	f.value = s;
}

function FormatCurrency(f) {
	num = f.value;
	num = num.toString().replace(/\$|\,/g,'');
	if (isNaN(num)) num = "0";
	f.value = FormatCurrencyAsString(num);
}

function FormatCurrencyAsString(c) {
	pence = Math.floor((c*100+0.5)%100);
	num = Math.floor((c*100+0.5)/100).toString();
	if (pence < 10) pence = "0" + pence;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
		num = num.substring(0, num.length-(4*i+3)) + ',' + num.substring(num.length-(4*i+3));

	return num + '.' + pence;
}

function FormatSterling(c) {
	return "£" + FormatCurrencyAsString(c);
}

function DisplayCurrency(n, c) {
	var f = document.all[n];
	var type = browserType();
	if (type != 1) {
		f.value = FormatCurrencyAsString(c);
	} else {
		f.innerHTML = FormatSterling(c); 
	}
}

function isBlank(s) {
	var c;
	for(var i = 0; i < s.length; i++) {
		c = s.charAt(i);
		if ((c != ' ') && (c != '\n') && (c != '\t')) return false;
	}
	return true;
}

function MM_swapImgRestore() 
{
	if (document.MM_swapImgData != null)
		for (var i=0; i<(document.MM_swapImgData.length-1); i+=2)
			document.MM_swapImgData[i].src = document.MM_swapImgData[i+1];
}

function MM_swapImage() 
{
	var i,j=0,objStr,obj,swapArray=new Array,oldArray=document.MM_swapImgData;
	for (i=0; i < (MM_swapImage.arguments.length-2); i+=3) {
		objStr = MM_swapImage.arguments[(navigator.appName == 'Netscape')?i:i+1];
		if ((objStr.indexOf('document.layers[')==0 && document.layers==null) || (objStr.indexOf('document.all[')   ==0 && document.all   ==null)) {
			objStr = 'document'+objStr.substring(objStr.lastIndexOf('.'),objStr.length);
		}
		obj = eval(objStr);
		if (obj != null) {
			swapArray[j++] = obj;
			swapArray[j++] = (oldArray==null || oldArray[j-1]!=obj)?obj.src:oldArray[j];
			obj.src = MM_swapImage.arguments[i+2];
		}
	}
	document.MM_swapImgData = swapArray; //used for restore
}

function isOrphan(c) 
{
	if (c > 0 ) {
		s1 = ((c == 1) ? 'is' : 'are');
		s2 = ((c == 1) ? 'item' : 'items');
		alert('Unable to delete this record since there ' + s1 + ' ' + c + ' related ' + s2);
		return false;
	} else return true;
}

function formSubmit() {
	if (formValidate()) {
		document.mainForm.submit();
	}
}

function formValidate() {
	f = document.mainForm;
	for(var i = 0; ((i < f.length)); i++) {
		if (f.elements[i].onchange != null) {
			if (!f.elements[i].onchange()) {
				//alert(f.elements[i].name);
				return false;
			}
		}
	}
	return true;
}

function validateInteger(field, title, allownull) {
	value = document.getElementById(field).value;
	if (value.length < 1) {
		if (!allownull) {
			alert(title + ': This field will not accept a null value.');
			return false;
		}
		else return true;
	} else {
		valueint = parseInt(value);
		if (isNaN(valueint) || (valueint != value)) {
			alert(title + ': ' + value + ' is not an integer value.');
			return false;
		}
		else return true;
	}
}
	
function validateReal(field, title, allownull) {
	value = field.value;
	if (value.length < 1) {
		if (!allownull) {
			alert(title + ': This field will not accept a null value.');
			return false;
		}
		else return true;
	} else {
		valuereal = parseFloat(value);
		if (isNaN(valuereal) || (valuereal != value)) {
			alert(title + ': ' + value + ' is not an real value.');
			return false;
		}
		else return true;
	}
}

function isNull(s) 
{
	return (s.length <= 0);
}

function IsNumeric(strTxt)
{

   var ValidChars = "0123456789.";
   var IsNumber=true;
   var Char;

 
   for (i = 0; i < strTxt.length && IsNumber == true; i++) 
      { 
      Char = strTxt.charAt(i); 
      if (ValidChars.indexOf(Char) == -1) 
         {
         IsNumber = false;
         }
      }
   return IsNumber;
   

}

function validateChar(field, title, len, checklength, allownull) 
{
	v = field.value;
	if ((!allownull) && (isNull(v))) {
		alert(title + ': A value must be entered for this field');
		return false;
	}
	if ((checklength) && (v.length > len)) {
		alert(title + ': Entered length ' + v.length + ' exceeds maximum of ' + len);
		return false;
	}
	return true;
}

function validateDate(o, allownull) 
{
	return true;
}

function validateEmail(o, len, checklength, allownull) 
{
	v = o.value;
	if ((allownull) && (isNull(v))) return true;
	if ((checklength) && (v.length > len)) {
		alert(o.name + ': Entered length ' + v.length + ' exceeds maximum of ' + len);
		return false;
	}
	okay = v.indexOf('@') >= 0;
	if (okay) return true;
	else {
		alert(o.name + ': does not contain a valid Email address');
		return false;
	}
}

function validatePassword(field) {
	value = field.value;
	if (value.length < 6) {
		alert('Password must be at least 6 characters in length.');
		return false;
	}
	else return true;
}

function validateNumber(o, min, max, range, allownull) 
{
	return validateNumberRaw(o, min, max, range, allownull, o.name);
}

function validateNumberRaw(o, min, max, range, allownull, name) 
{
	v = o.value;
	if (isNull(v)) {
		if (!allownull) {
			alert(name + ': A value must be entered for this field');
			return false;
		}
	}
	vi = parseInt(v);
	if (isNaN(vi) || (vi != v)) {
		alert(name + ': ' + v + ' is not a whole number');
		return false;
	}
	if (range) {
		if (((vi < min) && (min > 0)) || (( vi > max) && (max > 0))) {
			msg = name + ' must be';
			if (min > 0) msg = msg + ' at least ' + min;
			if (max > 0) {
				if (min > 0) msg = msg + ' and ';
				msg = msg + ' not more than ' + max;
			}
			alert(msg);
			return false;
		}
	}
	if (vi != v) {
		alert(name + ': ' + v + ' is not a whole number');
		return false;
	}
	return true;
}

function spanChange(id, str) {
  if (browserType()!=1) {
    with (document[id].document) {
      open();
      write(str);
      close();
    }
  } else {
    document.all[id].innerHTML = str;
  }
}

function browserType() {
	if (navigator.userAgent.indexOf("Mozilla/3.0") != -1) return 3;
	if (navigator.userAgent.indexOf("MSIE") != -1) return 1;
	if (navigator.userAgent.indexOf("Mozilla/2.0") != -1) return 2;
    return 0;
}

function submitenter(myfield,e)
{
  var keycode;
  if (window.event) keycode = window.event.keyCode;
  else if (e) keycode = e.which;
  else return true;

  if (keycode == 13)
    {
    myfield.form.submit();
    return false;
    }
  else
    return true;
}

function uploadFormSubmit()
	{
	var c = 0;
	var d = 0;
	var f = document.uploadForm;
	for(var i = 0; i < f.length; i++) {
		var item = f.elements[i];
		var itemname = item.name;
		if (itemname.substring(0,8) == 'filename') {
			if (item.value==''){
				c++;
			}
			else{
				for(var i = 0; i < f.length; i++) {
					var item2 = f.elements[i];
					var itemname2 = item2.name;
					if (itemname2.substring(0,8) == 'filename') {
						if (item2.value==item.value){
							d++;
						}
					}
				
				}
			}
		}
	}
	if (c > 0) {
		alert('One or more input areas are blank');
		}
	else{
		if(d > 1){
			alert('Do NOT upload the same image more than once!');
		}
		else{document.uploadForm.submit();}
	}
}

// ************************************************************** //
// ***** New left hand catalogue navigational controls - IO ***** //
// ************************************************************** //

function menuControl(activeObj){

	var obj = document.getElementById(activeObj);
	var objstatus = obj.className;
	
	if(objstatus.length==0){ //open the selected list
		obj.className = 'current';
	}else{ //close the selected list
		obj.className = '';
	}
	
	//## close all siblings and their children
	//loop through the previous children in the list
	var previousSibs;
	previousSibs = obj.previousSibling;
	while(previousSibs) {
		//check that the child is an object and if the menu item is open
		if(previousSibs.nodeType==1&&previousSibs.className=='current'){
			previousSibs.className = ''; //close the item
			closeChildren(previousSibs); //close the children of the item
		}
		previousSibs = previousSibs.previousSibling;
	}
	
	//loop through all siblings that follow the selected element
	var nextSibs;
	nextSibs = obj.nextSibling;
	while(nextSibs) {
		//check that the child is an object and if the menu item is open
		if(nextSibs.nodeType==1&&nextSibs.className=='current'){
			nextSibs.className = ''; //close the item
			closeChildren(nextSibs); //close the children of the item
		}
		nextSibs = nextSibs.nextSibling;
	}
	
}

function closeChildren(nodeObj){
	//loop through children and close if open
	var i=0, x=0, nodesLen, listNodesLen, currentNode, currentChildNode;
	nodesLen = nodeObj.childNodes.length;
	for(i;i<nodesLen;i++){
		currentNode = nodeObj.childNodes[i];
		if(currentNode.nodeType==1&&currentNode.tagName=='UL'){
			listNodesLen = nodeObj.childNodes[i].childNodes.length;
			for(x;x<listNodesLen;x++){
				currentChildNode = nodeObj.childNodes[i].childNodes[x];
				if(currentChildNode.className=='current'){
					currentChildNode.className = ''; //close the item
					closeChildren(currentChildNode); //close children
				}
			}
		}
	}
}

function openParents(activeGroup){
	var activeObj, nextParent;
	activeObj = document.getElementById(activeGroup);
	if(activeObj){
		nextParent = activeObj.parentNode;
		while(nextParent){
			if(nextParent.tagName=='LI'){
				nextParent.className = 'current';
			}
			nextParent = nextParent.parentNode;
		}
	}
}

// ************************************************************** //
// ***** END of catalogue navigational controls ***************** //
// ************************************************************** //

// ************************************************************** //
// ***** Basket summary controls - IO *************************** //
// ************************************************************** //

function bsksumAlterQty(jsproduct, jsnewqty, jsincvat){
    //if new quantity is less than 0 or blank then make it equal 0
    if(jsnewqty < 0 || jsnewqty == ""){
        jsnewqty = 0;
    }

    var jsproductqtyobj = document.getElementById('qty_'+jsproduct);
    //set the quantity in the qty input field
    jsproductqtyobj.value = jsnewqty;

    //need to alter the line price to reflect the quantity change
    //calculate the value
    var unitprice;
    if(jsincvat == 0){
        unitprice = document.getElementById('unit_price_'+jsproduct).value;
    }else{
        unitprice = document.getElementById('unit_priceincvat_'+jsproduct).value;
    }
    var lineprice = roundnumber(jsnewqty * unitprice);    
    if(jsincvat == 0){
        document.getElementById('line_price_'+jsproduct).value = lineprice;
    }else{
        document.getElementById('line_priceincvat_'+jsproduct).value = lineprice;
    }
    
    document.getElementById('display_price_'+jsproduct).innerHTML = lineprice;

    //bsksumtotal
    var doc = document.getElementsByTagName('input');
    var jsbsksumtotal = 0;
    for (var i = 0; i < doc.length; i++){
        if (doc[i].id!=undefined){
            var jsid = doc[i].id;
            //if the id matches a line price input total it up
            if(jsincvat == 0){
                if(jsid.substr(0, 11) == "line_price_"){
                    jsbsksumtotal = parseFloat(jsbsksumtotal) + parseFloat(doc[i].value);
                }
            }else{
                if(jsid.substr(0, 16) == "line_priceincvat"){
                    jsbsksumtotal = parseFloat(jsbsksumtotal) + parseFloat(doc[i].value);
                }
            }
        }
    }

    document.getElementById('bsksumtotal').innerHTML = roundnumber(jsbsksumtotal);
    document.getElementById('bsksumtotalsum').innerHTML = roundnumber(jsbsksumtotal);

}

function roundnumber(roundthis) {
	var rnum = roundthis;
	var rlength = 2; // The number of decimal places to round to
	if (rnum > 8191 && rnum < 10485) {
		rnum = rnum-5000;
		var newnumber = Math.round(rnum*Math.pow(10,rlength))/Math.pow(10,rlength);
		//newnumber = newnumber+5000;
	} else {
		var newnumber = Math.round(rnum*Math.pow(10,rlength))/Math.pow(10,rlength);
	}
	//need to add a trailing zero if necessary
	var newnumberstr
	newnumberstr = newnumber.toString();
	if(newnumberstr.indexOf(".") > 0){
		numsplit = newnumberstr.split(".");
		if (numsplit[1].length < 2){
			newnumber = newnumber + "0";
		}
	}
	return newnumber;
}    

function basketsummarycontrol(jsdisplay){
    if(jsdisplay=='detail'){
        document.getElementById("basket").style.display = 'block';
        document.getElementById("basketsummary").style.display = 'none';
    }else{
        document.getElementById("basketsummary").style.display = 'block';    
        document.getElementById("basket").style.display = 'none';
    }
}

// ************************************************************** //
// ***** End of basket summary controls - IO ******************** //
// ************************************************************** //

// ************************************************************** //
// ***** AJAX controls - IO ************************************* //
// ************************************************************** //

// ************** Main Request Function ************************* //
function xmlhttprequest(xhType, xhSubmitTo, xhValues, xhReturnFunction){	
    
  var returnfunction;
  var xreturnfunction;

  //## code for Mozilla, etc.
  if (window.XMLHttpRequest){
    xmlhttp=new XMLHttpRequest()
  }
  //## code for IE
  else if (window.ActiveXObject){
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")
  }

  returnfunction = xhReturnFunction;
  xreturnfunction = eval(returnfunction)

  if(xmlhttp){
    xmlhttp.onreadystatechange=xreturnfunction;
    xmlhttp.open(xhType,xhSubmitTo,true);
    xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xmlhttp.send(xhValues);
  }else{
    alert('Your browser doesnt support XMLHTTP');
  }
}
		
function xmlhttpchange(){
  //## if xmlhttp shows "loaded"
  if (xmlhttp.readyState==4){
    //## if "OK"
    if (xmlhttp.status==200){
    	//## this is where the funky stuff happens
    	jsresponsetext = xmlhttp.responseText;
			//## need to check for any returned javascript, strip it out and execute it. 
			//## script passed back should always be at the end of the returned text in this case
			scriptyes = jsresponsetext.indexOf("<script>")
			
			if(scriptyes > 0){
			  //## search for jscript as searching for normal script tags fails??
			  splitresponse = jsresponsetext.split("<jscript>");
			  removeendscript = splitresponse[1].split("</jscript>");
			  jsreturned = removeendscript[0];
			  txtreturned = splitresponse[0];
			}
			else{
			  txtreturned = jsresponsetext;
			}
			//## write the returned text to the page
			//document.write(txtreturned);
		
			if(scriptyes > 0){
			  //## execute the returned javascript
			  eval(jsreturned);
			}
    }
    else{
      //## need a way to handle errors correctly.  Perhaps log to a table in the DB??
      alert(xmlhttp.responseText);
    }   
  }
}

// Search box validation
function SimpleSearchValidate(frm) {

	var c = 0;
	if (isBlank(document.SearchForm.SrchTxt.value)) {
		alert('Please enter at least one word or phrase on which to search');
		return false;
	} 
	else
	{
	 		document.SearchForm.submit();
	}

	return true;
}

//*** adds the listener
function addListener(obj, event, handler) {
      // function that allows you to add multiple event listeners in all browsers
      if (obj.addEventListener) {
            obj.addEventListener(event, handler, false);
            } else if (obj.attachEvent) {
                  obj.attachEvent('on' + event, handler);
            } else {
                  window.status = 'Please upgrade your browser to a more recent version.';
      }
}

