/*!
 * jQuery-якорь
 * Позволяет:
 * 1) плавно переходить к якорю
 * 2) если цель перехода скрыта, то контент цели обновляется
 */

jQuery.fn.anchor = function (options) {
    var targetContent = options.targetContent;
    var action = options.action;
    var targetAnchor = options.targetAnchor;

    var scroller = "html";
    //хак для Chrome и Safari
    if($.browser.chrome || $.browser.safari) {
        scroller = "body";
    }

    var className = options.className;
    $(this).addClass(className);
    $(this).unbind('click');
    $(this).click(function() {
        var visible =  ($("#"+targetContent+":visible").size() > 0) ? true : false;
        if(!visible) {
            $("#"+targetContent).load_post(action, { },function(){
                $("#"+targetContent).show(300, function() {
                    var destination = anchorGetOffsetTop(document.getElementById(targetAnchor))
                    $(scroller).animate({scrollTop: destination}, 1100 );
                    return false;
                });
            });
            return false;
        }
        var destination = anchorGetOffsetTop(document.getElementById(targetAnchor));
//        alert(destination);
//        alert($("#"+targetAnchor).offset().top);
        $(scroller).animate({scrollTop: destination}, 1100 );
        return false;
    });
}

function anchorGetOffsetTop(element) {
    var offsetTop = element.offsetTop;
    if(element.offsetParent != null) {
        offsetTop += anchorGetOffsetTop(element.offsetParent);
    }
    return offsetTop;
}