// 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);
	while ((!activeObj)&&(activeGroup.length>0)){
		activeGroup	= activeGroup.substr(0, activeGroup.length -1);
		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.';
      }
}

var MONTH_NAMES=new Array('January','February','March','April','May','June','July','August','September','October','November','December','Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec');var DAY_NAMES=new Array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sun','Mon','Tue','Wed','Thu','Fri','Sat');
function LZ(x){return(x<0||x>9?"":"0")+x}
function isDate(val,format){var date=getDateFromFormat(val,format);if(date==0){return false;}return true;}
function compareDates(date1,dateformat1,date2,dateformat2){var d1=getDateFromFormat(date1,dateformat1);var d2=getDateFromFormat(date2,dateformat2);if(d1==0 || d2==0){return -1;}else if(d1 > d2){return 1;}return 0;}
function formatDate(date,format){format=format+"";var result="";var i_format=0;var c="";var token="";var y=date.getYear()+"";var M=date.getMonth()+1;var d=date.getDate();var E=date.getDay();var H=date.getHours();var m=date.getMinutes();var s=date.getSeconds();var yyyy,yy,MMM,MM,dd,hh,h,mm,ss,ampm,HH,H,KK,K,kk,k;var value=new Object();if(y.length < 4){y=""+(y-0+1900);}value["y"]=""+y;value["yyyy"]=y;value["yy"]=y.substring(2,4);value["M"]=M;value["MM"]=LZ(M);value["MMM"]=MONTH_NAMES[M-1];value["NNN"]=MONTH_NAMES[M+11];value["d"]=d;value["dd"]=LZ(d);value["E"]=DAY_NAMES[E+7];value["EE"]=DAY_NAMES[E];value["H"]=H;value["HH"]=LZ(H);if(H==0){value["h"]=12;}else if(H>12){value["h"]=H-12;}else{value["h"]=H;}value["hh"]=LZ(value["h"]);if(H>11){value["K"]=H-12;}else{value["K"]=H;}value["k"]=H+1;value["KK"]=LZ(value["K"]);value["kk"]=LZ(value["k"]);if(H > 11){value["a"]="PM";}else{value["a"]="AM";}value["m"]=m;value["mm"]=LZ(m);value["s"]=s;value["ss"]=LZ(s);while(i_format < format.length){c=format.charAt(i_format);token="";while((format.charAt(i_format)==c) &&(i_format < format.length)){token += format.charAt(i_format++);}if(value[token] != null){result=result + value[token];}else{result=result + token;}}return result;}
function _isInteger(val){var digits="1234567890";for(var i=0;i < val.length;i++){if(digits.indexOf(val.charAt(i))==-1){return false;}}return true;}
function _getInt(str,i,minlength,maxlength){for(var x=maxlength;x>=minlength;x--){var token=str.substring(i,i+x);if(token.length < minlength){return null;}if(_isInteger(token)){return token;}}return null;}
function getDateFromFormat(val,format){val=val+"";format=format+"";var i_val=0;var i_format=0;var c="";var token="";var token2="";var x,y;var now=new Date();var year=now.getYear();var month=now.getMonth()+1;var date=1;var hh=now.getHours();var mm=now.getMinutes();var ss=now.getSeconds();var ampm="";while(i_format < format.length){c=format.charAt(i_format);token="";while((format.charAt(i_format)==c) &&(i_format < format.length)){token += format.charAt(i_format++);}if(token=="yyyy" || token=="yy" || token=="y"){if(token=="yyyy"){x=4;y=4;}if(token=="yy"){x=2;y=2;}if(token=="y"){x=2;y=4;}year=_getInt(val,i_val,x,y);if(year==null){return 0;}i_val += year.length;if(year.length==2){if(year > 70){year=1900+(year-0);}else{year=2000+(year-0);}}}else if(token=="MMM"||token=="NNN"){month=0;for(var i=0;i<MONTH_NAMES.length;i++){var month_name=MONTH_NAMES[i];if(val.substring(i_val,i_val+month_name.length).toLowerCase()==month_name.toLowerCase()){if(token=="MMM"||(token=="NNN"&&i>11)){month=i+1;if(month>12){month -= 12;}i_val += month_name.length;break;}}}if((month < 1)||(month>12)){return 0;}}else if(token=="EE"||token=="E"){for(var i=0;i<DAY_NAMES.length;i++){var day_name=DAY_NAMES[i];if(val.substring(i_val,i_val+day_name.length).toLowerCase()==day_name.toLowerCase()){i_val += day_name.length;break;}}}else if(token=="MM"||token=="M"){month=_getInt(val,i_val,token.length,2);if(month==null||(month<1)||(month>12)){return 0;}i_val+=month.length;}else if(token=="dd"||token=="d"){date=_getInt(val,i_val,token.length,2);if(date==null||(date<1)||(date>31)){return 0;}i_val+=date.length;}else if(token=="hh"||token=="h"){hh=_getInt(val,i_val,token.length,2);if(hh==null||(hh<1)||(hh>12)){return 0;}i_val+=hh.length;}else if(token=="HH"||token=="H"){hh=_getInt(val,i_val,token.length,2);if(hh==null||(hh<0)||(hh>23)){return 0;}i_val+=hh.length;}else if(token=="KK"||token=="K"){hh=_getInt(val,i_val,token.length,2);if(hh==null||(hh<0)||(hh>11)){return 0;}i_val+=hh.length;}else if(token=="kk"||token=="k"){hh=_getInt(val,i_val,token.length,2);if(hh==null||(hh<1)||(hh>24)){return 0;}i_val+=hh.length;hh--;}else if(token=="mm"||token=="m"){mm=_getInt(val,i_val,token.length,2);if(mm==null||(mm<0)||(mm>59)){return 0;}i_val+=mm.length;}else if(token=="ss"||token=="s"){ss=_getInt(val,i_val,token.length,2);if(ss==null||(ss<0)||(ss>59)){return 0;}i_val+=ss.length;}else if(token=="a"){if(val.substring(i_val,i_val+2).toLowerCase()=="am"){ampm="AM";}else if(val.substring(i_val,i_val+2).toLowerCase()=="pm"){ampm="PM";}else{return 0;}i_val+=2;}else{if(val.substring(i_val,i_val+token.length)!=token){return 0;}else{i_val+=token.length;}}}if(i_val != val.length){return 0;}if(month==2){if( ((year%4==0)&&(year%100 != 0) ) ||(year%400==0) ){if(date > 29){return 0;}}else{if(date > 28){return 0;}}}if((month==4)||(month==6)||(month==9)||(month==11)){if(date > 30){return 0;}}if(hh<12 && ampm=="PM"){hh=hh-0+12;}else if(hh>11 && ampm=="AM"){hh-=12;}var newdate=new Date(year,month-1,date,hh,mm,ss);return newdate.getTime();}
function parseDate(val){var preferEuro=(arguments.length==2)?arguments[1]:false;generalFormats=new Array('y-M-d','MMM d, y','MMM d,y','y-MMM-d','d-MMM-y','MMM d');monthFirst=new Array('M/d/y','M-d-y','M.d.y','MMM-d','M/d','M-d');dateFirst =new Array('d/M/y','d-M-y','d.M.y','d-MMM','d/M','d-M');var checkList=new Array('generalFormats',preferEuro?'dateFirst':'monthFirst',preferEuro?'monthFirst':'dateFirst');var d=null;for(var i=0;i<checkList.length;i++){var l=window[checkList[i]];for(var j=0;j<l.length;j++){d=getDateFromFormat(val,l[j]);if(d!=0){return new Date(d);}}}return null;}

