$(document).ready(function(){


    $("form[name='login_form']").submit(function() {

        $.ajax({
            type: "POST",
            url: "/login",
            data: $(this).serialize(),
            cache: false,
            success:
            function(result){
            
                if ( result ) { return alert('Hibás felhasználói név vagy jelszó!'); }

                if ( new String(document.location).indexOf('logout') !== -1 ) {
                    document.location = 'index.php';
                } else {
                    document.location.reload();
                }

            }
        });


    });

    $("form[name='uj_csoport_form']").submit(function() {
        
        $.ajax({
            type: "POST",
            url: "/content/uj_csoport",
            data: $(this).serialize(),
            cache: false,
            success:
            function(result){
                
                if ( result == '' ) {

                    alert('A csoport sikeresen fel lett véve!');
                    document.location.reload();
                    
                } else {
                    alert('Adatbázis hiba!');
                }

            }
        });

    });

    $("form[name='uj_kategoria_form']").submit(function() {

        $.ajax({
            type: "POST",
            url: "/content/uj_kategoria",
            data: $(this).serialize(),
            cache: false,
            success:
            function(result){

                if ( result == '' ) {

                    alert('A kategória sikeresen fel lett véve!');
                    document.location.reload();

                } else {
                    alert('Adatbázis hiba!');
                }

            }
        });

    });


    $("ul[class='kategoriak'] a[name='edit']").livequery("click",function(){
        $li = $(this).parent();
        var Id = $li.attr("id");
        $name = $li.find("#name");
        $name.hide();
        $name.after('<input type="text" name="name" value="'+$name.html()+'">');

        $(this).attr("name","save").html('Mentés');

    });

    $("ul[class='kategoriak'] a[name='save']").livequery("click",function(){
        $li = $(this).parent();
        var Id = $li.attr("id");
        $name = $li.find("#name");
        $input = $li.find("input");
        $a = $(this);

        $.post('/content/edit_kategoria/'+Id,$input.serialize(),function(result){
            if ( result == '') {
                $name.html($input.val()).show();
                $li.find("input").remove();
                $a.attr("name","edit").html('Szerkesztés');
            } else {
                alert(result);
            }
        },'POST');
        

    });

    $("ul[class='kategoriak'] a[name='del']").livequery("click",function(){
        var Id = $(this).parent().attr("id");
        $a = $(this);

        if ( confirm("Valóban törölni szeretné?") ) {

            $.post('/content/del_kategoria/'+Id, false, function(result) {
                if ( result=='' ) {
                    $a.parent().hide("normal",function(){
                        document.location.reload();
                    });
                } else {
                    alert(result);
                }
            });

        }

    });


    /*
    $("form[name='new_content_form']").submit(function(){

        var alias = $(this).find("input[name='alias']").val();
        var id = $(this).find("input[name='category']").val()+'33';

        $.post('/content/save', $(this).serialize(), function(result) {

            if ( result == '' ) {
                document.location = '/egyiksem/'+alias+'/'+id
            } else {
                alert(result);
            }

        }, 'POST');

    });*/

    $("form[name='edit_content_form'] a[name='formaz'], form[name='new_content_form'] a[name='formaz']").click(function(){

        $(this).remove();

        var oFCKeditor = new FCKeditor( 'subhead' );
        oFCKeditor.BasePath = '/design/js/fckeditor/';
        oFCKeditor.ToolbarSet	= 'Basic';
        oFCKeditor.Height	= 100;
        oFCKeditor.ReplaceTextarea();

    });

     $("a[name='delete_comment']").click(function(){

        if ( confirm('Biztos, hogy törölni szeretné?') ) {
         var Id = $(this).attr("rel").replace('id_','');
         $comment = $(this).parents('.comment');
         $.get('/comment/delete/' + Id, false, function(){
             $comment.slideUp("normal");
         });
        }

     });

     
     $("a[name='send_article']").livequery(function(){

        Id = $(this).attr("id").replace('content_','');
        $(this).colorbox({href:"/content/send_article/" + Id, fixedHeight:"500px"});

     });
    $("form[name='send_article']").livequery(function(){
        $form = $(this);
        $form.find("a[name='more_recipient']").click(function(){
            $dd = $form.find("dl > dd.to:last");
            $ddClone = $dd.clone(); $ddClone.find("input").val('');
            $ddClone.insertAfter($dd);
        });
        $form.submit(function(){

           // Ellenorzes
           var empty=0; $form.find("input[type='text']").each(function(){
              if ( !$(this).val() ) { $(this).css("background","#FFA1A1"); empty++; }
              else { $(this).css("background","none"); }
           }); if ( empty ) { return false; }
           
           $form.find(".status").html('Kérem várjon...');

            $.post('/content/send_article', $(this).serialize(), function(result) {
                if ( !result ) {
                    alert('Sikeresen elküldve!');
                } else {
                    alert('Belső hiba');
                }
                $("#modalClose").click();
            });
        });
    });

    $("a[name='send_tag_ajanlo']").livequery(function(){

        Id = $(this).attr("id").replace('content_','');
        $(this).colorbox({href:"/apply/send_tag_ajanlo", fixedHeight:"500px"});

     });
    $("form[name='send_tag_ajanlo']").livequery(function(){
        $form = $(this);
        $form.find("a[name='more_recipient']").click(function(){
            $dd = $form.find("dl > dd.to:last");
            $ddClone = $dd.clone(); $ddClone.find("input").val('');
            $ddClone.insertAfter($dd);
        });
        $form.submit(function(){

           // Ellenorzes
           var empty=0; $form.find("input[type='text']").each(function(){
              if ( !$(this).val() ) { $(this).css("background","#FFA1A1"); empty++; }
              else { $(this).css("background","none"); }
           }); if ( empty ) { return false; }

           $form.find(".status").html('Kérem várjon...');

            $.post('/apply/send_tag_ajanlo', $(this).serialize(), function(result) {
                if ( !result ) {
                    alert('Sikeresen elküldve!');
                } else {
                    alert('Belső hiba');
                }
                $("#modalClose").click();
            });
        });
    });

    
    $("input[name='vote']").click(function(){

        Id = $("input[name='president']:checked").val();

        if ( !Id ) { return false; }

        $.get('/politics/vote/' + Id, false, function(r){ alert(r);
            $("div[class='vote_for_presidents']").replaceWith( $('<p style="font-size:16px;color:green;">Köszönjük, hogy szavazott!</p>') );
        });

    });

    $("form[name='new_president']").livequery("submit",function(){

        $.get('/politics/addPresident/' + $(this).find("input[name='name']").val() ,false,function(result){
            document.location.reload(true);
        });

    });
    
    /* Jelentkezes */
    $("form[name='apply']").livequery(function(){

        $applyForm = $(this);
        
        setSettlements({
                event:      'change',
                country:    $applyForm.find("select[name='country']"),
                settlement: $applyForm.find("select[name='settlement']"),
                prepend:    '<option value="">válasszon települést</option>'
        });
        
        $applyForm.submit( function(){

            $button = $(this).find("input[name='submit']");

            $button.attr("disabled","disabled");

            jsonFormParse({
                form: $(this),
                url: '/politics/addApply',
                success: function() {
                    document.location = '#';
                    this.form.html(
                        '<h2>Köszönjük a jelentkezést!</h2>' +
                        '<p>Számunkra nagyon fontos, hogy jelentkezett, minden egyes taggal erősödünk.' +
                        'Ha mindenki egy kicsit tesz, csak annyit, amit a lehetőségei szerint tehet, biztosan változni fog a világ.' +
                        'Kérem, küldje el egy - két ismerősének</p> ');
                },
                error: function(data) {
                    setErrorFields($(this.form),data.errors);
                    alert('A pirossal jelzett mezők kitöltése kötelező!');
                    $button.attr("disabled","");
                }
            });

            return false;

            var URL = $applyForm.attr("name") == 'reg' ? '/user/add' : '/user/modify';

            showStatusLoading($applyForm);

            $.ajax({
                type: "POST",
                url: URL,
                data: $(this).serialize(),
                dataType: 'json',
                cache: false,
                success: function(data){

                    if ( data.errors.length ) {
                        setErrorStatus($applyForm,data.errorText);
                        document.location = "#";

                    } else {
                        document.location = "#";
                        $applyForm.html(data.msg);
                    }

                },
                error: errorHandler
            });

        });

        $applyForm.find("input[type='file']").livequery("change",function(){

            var elementId = $(this).attr("id");
            $status = $(this).parent().find('.foto#'+elementId);

            showLoading($status);

            $.ajaxFileUpload({

                url: '/user/fotoUpload',
                secureuri:false,
                fileElementId: elementId,
                dataType: 'json',
                success: function (data, status) {
                  if ( data.error ) {
                    $status.html(data.error);
                  } else {
                    $status.html('<img src="'+data.imgSrc+'" alt="" border=""> <a name="delete" rel="'+elementId+'">töröl</a>');
                  }

                },
                error: function (data, status, e) {
                  alert(data.responseText);
                }

            });

        });

        $applyForm.find("a.additional_data").livequery("click",function(){

            $applyForm.find(".additional").show();
            $(this).hide();
            $(this).next().hide();

        });

        $applyForm.find("a[name='delete']").livequery("click",function(){

            $a = $(this);

            $.get('/user/fotoDelete/'+$a.attr("rel"),false,function(result){
                if ( !result ) {
                    $a.parent().html('');
                }
            });

        });

        $applyForm.find("a.more_phone").livequery("click", function(){

            var phone_num = $applyForm.find("div.phone:visible").length;

            if ( phone_num < 3 ) {
                $applyForm.find("div.phone:hidden").eq(0).show();
            }
            if ( phone_num == 2 ) {
                $(this).remove();
            }

        });

    });


    /* userController */

    $("#login form[name='login']").livequery(function(){

        $loginForm = $(this);

        $loginForm.submit(function(){

        showStatusLoading($loginForm);

            $.ajax({
                type: "POST",
                url: "/user/login",
                data: $(this).serialize(),
                dataType: 'json',
                cache: false,
                success: function(data){

                    if ( typeof(data.error) != 'undefined' ) {

                        setErrorStatus($loginForm,data.error);

                    } else {

                        $loginForm.parent().fadeOut("normal",function(){ location.reload(true); });

                    }

                },
                error: errorHandler
            });


        });

    });

    showGoogleForm();
    
});

