var gs = {
	URL: '',
	curPage: '',
	msie: { 'is_browser' : false, 'version' : '0' },
	homeWelcome: { 'timeout': null },
	contentBGImg: { 'loaded': 0, 'num': 0, 'timeout': null },
	
	initialize: function(object){
		this.URL = '';
		
		for(var key in object){
			this[key] = object[key];
		}
		
		if($.browser.msie){
			this.msie.is_browser = true;
			this.msie.version = $.browser.version;
		}
				
		//Register Ajax Error Event
		$.ajaxSetup({
			error:function(x,e){
				Sexy.error('<h1 style="background:none;height:auto;font-weight:bold;font-size:14px;text-indent:0;">Hmmm....we got trouble here!</h1><p>Something wrong while requesting.</p><p>XHR Status : ' + x.status + '</p>');
			}
		});

		this.prepActions();	
	},
	prepActions: function(){
		/*---------------------------------------*/
		this.generalActions();
		
		/*---------------------------------------*/
		this.styling();
		
		/*---------------------------------------*/
		this.homeActions();
		
		/*---------------------------------------*/
		this.alternativeActions();
		
		/*---------------------------------------*/
		this.reservationActions();
		
		/*---------------------------------------*/
		this.contactActions();
		
	},
	checkEmail: function(element){
		var emailfilter=/^\w+[\+\.\w-]*@([\w-]+\.)*\w+[\w-]*\.([a-z]{2,4}|\d+)$/i;
		if(!emailfilter.test($(element).val())) return false;
		
		return true;
	},
	contentBGLoad: function(){
		gs.contentBGImg.loaded++;
				
		if( gs.contentBGImg.loaded == gs.contentBGImg.num ){
			$('.content-background div:first').show();
			
			if( $('.content-background div').length > 1 ){
				$('.content-wp .img-pagination').show();
				gs.contentBGImg.timeout = setTimeout( gs.contentBGAnimation, 6000 );
			}
		}
	},
	contentBGAnimation: function(){
		clearTimeout( gs.contentBGImg.timeout );
		if( $('.content-wp .img-pagination').hasClass('animated') )
			return false;

		gs.contentBackgroundAnime( 'auto', true );
		
	},
	contentBackgroundAnime: function( action, timeout, callback ){		
		var curImg = parseInt( $('.content-wp .img-pagination').attr('id').replace('i_', '') );
		switch( action )
		{
			case 'prev'	:
				if( curImg == 1 )
					return false;
				curImg -= 1;
				
				$('.content-wp .img-pagination').addClass('animated');
				var temp = $('.content-background #img_' + curImg ).clone().css({ 'opacity' : 0 }).attr('id', 'temp').show();
					$('.content-background').append(temp).find('.img:last').animate({ 'opacity' : 1 }, 'slow', function(){ 
						$('.content-background #img_' + curImg ).remove(); 
						$(this).attr('id', 'img_' + curImg ); 
						$('.content-wp .img-pagination').removeClass('animated');
						
						$('.content-wp .img-pagination').closest('.img-pagination').attr('id', 'i_' + curImg);
						
						clearTimeout( gs.contentBGImg.timeout );
						gs.contentBGImg.timeout = setTimeout( gs.contentBGAnimation, 6000 );
						
						if( typeof( callback ) != 'undefined' )
							callback;
					});
				break;
			case 'next'	:
				if( curImg == $('.content-background .img').length )
					return false;
				curImg += 1;
				
				$('.content-wp .img-pagination').addClass('animated');
				var temp = $('.content-background #img_' + curImg ).clone().css({ 'opacity' : 0 }).attr('id', 'temp').show();
					$('.content-background').append(temp).find('.img:last').animate({ 'opacity' : 1 }, 'slow', function(){
						$('.content-background #img_' + curImg ).remove(); 
						$(this).attr('id', 'img_' + curImg ); 
						$('.content-wp .img-pagination').removeClass('animated'); 
						
						$('.content-wp .img-pagination').closest('.img-pagination').attr('id', 'i_' + curImg);
						
						clearTimeout( gs.contentBGImg.timeout );
						gs.contentBGImg.timeout = setTimeout( gs.contentBGAnimation, 6000 );
						
						if( typeof( callback ) != 'undefined' )
							callback;
					});
				break;
			case 'auto':
				if( curImg == $('.content-background .img').length )
					curImg = 0;
				curImg += 1;
				
				$('.content-wp .img-pagination').addClass('animated');
				var temp = $('.content-background #img_' + curImg ).clone().css({ 'opacity' : 0 }).attr('id', 'temp').show();
					$('.content-background').append(temp).find('.img:last').animate({ 'opacity' : 1 }, 'slow', function(){
						$('.content-background #img_' + curImg ).remove(); 
						$(this).attr('id', 'img_' + curImg ); 
						$('.content-wp .img-pagination').removeClass('animated'); 
						
						$('.content-wp .img-pagination').closest('.img-pagination').attr('id', 'i_' + curImg);
						
						clearTimeout( gs.contentBGImg.timeout );
						gs.contentBGImg.timeout = setTimeout( gs.contentBGAnimation, 6000 );
						
						if( typeof( callback ) != 'undefined' )
							callback;
					});
				break;
			default:
				var toImg = parseInt( action );
				if( curImg == toImg )
					return;
				
				//$('.content-background .img:eq(' + ( toImg - 1 ) + ')').animate({ 'opacity' : 1 }, 'slow', function(){ $('.content-background .active').css({ 'opacity': 0 }); } );
				$('.content-wp .img-pagination').addClass('animated');
				var temp = $('.content-background #img_' + toImg ).clone().css({ 'opacity' : 0 }).attr('id', 'temp').show();
					$('.content-background').append(temp).find('.img:last').animate({ 'opacity' : 1 }, 'slow', function(){
						$('.content-background #img_' + toImg ).remove();
						$(this).attr('id', 'img_' + toImg ); 
						$('.content-wp .img-pagination').removeClass('animated'); 
						
						$('.content-wp .img-pagination').closest('.img-pagination').attr('id', 'i_' + toImg);
						
						clearTimeout( gs.contentBGImg.timeout );
						gs.contentBGImg.timeout = setTimeout( gs.contentBGAnimation, 6000 );
						
						if( typeof( callback ) != 'undefined' )
							callback;
					});
				break;
		}
	},
	generalActions: function(){
		//Menu actions
		$('#menu li.reservation a').hover(
			function(){
				$(this).closest('span').addClass('hover');
			},
			function(){
				$(this).closest('span').removeClass('hover');
			}
		);
		
		//Content Background
		var bg = $('.content-background div');
		gs.contentBGImg.num = bg.length;
		bg.each(function(){
			var url = $(this).css('background-image');
			url = url.replace("url(\"", "").replace("url(", "").replace("\")", "").replace(")", "");
			
			var newImg = new Image();
			newImg.onLoad = gs.contentBGLoad();
			newImg.src = url;
		});
	
		$('.content-wp .img-pagination a span.overlay').css({ 'opacity': 0.75 });
		$('.content-wp .img-pagination').delegate('a', 'click', function(e){
			e.preventDefault();
			
			if( $('.content-wp .img-pagination').hasClass('animated') )
				return false;
			
			
			gs.contentBackgroundAnime( $(this).attr('rel') );			
		});
		
		//Search form
		$('form#search').submit(function(){
			if( $(this).find('#src-key').val() === '' )
				return false;
				
			return true;
		});
	},
	styling: function(){		
		if( $('#alternative-content').length > 0 ){
			if( $('#alternative-content .right').outerHeight() >  $('#alternative-content .left').outerHeight() )
				 $('#alternative-content .left').css({ 'height' : $('#alternative-content .right').outerHeight() });
			$('#alternative-content .left').addClass('left-border');
		}		
	},
	homeWelcomeClose: function(){
		$('div#welc-content-wrp').stop().animate({ 'height': ( $('div#welc-content-wrp h1').height() + 19 ) + 'px' }).find('.window-handler').html('=');
	},
	homeActions: function(){
		if( gs.curPage != 'home' )
			return;
			
		$('.transparent').css({ 'opacity': 0.75 });
		
		if( gs.msie.is_browser && ( gs.msie.version == '8.0') )
			$('#welc-content-wrp').hide().css({ 'bottom': '40px' }).show();
		if( gs.msie.is_browser && ( gs.msie.version == '7.0') ){
			var ie7height = $('#welc-content-wrp').css({ 'height' : 'auto' }).outerHeight();
			$('.welc-ct-overlay').height( $('.welc-ct-overlay').closest('.welc-content').outerHeight() );
			//$('#welc-content-wrp').css({ 'height' : '35px' })
		}else
			$('.welc-ct-overlay').height( $('.welc-ct-overlay').closest('.welc-content').outerHeight() );
		
		gs.homeWelcome.timeout = setTimeout( gs.homeWelcomeClose, 20000 );
		
		$('#welc-content-wrp').delegate('.window-handler', 'click', function(e){
			e.preventDefault();
			clearTimeout( gs.homeWelcome.timeout );
			
			if( $(this).html() == '=' ){
				if( gs.msie.is_browser && ( gs.msie.version == '7.0') ){
					$(this).html('x').closest('div#welc-content-wrp').stop().animate({ 'height': ie7height + 'px' });
				}else{
					$(this).html('x').closest('div#welc-content-wrp').stop().animate({ 'height': $('#welc-content-wrp .welc-content').outerHeight() + 'px' });
				}
			}
			else
				$(this).html('=').closest('div#welc-content-wrp').stop().animate({ 'height': ( $('div#welc-content-wrp h1').height() + 19 ) + 'px' });
		});
		
	},
	alternativeActions: function(){
		if( $('#alternative-content').length <= 0 )
			return;
			
		$('.a-slideshow-wrapper a.np span.tc-overlay').css({ 'opacity': 0.6 });
		
		if( gs.msie.is_browser && gs.msie.version === '7.0' ){
			$('.a-slideshow').find('img').each(function(){
				if( $(this).height() < $(this).closest('li').height() ){
					var difHeight = $(this).closest('li').height() - $(this).height();
					$(this).closest('a').css('margin-top', Math.floor( difHeight / 2 ) + 'px');
				}
			});
			
			
			$('.thumbnails-list').find('img').each(function(){
				if( $(this).height() < $(this).closest('li').height() ){
					var difHeight = $(this).closest('li').height() - $(this).height();
					$(this).closest('span').css('margin-top', Math.floor( difHeight / 2 ) + 'px');
					//alert( $(this).closest('span').css('margin-top') );
				}
			});
		}
		
		$('#alternative-content .right').delegate('.a-slideshow-wrapper a.np', 'click', function(e){
			e.preventDefault();
			
			if( $('.a-slideshow:animated').length > 0 )
				return false;
				
			var atStart = ( parseInt( $('.a-slideshow').css('margin-left').replace('px','') ) == 0 )? true:false;
			switch( $(this).attr('rel') ){
				case 'prev':
					if( atStart )
						return false;
					/*var curCol = parseInt( $('.a-slideshow ul').attr('id').replace('i_', '') );
					
					//if( ( Math.abs ( parseInt( $('.a-slideshow').css('margin-left').replace('px','') ) ) % 193 ) > 0 )
					if( curCol == 1 && ( ( Math.abs ( parseInt( $('.a-slideshow').css('margin-left').replace('px','') ) ) % 193 ) > 0 ) )
						var moveRight = 43;
					else
						var moveRight = 193;
					
					$('.a-slideshow').stop().animate({ 'margin-left': ( parseInt( $('.a-slideshow').css('margin-left').replace('px','') ) + moveRight ) + 'px' }, 'medium', 'easeInQuad');

					curCol -= 1;
					$('.a-slideshow ul').attr('id', 'i_' + curCol);*/
					
					var moveRight = parseInt( $('.a-slideshow').css('margin-left').replace('px','') ) >= 0? 0:182;
					$('.a-slideshow').stop().animate({ 'margin-left': ( parseInt( $('.a-slideshow').css('margin-left').replace('px','') ) + moveRight ) + 'px' }, 'medium', 'easeInQuad');
					
					break;
				case 'next':
					/*var curCol = parseInt( $('.a-slideshow ul').attr('id').replace('i_', '') );
					
					if( $('.a-slideshow li:gt(' + ( curCol + 2 ) + ')').length <= 0 )
						return false;
					
					if( $('.a-slideshow li:gt(' + ( curCol + 3 ) + ')').length <= 0 )
						var moveLeft = 43;
					else
						var moveLeft = 193;
					
					$('.a-slideshow').stop().animate({ 'margin-left': ( parseInt( $('.a-slideshow').css('margin-left').replace('px','') ) - moveLeft ) + 'px' }, 'medium', 'easeInQuad');
					
					curCol += 1;
					$('.a-slideshow ul').attr('id', 'i_' + curCol);*/
					
					var moveLeft = parseInt( $('.a-slideshow').css('margin-left').replace('px','') ) <= ( ( ( $('.a-slideshow').find('li').length - 4 ) * 182 ) * -1 )? 0:182;
					$('.a-slideshow').stop().animate({ 'margin-left': ( parseInt( $('.a-slideshow').css('margin-left').replace('px','') ) - moveLeft ) + 'px' }, 'medium', 'easeInQuad');
					
					break;
			}
		});
		
		$('#thumbnails-wrapper').delegate('h3 a', 'click', function(e){
			e.preventDefault();
			
			if( $(this).closest('h3').siblings('div.lists:animated').length > 0 )
				return;
			
			if( $(this).closest('h3').siblings('div.lists:visible').length > 0 )
				$(this).closest('h3').siblings('div.lists:visible').slideUp();
			else
				$(this).closest('h3').siblings('div.lists:hidden').slideDown();
		});
		
		/*
		//Sub Menu AJAX
		$('#submenu').delegate('a', 'click', function(e){
			e.preventDefault();
			$('#submenu a').removeClass('active');
			$(this).addClass('active');
			
			$.post(
				gs.URL + gs.curPage + '/getDetail',
				{},
				function(data){
					$('#alternative-content .right').html( data );
					$('.a-slideshow-wrapper a.np span.tc-overlay').css({ 'opacity': 0.6 });
					
					$('#SLB-Wrapper').remove();
					SexyLightbox.initialize({ OverlayStyles:{ 'background-color':'#fff', 'opacity': 0.5 }, color: 'black', dir: gs.URL + 'js/library/sexyimages' });
				}
			);
		});
		*/
	},
	reservationActions: function(){
		if( $('#reservation').length <= 0 )
			return;
		
		$('#reservation form input[type=reset]').click(function(){
			$('#reservation form input, #reservation form select').removeClass('error');
			$('#error-message').remove();
		});
		
		$('#reservation form').submit(function(){
			$('#error-message').remove();
			$('#reservation form input, #reservation form select').removeClass('error');
			
			var errorArr = new Array();
			var phoneArr = new Array();
			
			var noEmpty = $(this).find('.no-empty, .cc-type');
			
			noEmpty.each(function(){
				if( $(this).hasClass('email') ){
					if( !gs.checkEmail( $(this) ) ){
						$(this).addClass('error');
						
						if( $.inArray( $(this).closest('td').prev('td.ttitle').html(), errorArr ) < 0  )
							errorArr.push( $(this).closest('td').prev('td.ttitle').html() );
					}
				}else if( $(this).hasClass('phone') ){
					
					if( $(this).val() === '' ){
						if( $.inArray( $(this).closest('td').prev('td.ttitle').html(), phoneArr ) < 0  )
							phoneArr.push( $(this).closest('td').prev('td.ttitle').html() );
					}
					
					if( ( $(this).attr('name') === 'fax_phone[]' ) && ( $(this).hasClass('at-least-one') ) ){
						if( phoneArr.length >= 4 ){
							$('#reservation form input.phone').addClass('error');
							errorArr.push( 'Phone' );
						}
					}
				}else if( $(this).hasClass('cc-type') ){
					if( $(this).val() === '' || $(this).val() === 'no-value' ){
						$(this).addClass('error');
						
						if( $.inArray( $(this).closest('td').prev('td.ttitle').html(), errorArr ) < 0  )
							errorArr.push( $(this).closest('td').prev('td.ttitle').html() );
					}else{
						var cardNum = $('#reservation form').find('input[name=card_num]');
						if( cardNum.val() === '' ){
							cardNum.addClass('error');
							
							if( $.inArray( cardNum.closest('td').prev('td.ttitle').html(), errorArr ) < 0  )
								errorArr.push( cardNum.closest('td').prev('td.ttitle').html() );
						}else{
							if( !checkCreditCard( cardNum.val(), $(this).val() ) ){
								if( $.inArray( 'ccError' , errorArr ) < 0  ){
									cardNum.addClass('error');
									errorArr.push( 'ccError' );
								}
							}
						}
					}
				}else{
					if( $(this).val() === '' || $(this).val() === 'no-value' ){
						$(this).addClass('error');
						
						if( $.inArray( $(this).closest('td').prev('td.ttitle').html(), errorArr ) < 0  )
							errorArr.push( $(this).closest('td').prev('td.ttitle').html() );
					}
				}
			});

			if( errorArr.length > 0 ){
				var message = '';
				for( index in errorArr ){
					switch( errorArr[index] ){
						case 'Email Address' 	: message += '<strong>' + errorArr[index] + '</strong> is invalid<br/ >'; break;
						case 'Phone'		 	: message += '<strong>Phone</strong> must be filled at least 1 (one)<br />'; break;
						case 'Credit Card Type' : message += '<strong>' + errorArr[index] + '</strong> must be selected<br />'; break;
						case 'ccError'			: message += ccErrors[ ccErrorNo ] + '<br />'; break;
						default				 	: message += '<strong>' + errorArr[index] + '</strong> must be filled<br/ >'; break;
					}
				}
				
				var errorMessage  = $('<div />', { 'id': 'error-message' }).append( $('<p />').append(message) );
				$('#reservation').prepend( errorMessage );
				
				$.scrollTo('#reservation', 800);
			}
			
			return ( errorArr.length > 0 )? false:true;
		});
	},
	contactActions: function(){
		if( $('#contact').length <= 0 )
			return;
		
		$('#contact form input[type=reset]').click(function(){
			$('#contact form input, #contact form select, #contact form textarea').removeClass('error');
			$('#error-message').remove();
		});
		
		$('#contact form').submit(function(){
			$('#error-message').remove();
			$('#contact form input, #contact form select, #contact form textarea').removeClass('error');
			
			var errorArr = new Array();
			var phoneArr = new Array();
			
			var noEmpty = $(this).find('.no-empty');
			
			noEmpty.each(function(){
				if( $(this).hasClass('email') ){
					if( !gs.checkEmail( $(this) ) ){
						$(this).addClass('error');
						
						if( $.inArray( $(this).closest('td').prev('td.ttitle').html(), errorArr ) < 0  )
							errorArr.push( $(this).closest('td').prev('td.ttitle').html() );
					}
				}else if( $(this).hasClass('phone') ){
					
					if( $(this).val() === '' ){
						if( $.inArray( $(this).closest('td').prev('td.ttitle').html(), phoneArr ) < 0  )
							phoneArr.push( $(this).closest('td').prev('td.ttitle').html() );
					}
					
					if( ( $(this).attr('name') === 'fax_phone[]' ) && ( $(this).hasClass('at-least-one') ) ){
						if( phoneArr.length >= 4 ){
							$('#contact form input.phone').addClass('error');
							errorArr.push( 'Phone' );
						}
					}
				}else if( $(this).hasClass('message') ){
					if( $(this).val() === '' ){
						$(this).addClass('error');
						
						if( $.inArray( 'Message', errorArr ) < 0  )
							errorArr.push( 'Message' );
					}
				}else{
					if( $(this).val() === '' || $(this).val() === 'no-value' ){
						$(this).addClass('error');
						
						if( $.inArray( $(this).closest('td').prev('td.ttitle').html(), errorArr ) < 0  )
							errorArr.push( $(this).closest('td').prev('td.ttitle').html() );
					}
				}
			});

			if( errorArr.length > 0 ){
				var message = '';
				for( index in errorArr ){
					switch( errorArr[index] ){
						case 'Email Address' 	: message += '<strong>' + errorArr[index] + '</strong> is invalid<br/ >'; break;
						case 'Phone'		 	: message += '<strong>Phone</strong> must be filled at least 1 (one)<br />'; break;
						default				 	: message += '<strong>' + errorArr[index] + '</strong> must be filled<br/ >'; break;
					}
				}
				
				var errorMessage  = $('<div />', { 'id': 'error-message' }).append( $('<p />').append(message) );
				$('#contact').prepend( errorMessage );
				
				$.scrollTo('#contact', 800);
			}
			
			return ( errorArr.length > 0 )? false:true;
		});
	}
}

/*================================================================================================*/

/*

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
Updated:    18th Jan. 2008      Additional cards added from Wikipedia
Updated:    26th Nov. 2008      Maestro cards extended
Updated:    19th Jun. 2009      Laser cards extended from Wikipedia
Updated:    11th Sep. 2010      Typos removed from Diners and Solo definitions (thanks to Noe Leon)

*/

/*
   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] = "<strong>Unknown card type</strong>";
ccErrors [1] = "<strong>No card number</strong> provided";
ccErrors [2] = "<strong>Credit Card number</strong> is in invalid format";
ccErrors [3] = "<strong>Credit Card number</strong> is invalid";
ccErrors [4] = "<strong>Credit Card number</strong> 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 as follows.
  
  //  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: "305,36,38,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};
  cards [12] = {name: "LaserCard", 
               length: "16,17,18,19", 
               prefixes: "6304,6706,6771,6709",
               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;
}

/*================================================================================================*/

