window.addEvent("domready", function(){
    var status = "";

    $$('#smart-enquiry input[type=text]', '#smart-enquiry textarea', '#smart-enquiry select').each(function(el) {
        el.addEvents({                              
            'blur'   :  function() {
                this.setStyle('background-color','');
                        
                if (this.value.clean() == "" && this.hasClass('required')) {   
                    // Required field - not filled.
                    this.highlight('#ee8282');
                    var status = "invalid";
                } else if ((this.value.clean() != "" && this.hasClass('required')) ||
                           (this.value.clean() != "" && !this.hasClass('required'))) {
                    // Check for valid email
                    if (this.hasClass('email') && isEmail(this.value.clean())) {
                        this.highlight('#87ee82');
                        var status = "valid";
                    } else if (!this.hasClass('email')){
                        this.highlight('#87ee82');
                        var status = "valid";
                    } else {
                        this.highlight('#ee8282');
                        var status = "invalid";
                    }
                }
                
                // label that will be adopting
                var adopter = this.getParent();
                
                // New status symbol element
                statusImg = new Element('img', {
                    'class': 'status ' + status,
                    'width': '16',
                    'height': '16'});
                
                // Change image source
                if (status == "invalid") {
                    statusImg.src = base + "img/smart-enquiry/exclamation.gif";
                    statusImg.alt = "This field is required";
                } else if (status == "valid") {
                    statusImg.src = base + "img/smart-enquiry/tick.gif";
                    statusImg.alt = "This field is filled";
                }
    
                // Check for existing status image
                if (adopter.getFirst($('img')).hasClass('status')) {
                    var toReplace = adopter.getFirst($('img'));
                    // Destroy the status image if this is not a required field
                    if (this.value.clean() == "" && !this.hasClass('required')) {
                        toReplace.destroy();
                    } else {
                        statusImg.replaces(toReplace);
                    }   
                } else if (this.value.clean() != "" || this.hasClass('required')) { 
                    statusImg.inject(adopter, 'top');
                }   
            }
        });
    });    

    $('smart-enquiry').addEvent('submit', function(e) {
        
    	new Event(e).stop();

    	var containerHeight = $('contact-form').getSize(); 
    	
		var overlay = new Element('div', {	
			'id' : 'overlay'			
		}).set('styles', {
			'height':containerHeight.y ,
			'width':containerHeight.x
		});
		
		var waiter = new Element('img', {	
			'width'  : '32',
			'height' : '32',
			'src'	 : base + "img/smart-enquiry/ajax-load.gif",
			'alt'	 : 'Please wait...',
			'id'	 : 'waiter'
		}).set('styles', {
			'margin-top':containerHeight.y / 2 - 16,
			'margin-left':containerHeight.x / 2 - 16
		});	

		var messageBox = new Element('div', {	
			'id' : 'message-box'
		}).set('styles', {
			'margin-top': 0,
			'margin-left':containerHeight.x / 2 - 124
		});	
		
		var fade = new Fx.Morph(overlay, {
			duration : 200,
			transition: Fx.Transitions.Sine.easeOut
		}).set({
			'opacity':0
		}) ;	
	   
		new Request.JSON({

			onRequest  :  function() {
				
				overlay.inject($('contact-form'), 'top');
				
				fade.start({
					'opacity':0.7
				}).chain(function() {
					waiter.inject($('contact-form'), 'top');	
				});
			},
	        onSuccess : function(json){
				waiter.destroy();

				var middley = containerHeight.y / 2 - 81;
				
				var bounceFade = new Fx.Morph(messageBox, {
					duration : 1600,
					transition: Fx.Transitions.Elastic.easeOut
				}).set({
					'opacity':0,
					'margin-top' : 0
				}) ;
				
				if (!json || json.errors) {
	            	
	            	messageBox.setStyle('background-image', "url('" + base + "img/smart-enquiry/error-background.gif')");
					messageBox.inject($('contact-form'), 'top');    
						
					if (json.errors) {
						var errors = json.errors;
						var errorList = "";
						$each(errors, function(type, value) {
							errorList += '<li>' + type.enquiry_error + '</li>';
						});
						messageBox.set('html','<a href="#" id="close-button"></a><h1>OOPS!</h1><ul>' + errorList + '</ul>');
					} else {
						messageBox.set('html','<a href="#" id="close-button"></a><h1>OOPS!</h1><p>An unknown error occured. Please try again</p>');
					}

					$('close-button').addEvent('click', function(e) {

						e.preventDefault();
						
						bounceFade.options.transition = Fx.Transitions.Sine;
						bounceFade.options.duration = 200;
						
						bounceFade.start({
							'opacity':0,
							'margin-top' : 0
						}).chain(function(){
							messageBox.destroy();
							fade.start({
								'opacity':0
							}).chain(function() {
								overlay.destroy();
							});
						});
					});					

					bounceFade.start({
						'opacity':1,
						'margin-top' : middley
					});
					
				
	            } else {

	            	if (json.status == 1) {
	            		
		            	messageBox.setStyle('background-image', "url('" + base + "img/smart-enquiry/thanks-background.gif')");
						messageBox.inject($('contact-form'), 'top');    

						messageBox.set('html','<div style="height: 30px"></div><h1>THANK YOU!</h1><p>We have received your message. One of our team will be in touch shortly.</p>');
						
						bounceFade.start({
							'opacity':1,
							'margin-top' : middley
						});	            		

						// Fade out 
						(function() { // null function so we can apply the delay method

							bounceFade.options.transition = Fx.Transitions.Sine;
							bounceFade.options.duration = 200;
							
							bounceFade.start({
								'opacity':0,
								'margin-top' : 0
							}).chain(function(){
								fade.start({
									'opacity':0
								}).chain(function() {
									overlay.destroy();
								});
							});
						}).delay(5000);						
	            	}
	            }
			},
			url       : base + 'ajax.php',
	        noCache   : true

	    }).send(this);    
    });
    
});

function isEmail(address) {
    var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
    if(reg.test(address) == false) {
        return false;
    } else {
        return true;
    }   
}