// Init, extend jquery + create functions
$jq = jQuery.noConflict();
(function($) {
    // AdTech

appendAd = function(elementMoveFrom, elementMoveTo) { var newPos = document.getElementById(elementMoveTo); var oldPos = document.getElementById(elementMoveFrom); if (newPos && oldPos) { var x = oldPos.getElementsByTagName("script"); if (x !== null) { for (i = 0; i < x.length; i++) { x[i].parentNode.removeChild(x[i]); } } var body = oldPos.parentNode; body.removeChild(oldPos); newPos.innerHTML = ""; newPos.appendChild(oldPos); }
}

    if(window.adgroupid == undefined){window.adgroupid = Math.round(Math.random()*100000);}

    $.extend({
        Carousel: function(data) {
            $.Carousel.prototype.data = data;
            $.Carousel.prototype.current = 0;
            $.Carousel.prototype.move = function(pos) {
                var len = this.data.length;
                return this.data[Math.abs(this.current = (this.current + (pos ? 1 : len - 1)) % len)];
            }
            $.Carousel.prototype.next = function() {
                return this.move(1);
            }
            $.Carousel.prototype.prev = function() {
                return this.move(0);
            }
            $.Carousel.prototype.getCurrent = function() {
                return this.data[this.current];
            } 
        },
        topStories: function() {
            var timeoutCb,
            elems = $(".topStories .preamble"),
            c = new $.Carousel($.makeArray(elems)),
            pagination = $("<li><ul class=\"pagination\" /></li>")
                            .appendTo(elems.parent()),
            handler = function(name) {
                elems.addClass("hide");
                var elem = c[name]();
                $(".pagination", pagination)
                    .find("li")
                    .removeClass("selected")
                    .end()
                        .find("#t-" + $(elem).attr("id").replace("c-", ""))
                        .addClass("selected");
                $(elem).removeClass("hide");
            },
            next = $("<span class=\"next\">Next</span>")
                .click(function() {
                    handler("next");
                    clearInterval(timeoutCb);
                }
            ).appendTo(pagination),
            prev = $("<span class=\"prev\">Prev</span>")
                .click(function() {
                    handler("prev");
                    clearInterval(timeoutCb);
                }
            ).appendTo(pagination);

            elems.each(function(i) {
                var that = $(this);
                if (i != 0)
                    that.addClass("hide");
                that.attr('id', "c-" + i);
                var count = i+1;
                var li = $("<li id='t-" + i + "' class='inline'><a href=\"#\">" + count + "</a></li>")
                    .click(function(e) {
                        e.preventDefault();
                        c.current = i;
                        clearInterval(timeoutCb);
                        pagination
                            .find("li.selected")
                            .removeClass("selected");
                        $(this).addClass("selected");
                        elems.addClass("hide");
                        $(c.getCurrent()).removeClass("hide");
                    });
                if (i == 0)
                    li.addClass("selected");
                pagination.find(".pagination").append(li)
            });
            timeoutCb = setInterval(function() {
               handler("next");
            },
            4000);
        }
    });

    sticky = function(selector, triggerSelector, css, background) {
            var elem = $(selector),
                triggerElem = triggerSelector ? $(triggerSelector) : elem,
                triggerElemHeight = triggerElem.outerHeight(true),
                elemHeight = elem.outerHeight(true),
                win = $(window),
		doc = $(document),
                positionState = 'absolute',
                stopEl = $("#footer"),
                oldCss = {
                    'position': elem.css('position'),
                    'top': elem.css('top'),
                    'left': elem.css('left')
                };
                css = $.extend({
                    'position': 'fixed',
                    'top': 0,
                    'left': elem.offset().left
                }, css);

                win.bind('resize', function(e) {
                        positionState = 'absolute';
                        elem.css({
                            'left': elem.offset().left 
                        });
                });
            if (background === true)
                css.backgroundAttachment = 'fixed';
            win.bind('scroll', function() {
                var stop = Math.round(stopEl.offset().top);
                if ((win.scrollTop() + elemHeight) > stop - 50) {
                    elem.css({ top: stop - elemHeight, position: 'absolute', left: oldCss.left });
                    positionState = oldCss.position;
                }
                else if (win.scrollTop() > triggerElemHeight) {
                    if (positionState == 'fixed') return;

                    elem.css({
                        top: css.top,
                        position: css.position,
                        left: elem.offset().left
                    });
                    positionState = css.position;
                    if (triggerElem.css('position') === 'fixed')
                        elem.css('top', 0);
                }
                else {
                    positionState = oldCss.position;
                    elem.css(oldCss);
		    elem[0].style.zoom = 1;
                }
            });
        }

	$(window).bind("bodyLoaded", function() {
		$("body").delegate("#nav", "click", function(e) {
				var f = $(e.target); if (f.is("a")) { $(this).find("li.selected").removeClass("selected"); f.parent().addClass("selected"); } });
	});
/*    $(window).load(function() {
        sticky("div.sticky");
    });*/
})(jQuery);

