/// <reference path="jquery.intellisense.js"/>
/// <reference path="common.js" />
var formchanged = false;

var FormSettings = {
    defaultValidateSettings: {
        ignore: '.ignore',

        showErrors: function (errorMap, errorList) {

            if (errorList.length) {
                var $form = $(this.currentForm);
                var hasFields = ($form.attr('hasfields') || "").toLowerCase() == 'true';
                var hasTabs = ($form.attr('hastabs') || "").toLowerCase() == 'true';

                function checkExpandGroupFields($elem) {
                    if (hasFields) {
                        var $childfields = $elem.closest('.childfields');
                        if ($childfields.length && !$childfields.is(':visible')) {
                            var $field = $childfields.closest('.field');
                            expandGroupElement($field.find('.field-group-label:first > .expand-group-element'), true);
                            checkExpandGroupFields($field);
                        }
                    }
                }

                if (hasTabs) {
                    var tabId = '';
                    var setTabFunc = $form.attr('customsettab') || 'setTab';

                    function executeFunctionByName(functionName, context, $form, tabName) {
                        if (functionName == 'setTab') {
                            window[functionName](tabName);
                            return;
                        }
                        try{
                            //var args = Array.prototype.slice.call(arguments, 2);
                            var namespaces = functionName.split(".");
                            var func = namespaces.pop();
                            for (var i = 0; i < namespaces.length; i++) {
                                context = context[namespaces[i]];
                            }
                            return context[func].call(context, $form, tabName);
                        }
                        catch (ex) {
                            alert('System error: ' + ex);
                        }
                    }

                    $.each(errorList, function (i, v) {
                        if (i == 0) {
                            tabId = $(v.element).closest('.tab').attr('id');
                            executeFunctionByName(setTabFunc, window, $form, tabId);
                            checkExpandGroupFields($(v.element));
                        }
                        else {
                            var tab = $(v.element).closest('.tab');
                            if (tab.attr('id') == tabId) {
                                checkExpandGroupFields($(v.element));
                            }
                        }
                    });
                }
                else {
                    $.each(errorList, function (i, v) {
                        if (hasFields) {
                            checkExpandGroupFields($(v.element));
                        }
                    });
                }
            }

            this.defaultShowErrors();
        }
    }
}

$(function() {
    //if closeaftersave defined - close form
    if ($('#postback').length > 0) {
        //alert('postback');
        try { if (afterSave) { afterSave(); } } catch (e) { }
        //try { afterSave(); } catch (e) { alert('notAfterSave!'); }
        if ($('#closeaftersave').val() == 'true') self.close();
    }

    //validate form first time to initialize validator
    if ($('form').size()) {
        var validateSettings = $.extend({}, FormSettings.defaultValidateSettings);
        if (typeof window["formAfterSubmit"] == 'function'){
            validateSettings['submitHandler'] = formAfterSubmit;
        }

        $('form').validate(validateSettings);
    }
    $('.validate input:not(.js-enter-handler)').keydown(function (e) { if (e.keyCode == 13) { formchanged = true; return false; } });
    //$('textarea').keydown(function(e) { if (e.keyCode == 27) { return false; } });

    if ($.browser.msie && $.browser.version < 8) { $('label.required').append('<span class="red">*</span>'); }

    $('input,textarea,select').change(function() { formchanged = true; });
    if ($('#focus').val() == null || $('#focus').val() == '')
        $('input:text:visible:enabled:not(.dateTime)').first().focus();
    $('.save').attr("title", "[ctrl+s]");
    $('.saveandreturn[data-isstatusbutton!=1]').attr("title", "[ctrl+shift+s]");
    $('.return').attr("title", "[esc]");

    if ($('#tab').val()) setTab($('#tab').val());
});

function findTab(field) {
    var prt = field.parentNode;
    while(prt != null)
    {
        if( $(prt).hasClass('tab') ) return prt.id;
        else prt = prt.parentNode;
    }
}

function closeForm(url) {
    if (formchanged == true && !confirm(FormResources.FormChanged)) return;
    if (url == 'close') {
        self.close();
        return;
    }
    
    if (url) {
        document.location.href = url;
        return;
    }
    
    var f = $('form:first');
    var action = f.attr('action');
    var controller = action.substr(0, action.indexOf('/'));
    var href = base + controller + '/list';   
    //проверим страницу, с которой пользователь действительно пришел
    /*if (document.referrer && document.referrer!=document.location.href) {
        href = document.referrer;
    }*/
    document.location.href = (href);
    return;
}

function recheckServices() {
    var handler = $("#listTree");

    var checked = $(this).attr("checked");
    var value = $(this).attr("value");

    if (checked) {
        handler.find("input[value^='" + value + "']").each(function () {
            $(this).attr('checked', 'checked');
            $(this).parent().removeClass("notFull");
        });

        $("#listServicePath").find("option[value^='" + value + "']").attr('selected', 'selected');
    } else {
        if (value.split('|').length > 1) {
            var pvalue = "";

            $.each(value.split('|'), function () {
                pvalue += (this + "|");

                if (pvalue != value) {
                    var el = handler.find("input[value='" + pvalue + "']:checked");
                    if (el.length)
                        el.parent().addClass("notFull");
                }
            });
        }
        handler.find("input[value^='" + value + "']").each(function () {
            $(this).removeAttr('checked');
            $(this).parent().removeClass("notFull");
        });

        $("#listServicePath").find("option[value^='" + value + "']").removeAttr('selected');
    }

    $("#listServicePath").trigger("change");
}

function expandGroupElement(link, forceShow) {
    var $link = $(link);
    var targetId = $link.attr('data-target');
    var $target = $('#' + targetId);
    var $img = $(link).find('img');
    var show = (forceShow != undefined && forceShow) || !$target.is('[group-expanded]');
    if (show) {
        $target.attr('group-expanded', true);
        $img.attr('src', 'img/tree/minus.gif');
        $target.show();
    }
    else {
        $target.removeAttr('group-expanded');
        $img.attr('src', 'img/tree/plus.gif');
        $target.hide();
    }

    return false;
}