jQuery(document).ready(function() {
    //jQuery('#commentform').submit(commentSubmit);

    jQuery('div.captcha_container').load('/common/captcha');

    jQuery('form.commentform').find('#code_img').click(function () {
        if(jQuery('form.commentform').find('#at15s_ji').css('display') == 'none')
        {
            jQuery('form.commentform').find('#at15s_ji').show('fast');
        }
        else
        {
            jQuery('form.commentform').find('#at15s_ji').hide('fast');
        }
    });

    jQuery('form.commentform').find('#at15sptx_ji').click(function () {
        jQuery('form.commentform').find('#at15s_ji').hide('fast');
    });

    for (lang in langObj)
    {
        jQuery("form.commentform").find("#" + lang).click(function(){jQuery('form.commentform').find('#at15s_ji').hide('fast');jQuery("form.commentform").find('#body').insertRoundCaret(jQuery(this).attr('id'))});
    }

});

function commentSubmit(obj)
{
    url = '/common/comment';
    user_name = jQuery(obj).find('input[name=user_name]').val();
    user_email = jQuery(obj).find('input[name=user_email]').val();
    captcha_input = jQuery(obj).find('input[name=captcha[input]]').val();
    captcha_id = jQuery(obj).find('input[name=captcha[id]]').val();
    comment_id = jQuery(obj).find('input[name=comment_id]').val();

    if(comment_id == undefined)
    {
        comment_id = '';
    }
    body = jQuery(obj).find('textarea[name=body]').val();
    jQuery.ajax({
        url: url,
        data: 'user_name=' + encodeURIComponent(user_name) + '&user_email=' + encodeURIComponent(user_email) + '&captcha[input]=' + encodeURIComponent(captcha_input) + '&captcha[id]=' + encodeURIComponent(captcha_id) + '&body=' + encodeURIComponent(body) + '&object_id=' + encodeURIComponent(object_id) + '&object_name=' + encodeURIComponent(object_name) + (return_url.length > 0 ? '&return_url=' + encodeURIComponent(return_url) : '') + '&comment_id=' + encodeURIComponent(comment_id) + '&object_user_id=' + encodeURIComponent(object_user_id) + '&object_title=' + encodeURIComponent(object_title),
        type: 'post',
        dataType: 'text',
        success: function(data) {
            /*try {
                data = '{ "success" : "asd" }';
                json = eval("(" + data + ")");
                alert(json.success);
            }
            catch(err)
            {*/
                // Это не json
                jQuery('div#commentBlock').html(data);
            /*}*/
            if(comment_id != '')
            {
                //console.log(jQuery('a.comment-' + comment_id));
                var parentOffset = jQuery('a.comment-' + comment_id).offset().top;
            }
            else
            {
                var parentOffset = jQuery('h3#respond').offset().top;
            }
            jQuery('html').animate({scrollTop: parentOffset}, 500);
            
            jQuery("body").find("#TB_overlay").remove();
        },
        error: function() {
            jQuery("body").find("#TB_overlay").remove();
            alert('Произошла ошибка, попробуйте обновить страницу и добавить комментарий снова.');
        },
        beforeSend: function() {
            if(!jQuery("body").find("#TB_overlay").is("div"))
            {
               if(!jQuery.browser.msie)
               {
                    jQuery("body").append("<div id='TB_overlay'></div>");
               }
               else
               {
                    jQuery("body").append("<div id='TB_overlay'><iframe scrolling='no' frameborder='0' style='position: absolute; top: 0; left: 0; width: 100%; height: 100%; filter:alpha(opacity=0)'></iframe></div>");
               }
            }

            if(comment_id != '')
            {
                //console.log(jQuery('a.comment-' + comment_id));
                var parentOffset = jQuery('a.comment-' + comment_id).offset().top;
            }
            else
            {
                var parentOffset = jQuery('h3#respond').offset().top;
            }
            jQuery('html').animate({scrollTop: parentOffset}, 500);

            //jQuery('table.jur_register select[name=city_id]').append('<option>идет загрузка...</option>')
        }
    });
}

function showForm(obj, level)
{
    jQuery('div#commentContainer').find('#at15s_ji').css('margin-right', '-' + (7+ (level-1)*3) + 'px');
    if(jQuery('div#reply-' + jQuery(obj).attr('id')).length)
    {
        jQuery('#reply-' + jQuery(obj).attr('id')).hide('slow', function() {jQuery(this).remove();});
    }
    else
    {
        jQuery('div#commentContainer').clone().insertAfter(obj).end().hide().show('slow').attr('id', 'reply-' + jQuery(obj).attr('id'));

        jQuery('#reply-' + jQuery(obj).attr('id')).find('#code_img').click(function () {
            if(jQuery('#reply-' + jQuery(obj).attr('id')).find('#at15s_ji').css('display') == 'none')
            {
                jQuery('#reply-' + jQuery(obj).attr('id')).find('#at15s_ji').show('fast');
            }
            else
            {
                jQuery('#reply-' + jQuery(obj).attr('id')).find('#at15s_ji').hide('fast');
            }
        });

        jQuery('#reply-' + jQuery(obj).attr('id')).find('#at15sptx_ji').click(function () {
            //console.log(jQuery('#reply-' + jQuery(obj).attr('id') + ' #at15s_ji'));
            jQuery('#reply-' + jQuery(obj).attr('id')).find('#at15s_ji').hide('fast');
        });

        jQuery('#reply-' + jQuery(obj).attr('id')).find('input#comment_id').val(jQuery(obj).attr('id'));

        for (lang in langObj)
        {
            jQuery('#reply-' + jQuery(obj).attr('id')).find("#" + lang).click(function(){jQuery('#reply-' + jQuery(obj).attr('id')).find('#at15s_ji').hide('fast');jQuery('#reply-' + jQuery(obj).attr('id')).find('#body').insertRoundCaret(jQuery(this).attr('id'))});
        }

        var parentOffset = jQuery(obj).offset().top;
        jQuery('html').animate({scrollTop: parentOffset}, 500);
    }
}


jQuery.fn.insertRoundCaret = function (lang) {
        return this.each(function(){
                strStart = '<code lang="'+lang+'">';
                strEnd = '</code>';
                if (document.selection) {
                        //IE support
                        stringBefore = this.value;
                        this.focus();
                        sel = document.selection.createRange();
                        insertstring = sel.text;
                        fullinsertstring = strStart + sel.text + strEnd;
                        sel.text = fullinsertstring;
                        document.selection.empty();
                        this.focus();
                        stringAfter = this.value;
                        i = stringAfter.lastIndexOf(fullinsertstring);
                        range = this.createTextRange();
                        numlines = stringBefore.substring(0,i).split("\n").length;
                        i = i+3-numlines+/*tagName.length*/4;
                        j = insertstring.length;
                        range.move("character",i);
                        range.moveEnd("character",j);
                        range.select();
                }else if (this.selectionStart || this.selectionStart == '0') {
                        //MOZILLA/NETSCAPE support
                        startPos = this.selectionStart;
                        endPos = this.selectionEnd;
                        scrollTop = this.scrollTop;
                        this.value = this.value.substring(0, startPos) + strStart + this.value.substring(startPos,endPos) + strEnd + this.value.substring(endPos,this.value.length);
                        this.focus();
                        this.selectionStart = startPos + strStart.length ;
                        this.selectionEnd = endPos + strStart.length;
                        this.scrollTop = scrollTop;
                } else {
                        this.value += strStart + strEnd;
                        this.focus();
                }
        });
};

