$(function() {
    $(window).resize(function() {
        var small = false;
        if (typeof window.outerWidth != "undefined") {
            small = (window.outerWidth < 1020);
        } else {
            small = (document.body.clientWidth < 985);
        }
        $(document.body).toggleClass("w1024", !small);
    }).resize();
    
    /**
     * Рисование лучей от птички
     */
    if ($("#BIRD").is(":visible")) {
        var topRay = $("#BIRD .top-ray").css({visibility: "visible"});
        var bottomRay = $("#BIRD .bottom-ray").css({visibility: "visible"});
        var cb = $(".content-bar");

        Raphael(topRay[0])
                .path("M " + topRay.width() + " 0 " +
                "L " + topRay.width() + " " + (topRay.height() - topRay.width()) +" " +
                "L 0 " + topRay.height() + " " +
                "L " + topRay.width() + " 0")
                .attr({fill: topRay.css("background-color"), stroke: "none"});
        topRay.css({backgroundColor: "transparent"});

        Raphael(bottomRay[0])
                .path("M " + bottomRay.height() + " 0 " +
                "L " + bottomRay.width() + " 0 " +
                "L 0 " + bottomRay.height() + " " +
                "L " + bottomRay.height() + " 0")
                .attr({fill: bottomRay.css("background-color"), stroke: "none"});
        bottomRay.css({backgroundColor: "transparent"});

        $("#BIRD").bind("reposition", function() {
            $(this).css("top", cb.offset().top + cb.outerHeight() - topRay.height() + bottomRay.height() + 1);
        });

        var oldHeight = 0;
        (function() {
            var h = cb.outerHeight();
            if (h != oldHeight) {
                oldHeight = h;
                $("#BIRD").trigger("reposition");
            }
            setTimeout(arguments.callee, 250);
        })();
    }

    /**
     * Подсвечиваем нужный пункт меню
     */
    var urlStart = location.protocol + '//' + location.hostname;
    $("ul.top-menu > li").each(function(){
        var href = $("a", this).attr("href");
        if (href.charAt(0) != "/") {
             if (href.indexOf(urlStart) == -1) return;
             href = href.substr(urlStart.length);
        }
        if(href != "/" && location.pathname.indexOf(href) == 0) $(this).addClass("selected");
    });

    /**
     * Стрелочки в новостях
     */
    var lastTextNode = function(el) {
        var found = null;
        var ch = el.firstChild;
        while (ch) {
            if (ch.nodeType === 3 /* Node.TEXT_NODE */) {
                if (/\S/.test(ch.nodeValue)) found = ch;
            } else if (ch.hasChildNodes) {
                var f = lastTextNode(ch);
                if (f) found = f;
            }
            ch = ch.nextSibling;
        }
        return found;
    };
    $("div.news-item").each(function() {
        var link = $(this).find("> .title > a");
        var href = link.attr("href");
        link.parent().html(link.html());
        if ($(this).hasClass("with-more")) {
            var node = lastTextNode($(this).find("> .digest")[0]);
            node.nodeValue = node.nodeValue.replace(/\s*$/, "");
            var parentNode = node.parentNode;
            while ($(parentNode).css("display") == "inline") parentNode = parentNode.parentNode;
            $(parentNode)
                    .append("\u00A0<a href='#' class='readmore'>&rarr;</a>")
                    .find("a:last").attr("href", href);
        }
    });

    /**
     * Глоссарий
     */
    (function() {

        var hlClass = "glossary-link";
        var HL = function(node, pattern, data) {
            if(
                node.className == hlClass
                ||
                node.tagName && node.tagName.toLowerCase() == 'a'
            ) return;

            var ch = node.firstChild;
            while (ch) {
                HL(ch, pattern, data);
                ch = ch.nextSibling;
            }

            if(node.nodeType == 3 && !/^\s*$/.test(node.nodeValue)) { // text node
                var val = node.nodeValue;
                var found = val.match(pattern);
                if (found) {
                    var parent = node.parentNode;
                    for(var i = 0; i < found.length; i++) {
                        var hlSpan = document.createElement("span");
                        hlSpan.className = hlClass;
                        hlSpan.appendChild(document.createTextNode(found[i]));
                        hlSpan.setAttribute("data-hl", data);
                        hlSpan.setAttribute("title", "Что это?");
                        var ni = val.indexOf(found[i]);
                        parent.insertBefore(document.createTextNode(val.substr(0, ni)), node);
                        parent.insertBefore(hlSpan, node);
                        val = val.substr(ni + found[i].length);
                    }
                    parent.insertBefore(document.createTextNode(val), node);
                    parent.removeChild(node);
                }
            }
        };

        var patterns = [];
        for (var i = 0; i < GLOSSARY.length; i++) {
            try {
                patterns.push(new RegExp(GLOSSARY[i], "ig"));
            } catch (ignored) {}
        }

        $(".glossary-hl").each(function() {
            for (var i = 0; i < patterns.length; i++) HL(this, patterns[i], i);
        });

        $(".glossary-link").live('click', function() {
            var o = $(this).offset();
            $("#glossary-popup")
                .css({
                    left:   o.left + $(this).width() / 2,
                    top:    o.top + $(this).height()
                })
                .find("> .content")
                    .html("Загрузка…")
                    .load("/glossary-popup?n=" + $(this).data("hl"))
                .end()
                .show();
            return false;
        });
        $("#glossary-popup").click(false);
        $("#glossary-popup .close").click(function() { $("#glossary-popup").hide(); });
        $(document.body).click(function() { $("#glossary-popup").hide(); });
    })();

    /**
     * Страница вакансий
     */
    $(".vacancies > h2").each(function() {
        $(this)
            .nextUntil("h2").andSelf()
            .wrapAll("<div class='career-item' />")
            .parent()
            .before(
                $("<div class='career-link'></div>")
                    .text($(this).text())
                    .wrapInner("<span />")
            );
        $(this).nextAll().wrapAll("<div class='career-item-text' />");
    });
    $(".career-link span").live('click', function() {
        $(this).parent()
            .siblings(".career-item").hide().end()
            .siblings(".career-link").show().end()
            .hide().next().show();
        $("#BIRD").trigger("reposition");
    });
    $(".career-link").show();
    $(".career-item").hide();
    $(".career-item:first").addClass("first");

    /**
     * Капча
     */
    (function() {
        var CAPTCHA_ID = 3567;
        var renewCaptcha = function(form, id) {
            var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
	        var key = "";
	        for (var i = 0; i < 32; i++) {
		        var rnd = Math.floor(Math.random() * (chars.length-1));
		        key += chars.substring(rnd, rnd+1);
	        }
            $(form).find("img.captcha-image").attr("src", "http://webspamprotect.com/captcha.php?id=" + id + "&key=" + key);
            $(form).find("input[name='captcha_key']").val(key);
        };

        $("img.captcha-refresh").live("click", function() {
            renewCaptcha($(this).closest("form"), CAPTCHA_ID);
        });
    })();

    // Плейсхолдеры
    $('.feedback-form input, .feedback-form textarea').placeholder();

    if (location.hash == "#thanx") {
        $("#thanx-message").show();
        location.hash = "";
    }

    $("#contacts-map").load(function() {
        $("#BIRD").trigger("reposition");
    });

    var mp3PlayerCode =
        '<object type="application/x-shockwave-flash" data="http://flash-mp3-player.net/medias/player_mp3_maxi.swf" width="180" height="16" style="vertical-align:middle;">\
            <param name="movie" value="http://flash-mp3-player.net/medias/player_mp3_maxi.swf" />\
            <param name="bgcolor" value="#ffffff" />\
            <param name="FlashVars" value="mp3=[MP3URL]&amp;width=180&amp;height=16&amp;volume=75&amp;showvolume=1" />\
        </object>';
    $(".main-content-block a").each(function() {
        if ($(this).text().toLowerCase() == "mp3") {
            $(this).replaceWith(mp3PlayerCode.replace("[MP3URL]", encodeURIComponent(this.href)));
        }
    });

    $(".news-body img").each(function() {
        var $t = $(this);
        var w = $t.attr("width");
        var h = $t.attr("height");
        if (w > 511) $t.css({width: 511, height: Math.round(h * 511 / w)});
    });

    $(".content-bar.for-3-columns .item-content img").each(function() {
        var $t = $(this);
        var w = $t.attr("width");
        var h = $t.attr("height");
        if (w > 650) $t.css({width: 650, height: Math.round(h * 650 / w)});
    });
});

