$(document).ready(function(){

    /* common showhide links */
    $("a.showhide").each(function() {
        var target = $(this).parent().parent().parent().find( '.'+$(this).attr("ref") );
        if (target.css("display") == 'none')
            $(this).find("img").attr("src","/img/icons_2/GIF/action_add.gif");
        else
            $(this).find("img").attr("src","/img/icons_2/GIF/action_remove.gif");
    });
     
    $("a.showhide").livequery("click",function(){
        var target = $(this).parent().parent().parent().find( '.'+$(this).attr("ref") );
        if (target.css("display") == 'none') {
            $(this).find("img").attr("src","/img/icons_2/GIF/action_remove.gif");
            target.fadeIn("normal");            
        }
        else {
            $(this).find("img").attr("src","/img/icons_2/GIF/action_add.gif");
            target.fadeOut("normal");            
        }
    });
        

    /* regController */
    $("form[name='reg'], form[name='profile']").livequery(function(){

        $userForm = $(this);

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

        $userForm.submit( function(){

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

            showStatusLoading($userForm);
            
            // Nem kitoltott al-formok elrejtese.
            $userForm.find("input[name='education_typeOfQualification[]']").each(function(index) {
                if ($(this).val() == '') $(this).parent().hide();
            });
            $userForm.find("input[name='experience_position[]']").each(function(index) {
                if ($(this).val() == '') $(this).parent().hide();
            });
            $userForm.find("input[name='language_language[]']").each(function(index) {
                if ($(this).val() == '') $(this).parent().hide();
            });
            $userForm.find("input[name='child_name[]']").each(function(index) {
                if ($(this).val() == '') $(this).parent().hide();
            });
            

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

                    if ( typeof(data.errors) != 'undefined' && data.errors.length ) {
                        setErrorFields($userForm,data.errors);
                        document.location = "#";
                        hideStatusLoading($userForm);

                    } else {
                        if ( type == 'reg' ) {
                            if ( typeof(data.redirect) != 'undefined' ) {
                                document.location = data.redirect;
                            } else if ( typeof(data.msg) != 'undefined' ) {
                                $userForm.html(data.msg);
                            }

                        } else {
                            if ( typeof(data.redirect) != 'undefined' ) {
                                document.location = data.redirect;
                                return;
                            }
                            document.location = "#";
                            $msg = $('<div class="msg success">'+data.msg+'</div>');
                            $userForm.prepend($msg);
                            $msg.fadeOut(10000);
                        }
                        hideStatusLoading($userForm);
                    }

                },
                error: errorHandler
            });

        });
        

        $userForm.find("input[name^='foto'][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);
                }

            });

        });

        // Melleklet URL feltoltes.
        $userForm.find("#addAnnexes").livequery("click",function(){

            var elementId = 'annexesURL';
            $status = $(this).parent().parent();

            showLoading($status.find('.annexesLoad'));

            $.ajax({
                
                type: "POST",
                url: '/user/urlUpload',
                secureuri:false,
                fileElementId: elementId,
                data: $(this).parent().find("input[name='annexesURL']").serialize(),
                dataType: 'json',
                success: function (data, status) {
                  if ( data.error ) {
                    $status.find('.annexesLoad').html(data.error);
                  } else {
                    $status.find(".annexesLoad").html('');
                    if (data.url != '')
                    {
                        $status.find('.annexes').append('<div><a href="'+data.url+'" alt="" >'+data.url+'</a> <a name="delAnnex" rel="'+data.url+'"><img width="10" src="/img/icons_2/GIF/action_remove.gif" alt="" border="0" /> eltávolítás</a></div>');
                    }
                        
                  }

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

            });
            
        });
        
        $userForm.find("input[name='annexesURL']").livequery("keypress",function(event){
              if (event.keyCode == 13) 
              {
                $userForm.find("#addAnnexes").click();
                return false; 
              }
        });

        // Melleklet file feltoltes.
        $userForm.find("input[name='annexesFile'][type='file']").livequery("change",function(){

            var elementId = 'annexesFile';//$(this).attr("id");
            $status = $(this).parent().parent();

            showLoading($status.find('.annexesLoad'));

            var xhr = $.ajaxFileUpload({

                url: '/user/fileUpload',
                secureuri:false,
                fileElementId: elementId,
                dataType: 'json',
                success: function (data, status) {
                  if ( data.error ) {
                    $status.find('.annexesLoad').html(data.error);
                  } else {
                    $status.find(".annexesLoad").html('');
                    if (data.fileSrc != '')
                    {
                        var filename = (data.filename.charAt(0) == '/') ? data.filename.substr(1) : data.filename;                        
                        $status.find('.annexes').append('<div><a href="'+data.fileSrc+'" alt="" >'+filename+'</a> <a name="delAnnex" rel="'+data.filename+'"><img width="10" src="/img/icons_2/GIF/action_remove.gif" alt="" border="0" /> eltávolítás</a></div>');                        
                    }
                  }

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

            });

            xhr.abort();
        });

        // Melleklet torlese.
        $userForm.find("a[name='delAnnex']").livequery("click",function(){

            $a = $(this);

            $.ajax({
                
                type: "POST",
                url: '/user/fileDelete',
                secureuri:false,
                data: { filename: $a.attr("rel") },
                dataType: 'json',
                success: function (data, a) {
                  if ( data.error ) {
                    $a.parent().html('');
                  } else {
                    $a.parent().html('');                        
                  }

                },
                error: function (data, a, e) {
                  $a.parent().html('');
                }

            });
        });
                
        
        $userForm.find("a.cancelLoading").livequery("click",function(){
            $(this).parent().html('');
        });
        
        $userForm.find("a.additional_data").livequery("click",function(){

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

        });

        
        // Torles eseten sargaval kijeloli a torlendot.
        $userForm.find("a[name='delAnnex']").livequery("mouseenter",function(){ 
            $(this).parent().css('background-color','yellow'); 
        });
        $userForm.find("a[name='delAnnex']").livequery("mouseleave",function(){ 
            $(this).parent().css('background-color','transparent'); 
        });

        // Torles eseten sargaval kijeloli a torlendot.
        $userForm.find("a[name^='del_']").livequery("mouseenter",function(){ 
            $(this).parent().parent().css('background-color','yellow'); 
        });
        $userForm.find("a[name^='del_']").livequery("mouseleave",function(){ 
            $(this).parent().parent().css('background-color','transparent'); 
        });


        $userForm.find("a[name='add_child']").livequery("click",function(){
            $.get('/user/addUserChild/',null,function(Id){                
                $child = $userForm.find(".children .child:hidden").clone();
                $child.appendTo($userForm.find(".children"));
                $child.find("input[name^='child_id']").val(Id);
                tb_init($child.find("a[name^='p_']"));
                $child.fadeIn();                
            });
        });

        $userForm.find("a[name='del_child']").livequery("click",function(){
            $(this).parent().parent().fadeOut(300,function() { 
                $(this).find("input[name='child_name[]']").val(''); });
        });


        $userForm.find("a[name='add_education']").livequery("click",function(){
            $.get('/user/addUserEducation/',null,function(Id){            
                $child = $userForm.find(".educations .education:hidden:first").clone();
                $child.appendTo($userForm.find(".educations"));
                $child.find("input[name^='education_Id']").val(Id);
                tb_init($child.find("a[name^='p_']"));
                $child.fadeIn();
            });                
        });
                        
        $userForm.find("a[name='del_education']").livequery("click",function(){
            $(this).parent().parent().fadeOut(300,function() { 
                $(this).find("input[name='education_typeOfQualification[]']").val(''); });
        });


        $userForm.find("a[name='add_experience']").livequery("click",function(){
            $.get('/user/addUserExperience/',null,function(Id){
                $child = $userForm.find(".experiences .experience:hidden:first").clone();
                $child.appendTo($userForm.find(".experiences"));
                $child.find("input[name^='experience_Id']").val(Id);
                tb_init($child.find("a[name^='p_']"));
                $child.fadeIn();
            });
        });

        $userForm.find("a[name='del_experience']").livequery("click",function(){
            $(this).parent().parent().fadeOut(300,function() { 
                $(this).find("input[name='experience_position[]']").val(''); });
        });



        $userForm.find("a[name='add_language']").livequery("click",function(){
            $.get('/user/addUserLanguage/',null,function(Id){
                $child = $userForm.find(".languages .language:hidden:first").clone();
                $child.appendTo($userForm.find(".languages"));
                $child.find("input[name^='language_Id']").val(Id);
                tb_init($child.find("a[name^='p_']"));
                $child.fadeIn();
            });
        });

        $userForm.find("a[name='del_language']").livequery("click",function(){
            $(this).parent().parent().fadeOut(300,function() { 
                $(this).find("input[name='language_language[]']").val(''); });
        });


        $userForm.find("input[name='drivingLicenseClear']").click(function(){
            $userForm.find("input[name='drivingLicense[]']").attr('checked', false);
        });

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

            $a = $(this);

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

        });

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

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

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

        });

        $userForm.find("a.more_photo").livequery("click", function(){

            var photo_num = $userForm.find("div.foto_field:visible").length;
            var max_photo = $userForm.find("div.foto_field").length;
            
            if ( photo_num < max_photo ) {
                $userForm.find("div.foto_field:hidden").eq(0).show();
            }
            if ( photo_num == (max_photo-1) ) {
                $(this).remove();
            }

        });

    });

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

        $userForm       = $("form[name='reg'], form[name='profile']");
        $flottaForm     = $(this);
        var phoneNum    = $flottaForm.find("input[name='phone_num']").val();

        $flottaForm.find("select").change(function(){

            var html = $(this).find("option[value='"+$(this).val()+"']").text()
                     + '<input type="hidden" name="phone'+phoneNum+'_flotta" value="'+$(this).val()+'">';

            $userForm.find("#phone"+phoneNum).find(".flotta").html( html );

            tb_remove();

        })

        $flottaForm.submit(function(){

            var newName = $flottaForm.find("input[name='flotta']").val();
            var html    = newName
                        + '<input type="hidden" name="phone'+phoneNum+'_flotta" value="'+newName+'">';

            $userForm.find("#phone"+phoneNum).find(".flotta").html( html );

            tb_remove();

        })

    });
    
    // Globalvar.
    $.selectedPermisLink = null;
    $("a[name^='p_']").livequery(function(){
        $(this).click(function(){
             $.selectedPermisLink = $(this);
        });
    });

    $("form[name='permission']").livequery(function(){
        
        $permisForm = $(this);        
        var field = $permisForm.find("input[name='permis_field']").val();
        var form  = $permisForm.find("input[name='permis_form']").val();
        
         // Ha nincs form definialva akkor a megnyomott link szulein belul keresunk a tombositett inputot.
        var permisInput = null;       
        if (form != '')
            permisInput = $.selectedPermisLink.parent().parent().find("input[name='"+form+'_'+field+"[]']");
        else
            permisInput = $("form[name='reg'], form[name='profile']").find("input[name='"+field+"']");
                   
        $permisForm.find("select").change(function(){        

            // Atallitom a linket az uj ertekre.
            var href = $.selectedPermisLink.attr('href');
            $.selectedPermisLink.attr('href', href.substr(0, href.indexOf('&permis='))+'&permis='+$(this).val() );

            // Link kep modositasa.
            $.selectedPermisLink.removeClass('permis_public permis_private permis_grant').addClass('permis_'+$(this).val());
            permisInput.val($(this).val());
            tb_remove();
        });

        $permisForm.submit(function(){
            tb_remove();
        });

    });
    
    // 
    if ($("#user_details div.portrait").length > 0)
    {
        $("#user_details div.details p:eq(0) .value").addClass('short');
        $("#user_details div.details p:eq(1) .value").addClass('short');
        $("#user_details div.details p:eq(2) .value").addClass('short');
        $("#user_details div.details p:eq(3) .value").addClass('short');
        $("#user_details div.details p:eq(4) .value").addClass('short');
        $("#user_details div.details p:eq(5) .value").addClass('short');
        $("#user_details div.details p:eq(6) .value").addClass('short');
        $("#user_details div.details p:eq(7) .value").addClass('short');
        $("#user_details div.details p:eq(8) .value").addClass('short');
        $("#user_details div.details p:eq(9) .value").addClass('short');
        $("#user_details div.details p:eq(10) .value").addClass('short');
        $("#user_details div.details p:eq(11) .value").addClass('short');
        $("#user_details div.details p:eq(12) .value").addClass('short');
        $("#user_details div.details p:eq(13) .value").addClass('short');
        $("#user_details div.details p:eq(14) .value").addClass('short');
    }


    $("ul.menu li").click(function(){
        document.location = $(this).find("a").attr("href");
    });


    /* 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(){ document.location = '/user/adatlap'; /*location.reload(true);*/ });

                    }

                },
                error: errorHandler
            });


        });

    });

    /* search */

    $("#search").livequery(function(){

        $search = $(this);

        $search.find("form").livequery("submit",function(){

            showLoading($("#list"));


            $form = $(this);

            $.post('/list/search/?fromAjax=true',$(this).serialize(),function(result){

                $result = $(result);

                var hideForm = new Boolean($form.find("input[name='hide_form']").val());

                if ( $result.find(".user").length == 1 ) {
                    document.location = $result.find("a").attr("href");
                } else {

                    if ( hideForm ) {  }

                    $result.attr("class", $("#list").attr("class"));
                    $("#list").replaceWith($result);
                }

            });

        });

        setSettlements({
            event:      'change',
            country:    $search.find("select[name='country']"),
            settlement: $search.find("select[name='settlement']"),
            prepend:    '<option value="">Bármely település</option>'
        });

    });



    /* list */

    $("#list").livequery(function(){

        $list = $(this);

        $list.find(".user a[name='more_details']").livequery("click",function(){

            $user = $(this).parents("div[class='user']");
            $user.find("div[class='more_details']").slideDown("normal");
            $(this).attr("name","hide_details").attr("class","hide_details").html('részletek elrejtése');

        });

        $list.find(".user a[name='hide_details']").livequery("click",function(){

            $user = $(this).parents("div[class='user']");
            $user.find("div[class='more_details']").slideUp("normal");
            $(this).attr("name","more_details").attr("class","more_details").html('további adatok');

        });

        $list.find("table").livequery(function(){

            $(this).find("thead tr td").click(function(){

                var order = $(this).attr("id").replace('o_','');
                $.get('/list/setOrder/'+order+'/inverse',null,function(){ document.location.reload(true); });

            })
            
            $(this).find("tbody tr").each(function(i){

                if ( i % 2 == 0 ) {
                    $(this).addClass("even");
                }

                $(this).mouseover(function(){
                    $(this).addClass("hover");
                })

                $(this).mouseout(function(){
                    $(this).removeClass("hover");
                })

                $(this).click(function(){
                    document.location = $(this).find("a").attr("href");
                })

            })

        });

    })

    $("#view").livequery(function(){

        $view = $(this);

        $view.find("div[class$='boxview']").livequery("click",function(){

            $.get('/list/setView/box',false,function(){ getList(); });


        });

        $view.find("div[class$='tableview']").livequery("click",function(){

            $.get('/list/setView/table',false,function(){ getList(); });

        });

    });


    /* comment */

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

        $commentForm = $(this);

        showStatusLoading($commentForm);

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

                    hideStatusLoading($commentForm);

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

                        setErrorFields($commentForm,data.errors);

                    } else {
						
						$commentForm.find("textarea").val('');
						
                        $.get('/comment/list/'+data.userId,false,function(result){

                            $("#comment_list").replaceWith(result);

                        });

                    }

                },
                error: errorHandler
            });

    });

    $("#comment_list").livequery(function(){

        $comment_list = $(this);

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

            Id = $(this).attr("id").replace('comment_','');

            $comment = $(this).parents(".comment");


            if ( confirm('Valóban törölni szeretnéd a hozzászólást?') )
            $.get('/comment/delete/'+Id,false,function(result){

                if ( !result ) {
                    $comment.fadeOut("normal");
                } else {
                    alert('Adatbázis hiba!');
                }

            });

        });


    });


    /* settings */
    $("#settings").livequery(function(){


        $settings = $(this);


        $settings.find("form[name='password_change']").submit(function(){

            jsonFormParse({
                form: $(this),
                url: '/user/newPassword',
                success: function(data) {
                    this.form.find("fieldset").html(data.msg);
                }
            });


        });

    });

    /* invite */
    $("#invite").livequery(function(){

        $invite = $(this);

        $invite.find("form").submit(function(){

            jsonFormParse({
                form: $(this),
                url: '/user/meghivo',
                success: function(data) {
                    this.form.replaceWith(data.msg);
                }
            });

        });

    });

    /* politics */

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

        Id = $("input[name='president']:checked").val();
        $.get('/politics/vote/' + Id, false, function(){
            $("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);
        });

    });

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

        jsonFormParse({
                form: $(this),
                url: '/politics/addApply',
                onError: 'alert',
                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> ');
                }
            });

    });

    /* valtsuk meg a vilagot */
    $("#save_the_world").livequery(function(){

        $stw = $(this);


        $stw.find("ul.parties span").click(function(){
            var party = $(this).attr("class");

            switch (party) {

                case 'mszp': document.location = 'http://mszp.hu/';  break;
                case 'fidesz': document.location = 'http://fidesz.hu/';  break;
                case 'szdsz': document.location = 'http://www.szdsz.hu/';  break;
                case 'jobbik': document.location = 'http://www.jobbik.hu/';  break;
                case 'mdf': document.location = 'http://mdf.hu/';  break;
                case 'kdnp': document.location = 'http://kdnp.hu/';  break;
                case 'egyiksem': document.location = 'http://egyiksem.hu/gyere_velunk___hogy_lehetsz_tag_';  break;

            }

        });

    });

})




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

