/**
 * @name jQuery simpleAjax
 * @author Rifat Çağrı Ekin <cagri.ekin@gmail.com>
 */

(function( $ ){
	$.fn.simpleAjax = function(options) {

		var defaults = {

		};
		var options = $.extend(defaults, options);

		return this.each(function() {

			if(options.errorMessages == "inline"){
				$(this).find("input,textarea").each(function(){
					$(this).attr('firstval',$(this).val());

					$(this).on("focusin.simpleAjax",function(){
						if($(this).attr('tempval')){
							if($(this).attr('tempval') == $(this).attr('firstval')) $(this).val('').text('').removeClass('inlineFormError');
							else $(this).val($(this).attr('tempval')).text($(this).attr('tempval')).removeClass('inlineFormError');
						}
						else if($(this).val() == $(this).attr('firstval')) $(this).val('').removeClass('inlineFormError');
					});
					$(this).on("focusout.simpleAjax",function(){
						if($(this).val() == '' && $(this).text() == '') $(this).val($(this).attr('firstval')).text($(this).attr('firstval'));
					});
				});
			}
			else{
				$(this).find("input,textarea").each(function(){
					$(this).bind("focus.simpleAjax",function(){
						$(this).parent().next(".error").fadeOut("fast",function(){
							$(this).remove();
						});
					});
				});
			}

			$(this).submit(function(){
				$(this).find(".error").each(function(){
					$(this).fadeOut("fast",function(){
						$(this).remove();
					});
				});

				var form = $(this);
				var debug = $(this).attr("debug");

				$.ajax( {
					url : form.attr("action"),
					data : form.serialize(),
					beforeSend : function(httpreq) {
						form.find("input[type='submit']").fadeOut();
						form.find(".ajaxload").fadeIn();
					},
					complete : function() {
						form.find(".ajaxload").fadeOut();
						form.find("input[type='submit']").fadeIn();
					},
					success : function(data) {

						if (data && data != "parsererror") {
							if (data.error == "false"){
								if(data.formErrors){
									if(options.errorMessages == "inline"){
										$.each(data.formErrors,function(i,el){
											form.find("[name='"+i+"']").attr('tempval',form.find("[name='"+i+"']").val()).val(el).text(el).addClass('inlineFormError');
										});
									}
									else{
										$.each(data.formErrors,function(i,el){
											form.find("[name='"+i+"']").parent().after("<div class=\"error\">"+ el +"</div>").fadeIn();
										});
									}

								}
								else{
									form.slideUp();
									form.next(".success").slideDown();
								}
							}
							else ajaxerror(data.errorText);
						}
						else ajaxerror("ajax error");

					}
				});
				return false;
			});
		});
	};
})( jQuery );

function ajaxerror(error){
	if(window.console) console.warn(error);
}
