/**
 * Compatible with Form Validator built-in Joomla
 */
if(typeof(jQuery) != "undefined" && $===jQuery){
	jQuery.noConflict();
}
	var ajaxModule = new Class({
	
		 setOptions: function(options){
			this.options = {
				suffix:	 		'',
			submitUrl:	 	'',
			useFX:		 	0,
			useAjax:	 	1,
			hideCharCount:	0,
			logFX:			0,
			redirectURL:	'',
			clearform:		9999999999,
			log:	 		'log',
			frm:	 		'',
			textField:		'text',
			msgDisplayMethod: 		'inline',
			googleConversionEnabled:	0,
			lang: {
				invalid:			'There are some invalid fields, please check fields in red',
				reachMaxCharacters:	'You have reached the maximum limit of characters allowed'
				}
		};
		Object.extend(this.options, options || {});
  },
 
		
  	initialize: function(options){
		this.setOptions(options);
	  	if(this.options.useFX){
	  		this.options.logFX	= new Fx.Slide(this.options.log); 
	  		this.options.logFX.toggle();
	  		
	  	}
	  	if(this.options.useAjax){
	  		this.attachEventToForm(options);
	  	}
	  	if(this.options.hideCharCount != 1){
	  		this.attachEventToTextfield(this.options);
	  	}
  		
	  	this.attachEventToSubmitButton();
	},
	
	setLogRes:function(txt, cls,slideIn){
		if(this.options.msgDisplayMethod == 'alert'){
			if(txt.length>1) alert(txt);
		}else{
			var obj	= $(this.options.log);
			obj.removeClass('error');
			obj.removeClass('success');
			obj.removeClass('ajax-loading');
			obj.addClass(cls);
			obj.setHTML(txt);
			if(slideIn == true && this.options.useFX){
				this.options.logFX.slideIn();
			}
		}
	},
	attachEventToSubmitButton:function(){
		var obj	= this;
		if(document.formvalidator){
			// Iterate through the form object and attach the validate method to all input fields.
			$A($(this.options.frm).elements).each(function(el){
				el = $(el);
				if ((el.getTag() == 'input' || el.getTag() == 'button') && el.getProperty('type') == 'submit') {
					if (el.hasClass('validate')) {
						el.onclick = function(){
							if(!document.formvalidator.isValid($(obj.options.frm))){
								obj.setLogRes(obj.options.lang.invalid, 'error', true);
								return false;
							}else{
								return true;
							}
						};
					}
				}
			});
		}
	},
	attachEventToForm:function(options){
		var obj	= this;
		$(this.options.frm).addEvent('submit', function(e) {
			new Event(e).stop();
			obj.setLogRes('','ajax-loading',true);
			//window.loadFirebugConsole();
			//build the request
			var jSonRequest = new Json.Remote(options.submitUrl, {onComplete: function(response){
				obj.setLogRes(response.msg,response.action,true);
					//did it return as good, or bad?
					if(response.action == 'success'){
						if(obj.options.googleConversionEnabled == 1){
							obj.googleConversion(options.submitUrl);
						}
						if(typeof(pageTracker) != 'undefined'){
							pageTracker._trackPageview('/ajaxcontactform_submitted');
						}
						if(obj.options.redirectURL != ''){
							window.location=obj.options.redirectURL;
						}else{
							(function(){ if(!window.ie){$(obj.options.frm).reset();}}).delay(obj.options.clearform);
							if(obj.options.useFX){
								obj.options.logFX.hide();
								obj.options.logFX.slideIn();
								(function(){obj.options.logFX.slideOut();}).delay(obj.options.clearform);
						  	}
						}
					}
					//reload captcha
					if(typeof(Recaptcha) != "undefined"){
						Recaptcha.reload();
					}else if(typeof(updateCaptcha) != "undefined"){
						updateCaptcha();
					}
				}
			}).send(obj.toJsonString($(obj.options.frm)));					
		});
	}, 
	
	attachEventToTextfield:	function(options){
		var maxlen = parseInt($('maxlen'+options.suffix).value);
		var obj 	= this;
		
		$(this.options.textField).addEvent('keyup', function(e) {
			new Event(e).stop();
			var fieldLength = this.value.length;
			
			if(fieldLength >= maxlen && maxlen > 0){
				obj.setLogRes(options.lang.reachMaxCharacters,'error',true);
				this.value = this.value.substring(0, maxlen);
			}else if(fieldLength <= (maxlen -1)){
				if(options.useFX){
					options.logFX.slideOut();
			  	}
			}
			$('limit_chars'+options.suffix).setText( (maxlen - fieldLength) );
		});
	},
	
	toJsonString:	function(frm){
		var jsonString = [];
		frm.getFormElements().each(function(el){
			var name = el.name;
			var value = el.getValue();
			if (value === false || !name || el.disabled) return;
			var qs = function(val){
				//if is an array
				if(name.indexOf('[') > 0 && name.indexOf(']') > 0){
					var fields = document.getElementsByName(name);
					var fieldValue	= '';
					name= name.replace('[','');
					name= name.replace(']','');
					for(var i=0; i<fields.length; i++){
						if(fields[i].checked == true){
							if(fieldValue.length < 1){
								fieldValue = fields[i].value;
							}else{
								fieldValue = fieldValue+', '+fields[i].value;
							}
						}
					}
					value	= fieldValue;
				}
				value = encodeURIComponent(value);
				jsonString.push(Json.toString(name) + ':' + Json.toString( encodeURIComponent(value) ));
			};
			if ($type(value) == 'array') value.each(qs);
			else qs(value);
		});
		return ('{' + (jsonString.join(',')) + '}');
	},
	googleConversion: function(url) {
		var iframe = document.createElement('iframe');
		iframe.style.width = '0px';
		iframe.style.height = '0px';
		document.body.appendChild(iframe);
		iframe.src = url+'&task=googleconversion';
	}
});
ajaxModule.implement(new Options);
