// Init, extend jquery + create functions
$jq = jQuery.noConflict();
(function($) {
    // AdTech
    appendAd = function (id) { 
        var pos = document.getElementById("ad" + id); 
        var ad = document.getElementById("tmpad" + id);
        if (pos && ad) { 
            pos.style.height = "auto"; 
            var script = ad.getElementsByTagName("script"); 
            if (script != null) { 
                for (var i = 0; i < script.length; i++) { 
                    var s = script[i]; 
                    s.src.replace = "http://static.gfx.no/common/js/empty.js"; 
                }
            }
            var body = ad.parentNode; 
            body.removeChild(ad); 
            pos.innerHTML = ""; 
            pos.appendChild(ad); 
        } 
    }

    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);
        }
    });


})(jQuery);


function getTMqs(prot, furl, dotl, tmac, tmcc, enc, sec) {
    var n = new Date();

    if (sec) {
        var loc = window.location + '&' + sec.join('&');
    } else {
        var loc = window.location;
    }

    if (parent.frames) {
        var ref = parent.document.referrer;
    } else {
        var ref = document.referrer;
    }

    var qs = loc + '*' + furl + '*' + dotl + '*' + ref + '*' + navigator.javaEnabled() + '/';
    if (window.screen) {
        qs += screen.width+'x'+screen.height + '/' + screen.colorDepth + '/';
    } else {
        qs += '//';
    };
    qs += tmac + '/' + tmcc + '/' + enc + '/' + n.getTime() + '/';
    
    var tmImg1 = '<img name="tmImg1" border="0" height="1" width="1" onLoad="nxtImg(\'tmImg2\', \'' + prot + '\', \'' + qs + '\')">';
    var tmImg2 = '<img name="tmImg2" border="0" height="1" width="1">';
    document.write(tmImg1);
    document.write(tmImg2);
    nxtImg('tmImg1', prot, n.getTime()); 
}

var tmLoc = 'statistik-gallup.net';
var tmVer = 'V11';
var tmLd = false;
function nxtImg(img, prot, qs)
{
   if((!document.images) || tmLd) return;
   tmLd = true;
   var n = '';
   if(img == 'tmImg1') {
      n = prot + '://' + tmLoc + '/VC' + qs;
   }
   else if(img == 'tmImg2') {
      n = prot + '://' + tmLoc + '/' + tmVer + qs;
   }
   if(document.images[img].src.indexOf(n)<0) {
      document.images[img].src = n;
   }
   tmLd = false;
}


$jq(function($) {
    $("#mainSearch label").inFieldLabels({ fadeOpacity: 0.3 });
    $("#nav").click(function(e) { var f = $(e.target); if (f.is("a")) { $(this).find("li.selected").removeClass("selected"); f.parent().addClass("selected"); } });
    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);
            }
        });
    }); */

});
