ah = []; //populates with articles in packages so we can hide them in the normal flow

$(document).ready(function() {
    /* reposition elements in newslist to appear side-by-side */
    positionNewsitems();

    /*Hide articles already in packages*/
    $.each(ah, function(index, value) {
        $('.article' + value).hide();
    });

    /*$('.clickable').click(function()
     {
     if (this.title)
     document.location = this.title;
     });*/

    $('.activatable').mouseover(
        function() {
            $(this).addClass('active');
        }).mouseout(function() {
            $(this).removeClass('active');
        });

    /* Show photo byline on mouseover */
    $('.img').live('mouseover',
        function() {
            $('.caption', this).stop(false, true);
            $('.caption', this).show();
        }).live('mouseout', function() {
            $('.caption', this).fadeOut();
        });

    if (typeof(category) !== 'undefined' && typeof(profile) !== 'undefined') {
        /* Active mainmenu items with current category */
        $('#mainmenu a[rel=' + category + '],#mainmenu a[rel=' + profile + ']').removeClass('inactive').addClass('active');
        /* Activate submenu items with current category */
        $('.submenu a[rel=' + category + '],.submenu a[rel=' + profile + '],#newsmenu a[rel=' + category + '],#newsmenu a[rel=' + profile + ']').addClass('active');
    }

    /*$('#submenu li').bind("mouseenter", function() {
     $('ul', this).stop(false, true);
     $('ul', this).show();
     }).bind("mouseleave", function() {
     $('ul', this).fadeOut();
     });*/

    /* Animated menuitems */
    $('.menu>a.inactive').bind("mouseenter",
        function() {
            $('div', this).stop(false, true).css('z-index', 100).fadeIn('fast');
        }).bind("mouseleave", function() {
            $('div', this).stop(false, true).fadeOut(function() {
                $(this).css('z-index', 0);
            });
        });

    /* Submit poll with Ajax */
    $('form.pollmini').submit(function() {
        $('.loading', this).show();
        var id = this.ID.value;
        $.post(this.action, $(this).serialize(), function(data) {
            $('#pollmini' + id).html(data);
        });
        return false;
    });

    // Popup
    $('a.colorbox').colorbox({iframe: true, width: 642, height: 482, opacity: 0.75});
    $('a.colorbox-image').colorbox({opacity: 0.75, photo: true, current: '{current} av {total}'});
    $('a.colorbox-slideshow').colorbox({opacity: 0.75, photo: true, slideshow: true, slideshowSpeed: 5000, current: '{current} av {total}'});
    $('a.colorbox-sudoku').colorbox({iframe: true, width: 360, height:520, opacity: 0.75, scrollbars: false});
    $('a.colorbox-wow').colorbox({iframe: true, width: 640, height:650, opacity: 0.75});
    $('a.colorbox-scoreradar').colorbox({iframe: true, width: 1000, height:700, opacity: 0.75});

    // Slideshows, not preloaded
    $('a.slideshow-link').click(function() {
        var container = $('.slideshowimages', this.parentNode).empty();
        var loading = $('.slideshowloading', this.parentNode).show();
        loadSlideshow(this.href, container, loading, this);
        return false;
    });

    // Font resize
    $(".textsize").fontScaler({
        target: '.textresize',
        store:true,
        fixed: {character: '', size1: '100', size2: '150',size3: '200', title1: 'Normal', title2: 'Stor', title3: 'Extra stor'}
    });

    /* Timer for blog rotation */
    $(document).everyTime(10000, function() {
        $('.rsscontainer .rssitem:visible').fadeOut('normal', function() {
            ($(this).next().length == 0 ? $('.rssitem:first', $(this).parent()) : $(this).next()).fadeIn();
        });
    });

    $('.latest .menuitem').click(function() {
        $('.box', $(this).parents('.latest')).hide();
        $('.menuitem', $(this).parents('.latest')).removeClass('active');
        $(this).addClass('active');
        $('#' + this.id + '_box').show();
    });

    $('#latestbottom #newsmenu > a').click(function() {
        $('#latestbottom .box').hide();
        $('#latestbottom #newsmenu a').removeClass('active');
        $(this).addClass('active');
        $('#' + this.id + '_box').show();
        return false;
    });

    initInputfields();

    $(".slider").everyTime(6000, function() {
        var slider = $(this);
        var items = $(".item", slider);
        var first = items.filter(':first');
        if(items.length > 1 && !slider.hasClass('hover')) {
            var current = $('.current:first', slider);
            if(current.length == 0) current = first;
            current.animate({left: -current.outerWidth()}, function() { $(this).removeClass('current').hide(); });
            var next = current.next();
            if(next.length == 0) next = first;
            next.css('left', next.outerWidth()).addClass('current').show().animate({left: 0});
        }
    }).mouseover(function() {
       $(this).addClass('hover');
    }).mouseout(function() {
       $(this).removeClass('hover');
    });

    $(".slider-vertical").everyTime(5000, function() {
        var slider = $(this);
        var items = $(".item", slider);
        var first = items.filter(':first');
        if(items.length > 1 && !slider.hasClass('hover')) {
            var current = $('.current:first', slider);
            if(current.length == 0) current = first;
            current.animate({top: -current.outerHeight()}, function() { $(this).removeClass('current').hide(); });
            var next = current.next();
            if(next.length == 0) next = first;
            next.css('top', next.outerHeight()).addClass('current').show().animate({top: 0});
        }
    }).mouseover(function() {
       $(this).addClass('hover');
    }).mouseout(function() {
       $(this).removeClass('hover');
    });

    $('iframe.autoheight').iframeAutoHeight();

//    $(window).resize(positionAds).scroll(positionAds);
});