function showLoading($tag) {

    $tag.html('<img src="/img/loader.gif" alt="Töltődik..." class="loading_image"><a class="cancelLoading">&nbsp;Mégse</a>');

}

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');
    $form.find(".info:hidden").show();

    for (var i=0;i<errors.length;i++) {

        $field = $form.find("[name='"+errors[i].fieldName+"']:last");
        $field.addClass('error');
        if ( typeof($field.parent()[0]) != 'undefined' && $field.parent()[0].tagName.toLowerCase() == 'label' ) {
            $field = $field.parent();
        }
        if ( $field.next('span').hasClass("info") ) {
            $field.next('span').hide();
        }
        $field.after('<span class="error">'+errors[i].text+'</span>');
    }

}

function errorHandler(XMLHttpRequest, textStatus, errorThrown) {

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

}

function setErrorStatus($form,text) {

    $form.find(".status").html('<div class="error">'+text+'</div>');

}

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.onError) != 'undefined' ) {
                    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;
}

function getList(_data) {

    if ( typeof(_data) == 'object' ) {
        object = _data.object;
    } else {
        object = $("#list");
    }

    showLoading(object);

    $.get('/list/list/?fromAjax=true',false,function(result){

        object.replaceWith(result);

    });

}

function storeForm(name,url,redirect) {
    var data = $("form[name='" + name + "']").serialize();
    $.post(url,data,function(){
        if ( redirect ) { document.location = redirect; }
    });

}

