$(document).ready(function() {

	$(document).on(
		"click" , 
		".form-item-captcha-img",
		function(e) {
			e.preventDefault();

            var obj = $(this);

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

	$(document).on(
		"click" , 
		"alert",
		function(e) {
			$(this).slideUp();
		}
	);




	$('.form .form-item').placeholder();

function formParseResponse(form , msg ) {
    form.removeClass("working");

    var responsebox = form.find(".responsebox"),
        firstError = true,
        dir = $("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"))  {
        
        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) {
            if (form.find(".form-item-captcha-img").length){
                form.find(".form-item-captcha-img").trigger("click");                               
            }

            for (i in msg.fields){

                switch (msg.fields[i]) {
                    case "image_code":
                        if ($(".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"){
                
                    //add the error code
                    form.find(".form-line-" + msg.fields[i]).addClass("error");

                    //check if has extra errors 

                    if (msg.message != null){ 
                        if (typeof msg.message[msg.fields[i]] != "undefined"){
                            form.find(".form-line-" + msg.fields[i] + "").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.message[msg.fields[i]] + '</p></div>' + 
                                '</div>');
                            
                            var el = form.find(".form-line-" + msg.fields[i] + " .form-line-error");

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

                            el.slideDown(function() {

                                if ($(this).attr("data-scroll") == "true") {


                                    //$('html, body').animate({
                                    //  scrollTop: ($(this).closest(".form-line").offset().top - 100)
                                    //});
                                }
                            });
                        }
                    }

                    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);

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


        if (msg.script != null) {

            eval(msg.script);
        }

    } else {

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

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

                if ($(".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');
                    $(".form-capcha-img").trigger("click");
                    //form[0].reset();

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


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

                var form = $(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 = $("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() {$(this).remove(); });
                form.find(".form-line.error").removeClass("error");
                responsebox.find(".alert").slideUp(function() {$(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 = $.ajax({
                    url: form.attr("action"),
                    type: form.attr("method"),
                    data: form.serialize()
                });

                var onDone = function (msg) {
                    try {
                        formParseResponse(form , msg );
						setTimeout(function() {
							$('.contact-side-content').getNiceScroll().resize(); 
						} , 1000);
                    } catch (e) {
                        getStack(0, e);
                    }
                };


                var onError = function (obj, status , error) {
                    form.removeClass("working");
                    responsebox.html('<div class="alert alert-danger"><p>' + error + '</p></div>');                 
                }
                ajaxForm.done(onDone);
                ajaxForm.error(onError);

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

    $(document).on("submit", "form.ajax", parseAjax);
    $(document).on("click", 
        ".form-line.error", 
        function() { 
            $(this).removeClass("error");

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


function runForms() {
    try {
        //set label width
        var parseOption = function () {

            var obj = $(this),
                max = 0,
                moreMax = 10,
                lineGroup = obj.find(".form-line-group-label"),
                lineGroupLnt = lineGroup.length,
                i = 0, 
				form = obj.closest(".form");

            for (i; i < lineGroupLnt; i++) {
                var onObj = $(lineGroup[i]),
                    onObjWidth = onObj.outerWidth();

                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 ($("html").attr("dir") == "rtl") {
					lineGroup.siblings(".icon").css("right" , finalMax + spc);
				} else {
					lineGroup.siblings(".icon").css("left" , finalMax + spc);
				}
			}
        };

        $(".form-label-option").each(parseOption);

        //replace placeholder
        var formNotPlaceholder = $(".form:not(.form-placeholder)");
        formNotPlaceholder.find("[placeholder]").removeAttr("placeholder");
        formNotPlaceholder.find("select").attr("data-placeholder", "&nbsp;");
        $(".form:not(.form-label-option)").find(".form-line-group-label").remove();


        //on change select redirect
        var onChSelRedirect = function () {
            window.location.href = $(this).find("option:selected").attr("data-link");
        };

        $("select[data-click=true]").on('change', onChSelRedirect);


        //change value select
        var setValue = function () {
            var obj = $(this);
            obj.val(obj.attr("data-selected"));
        };

        $("select[data-selected]").each(setValue);



    } catch (e) {
        getStack(0, e);
    }
    //$('.form .form-item').placeholder();
}


	function resizeErrorMessages() {
		$(".form-line-error").each(function() {
			var el = $(this);
			
			el.css("width" , parseInt(el.siblings(".form-line-group").outerWidth()));
		});
	}

	$(window).on('resize', resizeErrorMessages);

runAjax();
runForms();


});