function loadSlideshow(href, container, loading, link) {
    $.getJSON(href, function(data) {
        $(container).append(
            $('<a>Bild ' + data.current + '</a>')
                .attr({href: data.href, title: unescape(data.title), rel: data.id})
                .addClass('colorbox-slideshow'));
        loading.html('H�mtar bild ' + data.current + '/' + data.total);
        if (data.next) {
            loadSlideshow(data.next, container, loading, link);
        }
        else {
            loading.hide();

            $(link).unbind('click').click(function() {
                $('a:first-child', container).click();
                return false;
            });

            $('a.colorbox-slideshow', container).colorbox({opacity: 0.75, photo: true, slideshow: true, open: true, slideshowSpeed: 5000, current: '{current} av {total}'});
        }
    });
}

function initInputfields() {
    $('.inputfield').focus(
        function() {
            if (this.value == this.defaultValue) this.value = '';
        }).blur(function() {
            if (this.value == '') this.value = this.defaultValue;
        });
}

String.prototype.beginsWith = function(t, i) {
    if (i == false) {
        return (t == this.substring(0, t.length));
    }
    else {
        return (t.toLowerCase() == this.substring(0, t.length).toLowerCase());
    }
};

String.prototype.endsWith = function(t, i) {
    if (i == false) {
        return (t == this.substring(this.length - t.length));
    }
    else {
        return (t.toLowerCase() == this.substring(this.length - t.length).toLowerCase());
    }
};
String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g, '');
};

var maxLength = 500;

function checkMaxLength(e, maxLength) {
    if (e.value.length > maxLength) {
        alert('Max ' + maxLength + ' tecken!');
    }
    return e.value.length <= maxLength;
}

function updateCounter(e, counter, maxLength) {
    var currentLength = e.value.length;
    if (currentLength > maxLength)
        counter.addClass('toomuch');
    else
        counter.removeClass('toomuch');

    counter.html(currentLength);
}

function checkChecked(e, msg) {
    if (!e.checked) {
        alert(msg);
        return false;
    }
    return true;
}

