/*
	Stempora Web Framework
	Copyright (c) 2002-2018 Stempora. 
	All rights reserved.
		web:  www.stempora.com
		mail: support@stempora.com				
*/

var STBGlobalForms = Object.create(STBModule.prototype);

STBGlobalForms.name = "GlobalForms";

STBGlobalForms.initCaptcha = function() {
    var parseCaptcha = function (e) {
        try {
            e.preventDefault();

            var obj = jQuery(this);

            obj.parent().find("input[name=image_code]").val("");
            obj.find("img").attr("src", obj.attr("href") + "?code=" + obj.attr("data-code") + "&t=" + jQuery.now());
        } catch (e) {
            getStack(0, e);
        }
    };

    jQuery(document).on("click", ".form-item-captcha-img", parseCaptcha);
}


STBGlobalForms.initAjax = function() {

	var ajaxForm = false,
        parseAjax = function (e) {
            try {
                e.preventDefault();

                var form = jQuery(this);
                var parent = form.closest(".form");
                var firstError = true;
                var responsebox = form.find(".responsebox");

                //if already sent the info do nothing
                if (form.hasClass("__working")) {
                    return true;
                }

                if (ajaxForm) {
                    ajaxForm.abort();
                }

                form.addClass("__working");

                var labelWidth = 0;
                var dir = jQuery("html").attr("dir");

                if (parent.hasClass("form-label-option"))   {
                    labelWidth = form.find(".form-line .form-line-group-label").first().outerWidth();
                } 

                //remove all errors
                
                form.find(".form-line-error").slideUp(function() {jQuery(this).remove(); });
                form.find(".form-line.error").removeClass("error");
                responsebox.find(".alert").slideUp(function() {jQuery(this).remove(); });
                

                //add sending data if exists
                if (typeof form.attr("data-sending") != "undefined") {
                    if (form.attr('data-sending') != "") {
                        responsebox.html('<div class="alert alert-loading alert-sending"><p>' + form.attr('data-sending') + '</p></div>');
                    }
                }


                ajaxForm = jQuery.ajax({
                    url: form.attr("action"),
                    type: form.attr("method"),
                    data: form.serialize()
                }).done(function (msg) {
                    try {
                        STBGlobalForms.formParseResponse(form , msg );
                    } catch (e) {
                        getStack(0, e);
                    }
                }).error(function (obj, status , error) {
                    form.removeClass("__working");
                    responsebox.html('<div class="alert alert-danger"><p>' + error + '</p></div>');                 
                });

            } catch (e) {
                getStack(0, e);
            }
        };

    jQuery(document).on(
		"submit", 
		"form.ajax", 
		parseAjax
	);

    jQuery(document).on(
		"click", 
        ".form-line.error", 
        function() { 
            jQuery(this).removeClass("error");

            var alert = jQuery(this).find(".form-line-error");
            if (alert.length != 0) {
                alert.slideUp(function() { alert.remove(); });
            }
        }
    );
}


STBGlobalForms.formBuilderSelector = function () {
	var forms = jQuery(".form-types:not(.__done_selector)");

	if (forms.length){
		forms.each(function(e) {

			var form	= jQuery(this),
				lines	= form.find("[data-groups]"),
				types	= form.find("input[name='type']"),
				type	= form.find("input[name='type']:checked").val();

			if (types.length) {
				
				lines.each(function() {
					var grp = jQuery(this).attr("data-groups"),
						line = jQuery(this);
					
					line.addClass("type-line");

					if (grp != undefined) {
						var groups = grp.split(",");
						
						for (i in groups) {
							line.addClass("type-" + groups[i]);
						}

					} else {
						line.addClass("type-all");
					}
				});

				form.find(".type-line:not(.type-all):not(.type-" + type +")").hide();
				form.find(".type-line.type-all, .type-line.type-" + type +"").show();
			}

			types.click(function(e) {

				var form = jQuery(this).closest(".form-types"),
					type = jQuery(this).val();

				form.find(".type-line:not(.type-all):not(.type-" + type +")").hide();
				form.find(".type-line.type-all, .type-line.type-" + type +"").show();

			});

			jQuery(this).addClass("__done_selector");
		});
	}

}

