/**
* SRAX Anchor Mix v0.9 beta (build 4)
* Mix of AJAX & Standard Anchors - MASA
* http://www.fullajax.ru
* Copyright(c) 2008-2009, Ruslan Sinitskiy.
* http://fullajax.ru/#:license
**/

(function($) {
    var D = $.Default;
    D.ANCHOR = {
        ANIM_SCROLL: 1,
        RECURSIVE: 0,
        prefix: 'anchor',
        id: '_GLOBAL_'
    }
    var getPos = function(obj) {
        obj = $.get(obj);
        var x = 0, y = 0;
        while (obj) {
            x += obj.offsetLeft;
            y += obj.offsetTop;
            obj = obj.offsetParent;
        }
        return { x: x, y: y }
    }

    function scroll(el, d, init, anim, recursive) {
        if (!(recursive == null ? D.ANCHOR.RECURSIVE : recursive)) {
            var delta = getPos(el).y - Math.max(document.body.scrollTop, document.documentElement.scrollTop);
            var N = delta && (anim == null ? D.ANCHOR.ANIM_SCROLL : anim) ? 10 : 1;
            delta /= N;
            var anim = setInterval(function() {
                scrollBy(0, delta)
                if (! --N) clearInterval(anim);
            }, 100 / N)
            return;
        }
        if (!el || !el.parentNode) return; //|| el == document.body
        /*if (init && window.opera){
        var p = el;             
        while (p = p.parentNode) p.scrollTop = 0;
        }*/
        var parent = el.parentNode;
        var parentY = getPos(parent).y;
        var delta = getPos(el).y - parentY + d;

        delta -= parent.scrollTop;
        var N = delta && (anim == null ? D.ANCHOR.ANIM_SCROLL : anim) ? 10 : 1,
            DELTA = delta;
        delta /= N;
        parent.anim = setInterval(function() {
            parent.scrollTop += delta;
            if (! --N) {
                clearInterval(parent.anim);
                if (parent.parentNode) {
                    var d = DELTA - parent.scrollTop; //getPos(el).y - parentY - parent.scrollTop + D;
                    scroll(parent, d);
                }
            }
        }, 100 / N);
    }

    function anchor2target(anchor, add2history, id) {
        var el = $.get(anchor);
        if (!el) {
            var trgt = document.getElementsByName(anchor);
            for (var i = 0; i < trgt.length; i++) {
                if (trgt[i].nodeName == 'A') {
                    el = trgt[i];
                }
            }
        }
        if (el) {
            scroll(el, 0, 1)
            if (add2history) $.History.add(id || D.ANCHOR.id, anchor, D.ANCHOR.prefix);
            return false;
        }
    }


    $.Filter.on('beforewrap', function(ops) {
        var el = ops.el;
        if (el.nodeName == 'A' && !el.anchored) {
            var uri = $.parseUri(el.href),
                anchor = uri.anchor;
            if (anchor) {
                el.onclick = function() {
                    var id;
                    if (el.options) {
                        id = el.options.id;
                        var thread = $.Html.thread[id],
                            path = $.delHost($.parseUri(el.href).path);
                        if (thread && path == $.delHost($.parseUri(thread.history.currentUrl()).path)) {
                        } else if (path != $.delHost($.parseUri($.replaceLinkEqual(location.href, 1)).path)) return;
                    } else {
                        id = ops.layer == document ? null : ops.layer.id;
                    }
                    var useHistory = ops.ops ? !ops.ops.nohistory : 1;
                    return anchor2target(anchor, useHistory, id);
                }
                el.anchored = 1;
            }
            else {
                $.addEvent(el, 'click', function() { nonAnchoredLinkCliked(el) });

            }

        }
    })

    var nonAnchoredLinkCliked = function(el) {
        var hash = $.replaceLinkEqual($.getHash(), 1);

        indexOfAnchor = hash.indexOf(':' + D.ANCHOR.prefix);
        if (indexOfAnchor > -1) {
            hash = hash.substring(0, indexOfAnchor);
        }

        var rhash = $.replaceLinkEqual(hash);
        if ($.getHash() != rhash) {
            $.setHash(rhash);
        }
    }

    var anchorListener = function(ops) {
        if (ops && ops.owner && ops.owner.options.nohistory) return;
        var hash = $.getHash(),
            prevAx = $.parseAxHash($.History.previous, D.ANCHOR.prefix);
        curAx = $.parseAxHash(hash, D.ANCHOR.prefix);
        for (var id in curAx) {
            var anchor = curAx[id];
            var ownerAnchor = ops && ops.owner ? $.parseUri(ops.url).anchor : 1;
            if (ops && ops.id == id ? ownerAnchor : prevAx[id] != anchor) {
                anchor2target(anchor);
            }
        }
    }

    $.linkEqual[D.ANCHOR.prefix + ':' + D.ANCHOR.id + ':'] = '$';
    $.onReady(function() {
        $.History.prefixListener[D.ANCHOR.prefix] = anchorListener;
        anchorListener({ id: D.ANCHOR.id });
        $.Html.onall('load', anchorListener);
        $.History.on('beforeadd', function(ops) {
            var hash = ops.hash.replaceAll('#:', ':');
            var anchor = $.parseUri(ops.url).anchor;
            hash = hash.replace('#' + anchor, ':' + D.ANCHOR.prefix + ':' + ops.id + ':' + anchor);
            if (!hash.startWith('#')) hash = '#' + hash;
            return hash;
        })
    })

    $.scroll = function(el, anim, recursive) {
        scroll($.get(el), 0, 1, anim, recursive)
    }

})(SRAX)