$jq(function($) {
    $("#mainSearch label").inFieldLabels({ fadeOpacity: 0.3 });
    if ($("#search").length > 0) {
        $("#searchFilter .toggleFilters")
            .click(function(e) {
                e.preventDefault();
                $("#searchFilter .filters").toggleClass("hide");
            });
    }

    if ($("#quiz").length > 0) {
        $(".submit")
            .click(function(e) {
                if ($(".alternatives input").is(":checked"))
                    this.form.submit();
            });
    }

    if ($("#article").length > 0) {
        var imageCarousel = $(".mainMedia.imageCarousel"),
        imgUrls = [];

        imageCarousel
            .find("li:not(.prev, .next) a")
            .each(function() {
                $.imagePreload(this.href);
                imgUrls.push(this);
            });

        var c = new $.Carousel(imgUrls);

        imageCarousel
            .find(".next")
                .click(function(e) {
                    e.preventDefault();
                    var el = $(c.next());
                    imageCarousel
                        .find("img:first")
                            .attr({
				'src': el.attr('href'),
				'alt': el.attr('title')
				})
                        .end()
			.find(".caption cite").text(el.attr('title'))
                        .end()
                        .find("li:not(.prev, .next) a")
                            .removeClass("selected");
                    el.addClass("selected");
                })
            .end()
            .find(".prev")
                .click(function(e) {
                    e.preventDefault();
                    var el = $(c.prev());
                    imageCarousel
                        .find("img:first")
                            .attr({
				'src': el.attr('href'),
				'alt': el.attr('title')
				})
                        .end()
			.find(".caption cite").text(el.attr('title'))
                        .end()
                        .find("li:not(.prev, .next) a")
                            .removeClass("selected");
                    el.addClass("selected");
                });
        
        imageCarousel
            .find("li:not(.prev, .next) a")
            .each(function(i) {
                var that = $(this);
                that.click(function(e) {
                    e.preventDefault();
                    var that = $(this);
                    c.current = i;
                    imageCarousel
                        .find("img:first")
                            .attr({
				'src': that.attr('href'),
				'alt': that.attr('title')
				})
                        .end()
			.find(".caption cite").text(that.attr('title'))
			.end()
                        .find("li:not(.prev, .next) a")
                            .removeClass("selected");
                    that.addClass("selected");
                });
            })
    }

/*    $("li.preamble a").each(function(i) {
        $(this).mousedown(function(e) {
            var that = $(this),
            hrf = that.attr("href");
            if (hrf.indexOf("go.tek.no") == -1) {
                hrf = "http://" + location.host + hrf;
                hrf = "http://go.tek.no/?url=" + encodeURIComponent(hrf) + "&pid=" + i;
                that.attr("href", hrf);
            }
        });
    }); */

});