STBGlobalForms.formFieldsType = function () {

	var forms = jQuery(".form:not(.__done)");

	if (forms.length) {
		forms.each(function() {

			var form = jQuery(this);

			if (form.hasClass("form-placeholder")) {
			} else {

				//remove placeholder
				form.find("[placeholder]").removeAttr("placeholder");
				//remove data-placeholder from selects
				form.find("select").attr("data-placeholder", "");
			}

			if (form.hasClass("form-label-option")) {

				var max = 0,
					moreMax = form.hasClass("form-label-option-no-box") ? 15 : 5,
					lineGroup = form.find(".form-line-group-label"),
					i = 0;

				for (i; i < lineGroup.length; i++) {
					var onObj = jQuery(lineGroup[i]),
						onObjWidth = onObj.width();

					max = (onObjWidth > max ? onObjWidth : max);
				}

				var finalMax = max + moreMax;

				lineGroup.width(finalMax);

				
				if (form.hasClass("form-label-option"))	{

					var spc = 16;

					if (form.hasClass("form-label-option-no-box")) {
						spc = 26;
					}

					if (jQuery("html").attr("dir") == "rtl") {
						lineGroup.siblings(".icon").css("right" , finalMax + spc);
					} else {
						lineGroup.siblings(".icon").css("left" , finalMax + spc);
					}
				}
			} else {
				form.find(".form-line-group-label").remove();
			}

			form.addClass("__done");

		});
	}
}

STBGlobalForms.resizeErrorMessages = function () {
	var elements = jQuery(".form-line-error");

	if (elements.length) {
		elements.each(function() {
			var el = jQuery(this);			
			el.css(
				"width" , 
				parseInt(el.siblings(".form-line-group").outerWidth())
			);
		});
	}
}


/*no ussage ???*/
STBGlobalForms.formFieldError = function(form , field , msg , firstError) {

	var dir = jQuery("html").attr("dir"),
        labelWidth = 0,
		fieldContainer = form.find(".form-line-" + field + "");

	firstError = firstError || "false";
            
    if (parent.hasClass("form-label-option"))   {
        labelWidth = form.find(".form-line .form-line-group-label").first().outerWidth();
    }

	fieldContainer.append(
		'<div data-scroll="' + firstError + '" ' + 
		'class="form-line-error" ' + 
		'style="' + (dir == 'rtl' ? 'padding-right' : 'padding-left') + ':' + labelWidth + 'px;display: none;">' + 
			'<div class="alert alert-danger"><p>' + msg + '</p></div>' + 
		'</div>');
	
	fieldContainer.addClass("error");

	var el = fieldContainer.find(".form-line-error");

	el.css("width" , parseInt(el.siblings(".form-line-group").outerWidth()));

	el.slideDown(function() {
		if (jQuery(this).attr("data-scroll") == "true") {
		}
	});
}


/*will be depcreacted soon, need to check if i use it anywhere*/
STBGlobalForms.parseAjaxResponse = function(form , msg) {
	var responsebox = form.find(".responsebox");

	if (msg.indexOf("redirect:") != -1) {
		window.location.href = msg.replace("redirect:", "");

	} else {
		//capcha reload
		if (msg.indexOf("captcha:") != -1) {

			if (jQuery(".g-recaptcha").length) {
				//grecaptcha.reset(); // ??? cine e grecaptcha
				//Recaptcha.reload();
			} else {
				form.find(".form-item-captcha-img").trigger("click");
			}

			responsebox.html(msg.replace("captcha:", ""));

		} else {
			//execute function
			if (msg.indexOf("execute:") != -1) {
				eval(msg.replace("redirect:", ""));

			} else if (msg.indexOf("reset:") != -1) {
				//reset this form
				form.find('input:text, input:password, input:file, select, textarea').val('');
				form.find('input:radio, input:checkbox').removeAttr('checked').removeAttr('selected');
				jQuery(".form-capcha-img").trigger("click");
				//form[0].reset();

				//show the message
				responsebox.html(msg.replace("reset:", ""));
			} else {
				//full message
				responsebox.html(msg);
			}
		}
	}
}

