$(function(){

    /*
     * Vizszintes menu
     */
    $("#h_menu ul li[class!='active']:gt(0)").bind("mouseover mouseout click", function(event){
        if (event.type == 'mouseover') {
            $(this).addClass("active");
        }
        if (event.type == 'mouseout') {
            $(this).removeClass("active");
        }
        if (event.type == 'click') {
            document.location = $(this).find("a").attr("href");
        }
    });
    
    /**
     * Azonosito szerinti kereses
     * @note Kicsit hackes, mivel szarul tordeltek
     */
    var $idSearchForm = $(".bal_panel form[name='id-search']");
    $idSearchForm.submit(function() {
        if ($(this).find("input").val()) {
            document.location = '/hirdetes/' + $(this).find("input").val();
        }
        return false;
    });
    $idSearchForm.find(".kereses_gomb").click(function() {
        $idSearchForm.submit();
    });

    /*
     * Bejelentkezes
     */
    $("form[name='login']").submit(function() {
        $status = $(".status");
        $submit = $(this).find("input[type='submit']");
        $status.html('Adatok ellenőrzése...<img src="/img/indicator.gif" alt="" />');
        $.post("/login", $(this).serialize(), function(result) {
            var data = $.parseJSON(result);
            if (typeof(data.error) != 'undefined') {            
                $status.html($('<div class="error">' + data.error + '</div>'));
                $submit.val('Újra');
            } else {
                $status.html('Bejelentkezés folyamatban...');
                $submit.val('Kérem várjon...');
                document.location.reload(true);
            }
        });
        return false;
    });
    
    $("form[name='mini-login']").submit(function() {
        $submit = $(this).find("input[type='submit']");
        $.post("/login", $(this).serialize(), function(result) {
            var data = $.parseJSON(result);
            if (typeof(data.error) == 'undefined') {
                $submit.val('Belépés folyamatban...');
                document.location = '/office';
            } else {
                alert(data.error);
                document.location = '/office'
            }
        })
        return false;
    })

    $("form .unfilled").live("change", function() {
        $(this).removeClass("unfilled");
    })

});

function countyChange(countyId, settlement, callback) {
        if ( !countyId ) {
            settlement.html('<option>Kérem válasszon megyét</option>').attr("disabled", true);
            return;
        }
        settlement.html('<option>A lista töltődik...</option>');
        $.getJSON("/fetch_settlements/" + countyId, null, function(settlements) {
            var options = '<option value="">Kérem válasszon</option>';
            $.each(settlements, function(i, settlement) {
                options += '<option value="' + i + '">' + settlement + '</option>';
            });
            settlement.html(options);
            settlement.attr("disabled", false);
            if (typeof(callback) != 'undefined') {
                callback();
            }
        });
}

function notify(options) {
    var opt;
    if (typeof options != "object") {
        options = {'text': options};
    }
    opt = $.extend({}, $.pnotify.defaults, options);
    if (typeof options.text == 'object') {
        var text = [];
        for (var key in options.text) {
            text.push(options.text[key]);
        }
        options.text = text.join('<br />');
    }
    opt.pnotify_text = options.text;
    opt.pnotify_title = options.title;
    opt.pnotify_stack = {
                "dir1": "up",
                "dir2": "left",
                "firstpos1": 15,
                "firstpos2": 15
            };
    opt.pnotify_addclass = "stack-bottomright";
    if (typeof options.position != 'undefined') {
        if (options.position == 'bottom-left') {
            opt.pnotify_stack = {
                "dir1": "up",
                "dir2": "right",
                "firstpos1": 15,
                "firstpos2": 15
            };
            opt.pnotify_addclass = "stack-bottomleft";
        }
    }
    opt.pnotify_type = options.type;
    if (typeof options.type != 'undefined' 
        && options.type == 'error'
        && typeof options.title == 'undefined'
    ) {
            opt.pnotify_title = 'Hiba';
    }
    $.pnotify(opt);
}

function errorHandling($form, data, successCallback, errorCallback) {
    $form.find("input, select, textarea").removeClass("unfilled");
    if (data.errorCount) {
        for(var field in data.errors) {
            $form.find("[name='" + field + "']").addClass("unfilled");
        }
        if (typeof errorCallback == 'function') {
            errorCallback();
        }
    } else {
        if (typeof successCallback == 'function') {
            successCallback();
        }
    }
}

var errorCallbackAnnotation = function($form, data)
{
    for(var field in data.errors) {
        var $field = $form.find("[name='" + field + "']");
        if (!$field.parents("dd").find(".error-unfilled").length) {
            var $annotation = $('<div class="error-unfilled"> * ' + data.errors[field] + '</div>');
            $field.parents("dd").append($annotation);
        }
    }
    $('html, body').animate({
        scrollTop: $form.find(".unfilled:first").offset().top - 50
    });
}