function loadDisqusComments() {
    (function() {
        var dsq = document.createElement('script');
        dsq.type = 'text/javascript';
        dsq.async = true;
        dsq.src = 'http://' + disqus_shortname + '.disqus.com/embed.js';
        (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
    })();
}

function respondToChangeOnNewsList(that) {
    if (that.html() != "") {
        oldHtmlArr[that.attr("id")] = true;
        if ($(".disqus-link").length == 0) {
            clearTimeout(timer2);
        }
        that.unbind("DOMSubtreeModified");
        var html = that.html();
        var numOfComments = html.replace(/[^\d]+/i, "");
        var id = "comments_" + that.attr("id").replace(/[^\d]+/i, "");
        that.remove();
        var target = $("#" + id);
        if (numOfComments !== "0") {
            target.show();
            target.append(html);
        } else {
            target.remove();
        }
    }
}

function respondToChange(that) {
    if (that.html() != "") {
        that.unbind("DOMSubtreeModified");
        clearTimeout(timer);
        var newHtml = that.html().replace(/[^\d]+/i, "");
        var parent = that.parent();
        if (newHtml !== "0") {
            newHtml = parent.html().replace(/<a.*?>.*?<\/a>/i, "") + " " + newHtml;
            replacement = $(document.createElement("a"));
            replacement.attr("href", parent.attr("href"));
            replacement.html(newHtml);
            replacement.show();
            parent.replaceWith(replacement);
        } else {
            parent.remove();
        }
    }
}

/* Topbanner fixed position */
$(document).ready(function() {
    var banner = $("#topbanner");
    var doFixed = $('.isfixed', banner).length > 0;

    if (doFixed) {
        var placeholder = $("#topbanner-placeholder");
        var view = $(window);
        view.bind("scroll resize", function() {
            var placeholderTop = placeholder.offset().top;
            var viewTop = view.scrollTop();
            if ((viewTop > placeholderTop) && !banner.is(".fixed")) {
                placeholder.height(placeholder.height());
                banner.addClass("fixed").find("div:last").show();
            } else if ((viewTop <= placeholderTop) && banner.is(".fixed")) {
                placeholder.css("height", "auto");
                banner.removeClass("fixed").find("div:last").hide();
            }
        });
    }
});

function positionAds() {
    var contentHeight = $('#site').outerHeight(true);
    var bannerHeight = $('#sticky-right-ads').outerHeight(true);
    if (contentHeight > bannerHeight) {
        var windowHeight = $(window).height();
        var windowScrollOffset = $(document).scrollTop();
        var contentOffset = $('#site').offset().top;
        var newTopPosition = 0;
        if (windowScrollOffset > contentOffset) {
            newTopPosition = windowScrollOffset - contentOffset;
        }
        if (newTopPosition > 0 && bannerHeight > windowHeight) {
            newTopPosition = windowScrollOffset - contentOffset + (windowHeight - bannerHeight);
            if (newTopPosition < 0) {
                newTopPosition = 0;
            }
        }
        if (newTopPosition + bannerHeight > contentHeight) {
            newTopPosition = contentHeight - bannerHeight;
        }
        $('#sticky-right-ads').stop();
        $('#sticky-right-ads').animate({ top: newTopPosition + "px" }, 'normal');
    }
}

function twitterWidget(options) {
    var def = {
        version: 2,
        interval: 6000,
        theme: {
            shell: {
                background: '#8ec1da',
                color: '#fff'
            },
            tweets: {
                background: '#fff',
                color: '#000',
                links: '#069'
            }
        },
        features: {
            scrollbar: false,
            loop: true,
            live: true,
            hashtags: true,
            timestamp: true,
            avatars: true,
            toptweets: true,
            behavior: 'default'
        }
    };

    if (TWTR) {
        def.width = options.width;
        def.height = options.height;

        if (options.profile) {
            def.type = 'profile';
            new TWTR.Widget(def).render().setUser(options.profile).start();
        }
        else if (options.search) {
            def.type = 'search';
            def.search = options.search;
            def.title = options.title;
            def.subject = options.search;
            new TWTR.Widget(def).render().start();
        }
    }
}

function positionNewsitems() {
    $('.wantleft').each(function() {
        var right = $(this);
        var left = $('.wantright:first', right.parentNode);
        if (left.length > 0) {
            left.removeClass('dist wantright').addClass('halfleft');
            right.removeClass('dist wantleft').addClass('halfright');
            right.insertAfter(left).after($('<div class="dist"></div>').addClass(left.attr('class')).removeClass("halfleft puff"));
        }
    });
}

