var application = new function($) {
	
	this.root = 'http://' + document.domain + '/' + (document.domain.toLowerCase() == 'server2003' ? 'generalmatco' : '') + '/';
	
	this.core = {
		ready: function(fn, scope) {
		  var args = Array.prototype.slice.call(arguments, 2);
		  
		  $(function() {
			fn.apply(scope || application, args); 
		  });		
		}		
	};
	
	this.images = {
		random: function() {
			$('#random-images').cycle({
				fx: 'scrollDown',
				speed: 500,
				timeout: 5000,
				random: true,
				pause: true
			});
		}
	};
	
	this.newsletter = {
		subscribe: function() {
			var name = $('#newsletter-form .first-name');
			var initialName = name.val();
			var email = $('#newsletter-form [name=email]');
			var initialEmail = email.val();			

			name.bind('focus', function(){ 
				$(this).val() == initialName ? $(this).val('') : null; 
			}).bind('blur', function() { 
				$(this).val() == '' ? $(this).val(initialName) : null; 
			});

			email.bind('focus', function(){ 
				$(this).val() == initialEmail ? $(this).val('') : null; 
			}).bind('blur', function() { 
				$(this).val() == '' ? $(this).val(initialEmail) : null; 
			});
			
			$('#newsletter-form').bind('submit', function() {	
				if (/^\w+[\+\.\w-]*@([\w-]+\.)*\w+[\w-]*\.([a-z]{2,5}|\d+)$/.test(email.val())) {
					return true;	
				} else {
					alert('Please enter a valid email address.');
					
					email.val('').trigger('focus');
					
					return false;
				}
			});
		}
	};
	
	this.pricing = {
		password: function() {
			$('#pricing-form').bind('submit', function() {
				var passwordField = $('[type=password]', this);
				var password = passwordField.val().toLowerCase();
				var passcode = 1;
				var valid = 138878551350;
				
				for(i = 0; i < password.length; i++) {
					passcode *= password.charCodeAt(i);
				}
				
				if (passcode == valid) {
					window.location = application.root + password + '/wholesale_pricelist.pdf';	
				} else {
					alert('The password you entered is incorrect');
					
					passwordField.val('').trigger('focus');
				}	
				
				return false;
			});
		}
	};
	
	this.quote = {
		referer: function() {
			if (document.referrer) {
				var ref = document.referrer;
				
				ref = ref.split('/');
				ref = ref[ref.length - 1].replace('.htm','').replace(/\_|\-/g, ' ');
				
				$(' [name=referrer]').val(ref);
			}
		}
	};
	
	this.forms = {
		validate: function() {
			$('#quote-form, #distributor-form, #order-catalouge').validate();	
		}
	};

	this.init = function() {
		this.core.ready(function() {
			this.images.random();
			this.newsletter.subscribe();
			this.forms.validate();
			this.quote.referer();
			this.pricing.password();
		});
	};
}(jQuery);

application.init();