function write_reply(parentId) {
    $("form[name='comment_form']").find("input[name='replyto']").val(parentId);
    document.location = '#hsz';
}

function new_comment(form) {

    $form = $(form);

    $.ajax({
        type: "POST",
        url: "/comment/uj_hozzaszolas/?fromAjax",
        data: $form.serialize(),
        cache: false,
        success:
        function(result){
            if ( !result ) {
                document.location = '#comments';
                document.location.reload();
            } else {
                alert(result);
            }
        }
    });
}

function showGoogleForm() {

    $.get('/content/googleform',null,function(result){
        if ( !result ) {
            $("#show_google_form").trigger('click');
        }
    })

}




// -----------------------------------------------------------------------------

function showLoading($tag) {

    $tag.html('<img src="/img/loader.gif" alt="Töltődik..." class="loading_image">');

}

function hideLoading($tag) {
    $tag.find(".loading_image").hide();
}

function showStatusLoading($tag) {

    $tag.find('.status').html('<img src="/img/loader.gif" alt="Töltődik..." class="loading_image">');

}

function hideStatusLoading($tag) {

    $tag.find('.status').html('&nbsp;');

}

function setErrorFields($form,errors) {

    $form.find("span.error").remove();
    $form.find(".error").removeClass('error');

    for (var i=0;i<errors.length;i++) {
        $field = $form.find("[name='"+errors[i].fieldName+"']:last");

        if ( $field.parent()[0].tagName.toLowerCase() == 'label' ) {
            $field = $field.parent();
        }

        $field.addClass('error');
        if ( errors[i].text.length )
        $field.after('<span class="error">'+errors[i].text+'</span>');
    }

}

