//************** CONSOLE FIX ***************//
// stops console.log triggering errors in ie
//***************************************//


if (!window.console || !console.firebug)
{
    var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml",
    "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];

    window.console = {};
    for (var i = 0; i < names.length; ++i)
        window.console[names[i]] = function() {}
}

var Validation = new Class({
	//optional settings (Events may be required)
	Implements: [Options, Events],
	options: {
		form_id:"contact",
		base_url:"http://www.computeach.co.uk/enquiry-form-submit"
	},
	
	//init actions
	initialize: function(options){	
		
		//apply options
		this.setOptions(options);
		
		//init ajax_handler_obj
		this.ajax_call=this.ajax_handler_obj();
		
		form_submitted=false;
		
		//catch form submit press
		$(this.options.form_id).addEvent('submit', function(event){
			
			//console.dir(event);
			
			event.stop();
			//create new array with data from input, textarea and select elements
			req_array = new Array();
			$(this.options.form_id).getElements('input, textarea, select').each(function(item, index){
				if(item.get('type')=="radio"){
					if(item.get('checked')==true){
						req_array[index] = item.get('name')+'='+item.get('value');	
					}
				}else{
					//build validation query
					req_array[index] = item.get('name')+'='+item.get('value');
				}
			});
			
			//join the array back into a get string
			req_array=req_array.join("&");
			
			//send everything to ajax handler
			this.ajax_call.send('mode=AJAX&'+req_array);
			
			if($('success'))
			{
				$('success').dispose();
			}
			
			
			
		}.bind(this));
		
		$('submit_btn').addEvent('mousedown', function(event){ form_submitted = true; });
		
		$(this.options.form_id).getElements('input, textarea, select').each(function(item, index){
			req_str="";
			
			
			
			item.addEvent('blur', function(event){
				//alert("blur");
				//console.dir(event);
				
				
				
				if(item.get('type')=="radio"){
					if(item.get('checked')==true){
						req_str = item.get('name')+'='+item.get('value');	
					}
				}else{
					//build validation query
					req_str = item.get('name')+'='+item.get('value');
				}
				
			
			function fire_ajax_call()
			{
				if(form_submitted == false)
				{
					this.ajax_call.send('mode=AJAX&submitted=1&blur=1&'+req_str);
				}
				else
				{
					form_submitted=false;
				}
			}
			
			fire_ajax_call.delay(200, this);
			
			}.bind(this))
		
				
			item.addEvent('focus',function(event){
				
				//console.dir(event);
				
				if(item.getPrevious('div.bubble-error').getStyle('display')=='block'){
						var reHideFx = new Fx.Morph(item.getPrevious('div.bubble-error'),{
							onComplete:function(){
								this.element.setStyle('display', "none");
							}
						})
						reHideFx.start({
							 "opacity":0					   
			  			 });				
				}
				
				if($('success'))
				{
					$('success').dispose();
				}
				
			}.bind(this))
			
		}.bind(this))
		
	},	
	ajax_handler_obj:function()
	{
		//setup global ajax object              
		this.ajaxRequest = new Request(
		{
			url: this.options.base_url,
			method:'post',
			onSuccess:function(responseText, responseXML)
			{
				
				errors_found = 0;
				//decode the result
				var ajax_result = JSON.decode(responseText);

				
				//console.dir(ajax_result);
				
				for (k in ajax_result.errors)
				{
					if (ajax_result.errors.hasOwnProperty(k))
					{						
					//console.log(k);
					//console.log(ajax_result[k]);
					var error_block = $(k).getPrevious('div.bubble-error');
					error_block.getElement("div.bubble-error-middle").set("text",ajax_result.errors[k]);
					//error_block.setStyle("display","block");
					var showFx = new Fx.Morph(error_block);
					showFx.start(
					{
						"opacity":1,
						"display":"block"						   
					});
					
					
					
						
					errors_found++;
					}
				}
				
				if(errors_found == 0 && ajax_result.type == "submit"){					

					if( ajax_result.vars )
					{
						//console.dir(ajax_result.vars);
						var GET_str = "?";

						
						GET_str += "id="+ajax_result.vars.id+"&email="+ajax_result.vars.email;


						//console.log(GET_str);
					}

					$(this.options.form_id).reset();
					
					new Fx.Scroll(window, {
                        offset: {
                            'x': 0,
                            'y': 0
                        },
						onComplete:function(){
							window.location = "\/confirm-details";							
							//Sexy.alert('<h2>Thank You</h2><p>Your details have been submitted and we will be in touch with you shortly</p><iframe border="0" style="border-width: 0;" src="/tracking/callback-tracking-code.php'+GET_str+'" width="1" height="1"></iframe>');
						}
                    }).toTop();		
				}
				
			}.bind(this),//changes the scope of the onSuccess handler to class scope
			
			onFailure:function()
			{
				alert("FAIL");
			}
			
			
			
		});
		return this.ajaxRequest;
	}
	

});

window.addEvent('domready', function(){
	Sexy = new SexyAlertBox();							 
	var Validate = new Validation();
	
	/*
	$('Callback').addEvent("click",function(event)
	{
		if(!event.target.get("checked"))
			event.target.setProperty('value', 'false');
		else
			event.target.setProperty('value', 'true');
	});
	
	$('Brochure').addEvent("click",function(event)
	{
		if(!event.target.get("checked"))
			event.target.setProperty('value', 'false');
		else
			event.target.setProperty('value', 'true');
	});
	*/
	
	//hide error messages
	$$("div.bubble-error").each(function(item,index){
		var hideFx = new Fx.Morph(item);
		hideFx.set({
				   "opacity":0,
				   "display":"none"						   
				   });			
	})
	
	 
})