// JavaScript Document
(function() {	
	String.implement({
		isEmail: function() {
			return this.trim().search(/^[a-z0-9]+([-._+][a-z0-9]+)*@[a-z0-9]+([-._][a-z0-9]+)*[.][a-z]{2,6}$/i) != -1;
		}
		, isEmails: function() {
			return this.trim().search(/^[a-z0-9]+([-._+][a-z0-9]+)*@[a-z0-9]+([-._][a-z0-9]+)*[.][a-z]{2,6}(\s*[;,]\s*[a-z0-9]+([-._+][a-z0-9]+)*@[a-z0-9]+([-._][a-z0-9]+)*[.][a-z]{2,6})*$/i) != -1;
		}
		, isURL: function() {
			return this.trim().search(/^([a-z0-9]+[a-z0-9-_]*[a-z0-9]+[.])+[a-z]{2,6}$/i) != -1;
		}
		, isNum: function() {
			return this.trim().search(/^[0-9]+$/i) != -1;
		}
		, isBlank: function() {
			return this.trim() == '';
		}
		, isCreditCard: function(cardname) {
			var cardnumber = this.trim();
			
			// 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
			// Lengths:    	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
			var cards = new Array(
				{
					name: 'Visa'
					, lengths: '13, 16'
					, prefixes: '4'
					, checkdigit: true
				}
				, {
					name: 'Master' 
					, lengths: '16'
					, prefixes: '51, 52, 53, 54, 55'
					, checkdigit: true
				}
				, {
					name: 'DinersClub'
					, lengths: '14,16'
					, prefixes: '305, 36, 38, 54, 55'
					, checkdigit: true
				}
				, {
					name: 'CarteBlanche'
					, lengths: '14'
					, prefixes: '300, 301, 302, 303, 304, 305'
					, checkdigit: true
				}
				, {
					name: 'Amex'
					, lengths: '15'
					, prefixes: '34, 37'
					, checkdigit: true
				}
				, {
					name: 'Discover'
					, lengths: '16'
					, prefixes: '6011,622,64,65'
					, checkdigit: true
				}
				, {
					name: 'JCB'
					, lengths: '16'
					, prefixes: '35'
					, checkdigit: true
				}
				, {
					name: 'enRoute'
					, lengths: '15'
					, prefixes: '2014, 2149'
					, checkdigit: true
				}
				, {
					name: 'Solo'
					, lengths: '16, 18, 19'
					, prefixes: '6334, 6767'
					, checkdigit: true
				}
				, {
					name: 'Switch'
					, lengths: '16, 18, 19'
					, prefixes: '4903, 4905, 4911, 4936, 564182, 633110, 6333, 6759'
					, checkdigit: true
				}
				, {
					name: 'Maestro'
					, lengths: '12, 13, 14, 15, 16, 18, 19'
					, prefixes: '5018, 5020, 5038, 6304, 6759, 6761'
					, checkdigit: true
				}
				, {
					name: 'VisaElectron'
					, lengths: '16'
					, prefixes: '417500, 4917, 4913, 4508, 4844'
					, checkdigit: true
				}
				, {
					name: 'LaserCard'
					, lengths: '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++) {
				if (cardname.trim().toLowerCase() == cards[i].name.toLowerCase()) {
				  cardType = i;
				  break;
				}
			}
		  
			// If card type not found, report an error
			if (cardType == -1) {
				return false; 
			}
		   
			// Ensure that the user has provided a credit card number
			if (cardnumber.length == 0)  {
				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))  {
				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)  {
					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.replace (/\s/g, '').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) {
				return false; 
			}

			// See if the length is valid for this card
			lengths = cards[cardType].lengths.replace (/\s/g, '').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) {
				return false; 
			};   

			// The credit card is in the required format.
			return true;
		}
	});
	
	function initCaptchaImg() {
		var img = $('captchaImg');
		if (img) {
			var baseSrc = img.src;
			img.set('title', 'Cannot see? Click here to reload image!');
			img.addEvent('click', function(e) {
				e.stop();
				this.src = baseSrc + '?r=' + Math.random();
			});
		}
	}
	
	function initSlimBox() {
		/*$$("a").filter(function(el) {
			return el.rel && el.rel.test(/^lightbox/i);
		}).slimbox({}, null, function(el) {
			return (this == el) || ((this.rel.length > 8) && (this.rel == el.rel));
		});*/
		milkbox = new Milkbox();
	}
	
	function initFaq() {
		var togglers = $$('#faq h3');
		var elements = $$('#faq div');
		new Fx.Accordion(togglers, elements, {
			display: 0
			, opacity: false
			, alwaysHide: true
			, onActive: function(toggler, element) {
				toggler.addClass('hopened');
			}
			, onBackground: function(toggler, element) {
				toggler.removeClass('hopened');
			}
		});
	}
	
	function initRegisterForm() {
		var form = $('registerForm');
		if (!form) {
			return;
		}
		
		var firstname = form.getElement('input[name=firstname]');
		var lastname = form.getElement('input[name=lastname]');
		var email = form.getElement('input[name=email]');
		var email2 = form.getElement('input[name=email2]');
		
		if (!firstname || !lastname || !email || !email2) {
			return;
		}
		
		form.addEvent('submit', function(e){
			if (firstname.get('value').isBlank()) {
				alert('Please input your first name!');
				firstname.focus();
				e.stop();
				return;
			}
			if (lastname.get('value').isBlank()) {
				alert('Please input your last name!');
				lastname.focus();
				e.stop();
				return;
			}
			if (!email.get('value').isEmail()) {
				alert('Please input your valid email address!');
				email.focus();
				e.stop();
				return;
			}
			if (email2.get('value') != email.get('value')) {
				alert('Your confirm email does not match!');
				email2.focus();
				e.stop();
				return;
			}
		});
	}
	
	function initUninstallForm() {
		var form = $('uninstallForm');
		if (!form) {
			return;
		}
		
		var reason = form.getElement('textarea[name=reason]');
		var email = form.getElement('input[name=email]');
		
		if (!reason || !email) {
			return;
		}
		
		form.addEvent('submit', function(e){
			if (reason.get('value').isBlank()) {
				alert('Please input your comment!');
				reason.focus();
				e.stop();
				return;
			}
			if (!email.get('value').isEmail()) {
				alert('Please input your valid email address!');
				email.focus();
				e.stop();
				return;
			}
		});
	}
	
	function initUpgradeForm() {
		var form = $('upgradeForm');
		if (!form) {
			return;
		}
		
		var select = form.getElement('select[name=item]');
		var label = form.getElement('label[class=extend]');
		var check = form.getElement('input[name=extend]');
		
		if (!select || !label || !check) {
			return;
		}
		
		select.selectedIndex = 0;
		select.addEvent('change', setLabel);
		check.addEvent('click', setLabel);
		
		function setLabel(){
			var priceMap = [];
			priceMap[301] = 29.97;
			priceMap[302] = 39.97;
			priceMap[303] = 59.97;
			priceMap[304] = 99.97;
			
			priceMap[305] = 39.92;
			priceMap[306] = 59.96;
			priceMap[307] = 89.96;
			priceMap[308] = 149.96;
			
			priceMap[309] = 25.47;
			priceMap[310] = 33.97;
			priceMap[311] = 50.97;
			priceMap[312] = 84.97;
			
			priceMap[313] = 35.42;
			priceMap[314] = 53.96;
			priceMap[315] = 80.96;
			priceMap[316] = 134.96;
			
			priceMap[317] = 19.95;
			priceMap[318] = 29.95;
			priceMap[319] = 49.95;
			priceMap[320] = 89.95;
			
			priceMap[321] = 29.95;
			priceMap[322] = 49.95;
			priceMap[323] = 79.95;
			priceMap[324] = 139.95;
			
			priceMap[325] = 14.95;
			priceMap[326] = 19.95;
			priceMap[327] = 29.95;
			priceMap[328] = 49.95;
			
			priceMap[329] = 15.95;
			priceMap[330] = 29.95;
			priceMap[331] = 44.95;
			priceMap[332] = 74.95;
			
			try {
				var currentValue = Number(select.options[select.selectedIndex].value);
				var extendedValue = Number(check.checked ? 4 : 0);
				var totalValue = priceMap[currentValue + extendedValue];
				$('basketTotal').set('html', '<strong>Total:</strong> $' + totalValue);
			} catch (e) {}
		}
	}
	
	function initTutorialVideo() {
		var videoTarget = $('tutorialVideo');
		if (!videoTarget) {
			return;
		}
		new Swiff('/flashpub/main.swf', {
			id: videoTarget.id + 'Video'
			, width: 300
			, height: 255
			, params: {quality: 'best', allowFullScreen: 'true', menu: 'false', bgcolor: '#EFEFEF', wmode: 'window'}
			, vars: {flashBase: '/flashpub/', fileTitle: 'RegAce', fileCover: '../images/coming_soon.png', filePath: '../images/coming_soon.png', fileType: 'image'}
			, callBacks: {}
		}).inject(videoTarget);
	}

	function initDomDeady() {
		initCaptchaImg();
		initSlimBox();
		initFaq();
		initRegisterForm();
		initUninstallForm();
		initUpgradeForm();
		initTutorialVideo();
	}
	
	function initDomLoad() {
	}

	if (!/android|iphone|ipod|series60|symbian|windows ce|blackberry/i.test(navigator.userAgent)) {
		window.addEvent('domready', initDomDeady);
		window.addEvent('load', initDomLoad);
	}
})();