function errorHandler(XMLHttpRequest, textStatus, errorThrown) {

    console.log(XMLHttpRequest.responseText);
    alert('Adatbázis hiba!');

}

function setErrorStatus($form,text) {

    $form.find(".status").html(text);

}

function setStatus($tag,text) {

    $form.find(".status").html(text);

}

function setSettlements(_data) {

    var event   = '';
    var object  = '';

    if ( typeof(_data.event) != 'undefined' ) {
        event   = _data.event;
        if ( typeof(_data.object) != 'undefined' ) {
            object  = _data.object;
        } else {
            object  = _data.country;
        }
    }

    $(object).livequery( event, function(){

        var countryId = _data.country.val();
        
        $.get('/user/getSettlements/'+countryId,false,function(result){
            if ( typeof(_data.prepend) != 'undefined' ) {
                result = _data.prepend + "\n" + result;
            }
            if ( typeof(_data.callback) != 'undefined' ) {
                _data.callback(result);
            }
            _data.settlement.attr("disabled",false).html(result);
        });

    });

}

function jsonFormParse(_data) {

    $form = _data.form;

    showStatusLoading($form);

    $.ajax({
        type: "POST",
        url: _data.url,
        data: $form.serialize(),
        dataType: 'json',
        cache: false,
        success: function(data){

            hideStatusLoading($form);

            if ( typeof(data.errors) != 'undefined' && data.errors.length>0 ) {

                if ( typeof(_data.error) != 'undefined' ) {

                    return _data.error(data);

                }

                if ( typeof(_data.onError) != 'undefined' && _data.onError == 'alert' ) {
                    alert(data.errors[0].text);
                }

                setErrorFields($form,data.errors);

            } else {

                if ( typeof(_data.success) != 'undefined' ) {
                    _data.success(data);
                } else {
                    alert(data.msg);
                }

            }

        },
        error: errorHandler
    });

    return false;
}