STBGlobalForms.parseJsonResponse = function(form , msg) {

	var responsebox = form.find(".responsebox"),
        firstError = true,
        dir = jQuery("html").attr("dir");

	if (form.find(".form-item-captcha-img").length){
		form.find(".form-item-captcha-img").trigger("click");                               
	}

	if (msg.html.length) {

		if (msg.popup == "1")   {
			ShowPopup(msg.html , "center" , msg.popupbtn , true );
			responsebox.html("");
		} else {
			responsebox.html(msg.html);
		}
	} else {
		responsebox.html("");
	}

	if (msg.fields != null) {

		for (i in msg.fields){

			switch (msg.fields[i]) {
				case "image_code":
					if (jQuery(".g-recaptcha").length) {
						//grecaptcha.reset(); // ??? cine e grecaptcha
						//Recaptcha.reload();
					} else {
						form.find(".form-item-captcha-img").trigger("click");
					}
				break;                                  

				case "__global":
					responsebox.html(responsebox.html() + '<div class="alert alert-danger"><p>' + msg.message[msg.fields[i]] + '</p></div>');
				break;

			}

			if (msg.fields[i] != "__global"){
			
				if (msg.message != null){ 
					if (typeof msg.message[msg.fields[i]] != "undefined"){
						STBGlobalForms.formFieldError(form , msg.fields[i] , msg.message[msg.fields[i]], firstError);
					}
				}

				firstError = false;
			}

		}


	}

	if (msg.redirect != null ) {
		//redirect with delay
		if (msg.wait.length) {
			setTimeout(function() { window.location.href = msg.redirect; }, msg.wait);
		} else {
			window.location.href = msg.redirect;
		}                               
	}

	if (msg.reset == "true") {
		//reset this form
		form.find('input:text, input:password, input:file, select, textarea').val('');
		form.find('input:radio, input:checkbox').removeAttr('checked').removeAttr('selected');
		form.find("select").prop('selectedIndex',0);

		jQuery(".form-capcha-img").trigger("click");
	}


	if (msg.script != null) {
		eval(msg.script);
	}

}


STBGlobalForms.formParseResponse = function(form , msg ) {
    form.removeClass("__working");

    var responsebox = form.find(".responsebox"),
        firstError = true,
        dir = jQuery("html").attr("dir"),
        parent = form.closest(".form"),
        labelWidth = 0;
            
    if (parent.hasClass("form-label-option"))   {
        labelWidth = form.find(".form-line .form-line-group-label").first().outerWidth();
    } 

    if (form.hasClass("json"))  {
		STBGlobalForms.parseJsonResponse(form , msg);		
    } else {
		STBGlobalForms.parseAjaxResponse(form , msg);		
    }

	setTimeout(function() {
		var nice = form.closest(".nice-scroll");
		if (nice.length){
			nice.getNiceScroll().resize(); 
		}
	} , 500);
}

STBGlobalForms.runOnReady = function() {
	STBGlobalForms.initCaptcha();
	STBGlobalForms.initAjax();
	STBGlobalForms.formBuilderSelector();
	STBGlobalForms.formFieldsType();
}

STBGlobalForms.runOnContentUpdate = function() {
	STBGlobalForms.formBuilderSelector();
	STBGlobalForms.formFieldsType();
}


STBGlobalForms.runOnResize = function() {
	STBGlobalForms.resizeErrorMessages();
}

site.registerModule(STBGlobalForms);



