/* Global variables */
var WindowObjectReference = null; // Used in the openWindow function

/* Handy functions */
Object.extend = function (destination, source) {
    for (var property in source) {
        destination[property] = source[property];
    }
    return destination;
}

Object.to_s = function (source, seperator, combiner) {
    var sep = seperator || ',';
    var comb = combiner || '=';
    var ret = '';
    for (var i in source) {
        ret += i + comb + source[i] + sep;
    }
    return rtrim(ret, sep);
}

function rtrim(string) {
    regexp = (!arguments[1]) ? new RegExp('\s+$') : new RegExp(arguments[1] + '$');
    return string.replace(regexp, '');
}

function ltrim(string) {
    regexp = (!arguments[1]) ? new RegExp('^\s+') : new RegExp('^' + arguments[1]);
    return string.replace(regexp, '');
}

function trim(string) {
    return ltrim(rtrim(string));
}

function openWindow(href, title, attributes) { // opens a popup window, the viewport options can be set by the hash attributes.
    if (WindowObjectReference == null || WindowObjectReference.closed || WindowObjectReference.location != href) {
        var title = title || ''
        var atts = Object.extend({
            top: 0,
            left: 0,
            width: 'auto',
            height: 768,
            scrollbars: 'yes',
            resizable: 'yes',
            location: 'no',
            status: 'no'
        }, attributes || {});
        WindowObjectReference = window.open(href, title, Object.to_s(atts));
    }
    else {
        WindowObjectReference.focus();
    }
}

function printDocument(e) {
    if (!window.print) return; // Add error handling (alert?)
    window.print();
    e.preventDefault();
}

function CosmeticRules() {
    $("ul.sort-by li:first-child").addClass("first");
    $("ul.sort-by2").addClass("bg");
    $("th:first-child, #cm td.tableheadclass:first-child").each(function () { $(this).addClass("first"); });
    $("th:last-child, #cm td.tableheadclass:last-child").each(function () { $(this).addClass("last"); });
    $("tr:even").addClass("even");
    $("body.shop #content ul.articles.products li:odd").addClass("even");
    $(".highlight:visible").highlightFade(null, 2000, null, "exponential"); // Higlight page elements (see jquery_plugins.js)
    $("#cm div.clmn-v2:odd").addClass("even-v2");

    $("div.stock-indication div.clmn:odd").addClass("odd");

    $('.analyze-small-list').each(function () {
        $(this).find('ol li:last').addClass('last');
        $(this).find('ol li:odd').addClass('odd');
    });

    $('.analyze-small-list').each(function () {
        $(this).find('ul li:last').addClass('last');
        $(this).find('ul li:odd').addClass('odd');
    });

    $('.analyze table').each(function () {
        $(this).find('tr:last').addClass('last');
    });

    $('.about-analyze ul:last').each(function () {
        $(this).addClass('last');
    })


    var columns = $("#cm div.clmn:odd").addClass("even");

    /* IE specifics */
    /*
    @cc_on
    @if (@_win32)
    @columns.after("<hr>"); // Extra <hr> because of IE6 (may be possible to fix in the css) 
    $("#popular-products li.breaker").before("<hr>"); // Extra <hr> because of IE6 (may be possible to fix in the css)
    $("div.nice-form input[type='submit']").addClass("submit");
    $("div.nice-form input[type='reset']").addClass("reset");
    $("div.nice-form input[type='image']").addClass("image-submit");
    $("#cm div.article-list ul.articles div.body").after("<hr>"); // Extra <hr> because of IE6 (may be possible to fix in the css) 
    @end
    @
    */
}

function FunctionalRules() {
    $(".close-this a").click(function (e) {
        $(this).parents().each(function () { if (this.className == "nice-form") return $(this).toggle(); });
        e.preventDefault();
    });
    $("#tip-friend-container:visible").hide()
    $("a.forced-external").bind("click", function (e) {
        openWindow(this.href, this.target || '', { width: 580 });
        e.preventDefault();
    });
    $("#print-me").click(printDocument);
    $("#tip-friend").click(function (e) {
        var _b = $("#bookmark-me-container");
        var _t = $("#tip-friend-container");
        _b.toggle();
        _t.toggle();
        $("#tip-friend-container .close-this a").unclick();
        $("#tip-friend-container:visible .close-this a").bind("click", function (_e) {
            _t.toggle();
            _b.toggle();
            _e.preventDefault();
        });
        e.preventDefault();
    });
}

/* Event setters and element accesors */
$(document).ready(function () {
    $(".showhide").live("click", function () {
        $($(this).attr("href")).toggle();
        return false;
    });


    if (!document.getElementById("memberlist2")) {
        FunctionalRules();
        CosmeticRules();
    }

    //$("div.column").maxHeight({unit: 'em', base: 11, exclude: '#cm'});

    $("#site-nav li a:contains('Bokhandel')").tooltip({
        delay: 0,
        showURL: false,
        track: true,
        left: -4,
        top: 20,
        bodyHandler: function () {
            return $("<img/>").attr("src", "../images/pic-bokhandel-1.gif");
        }
    });

    /* ACCORDION */
    /*$('#result-list').accordion({
    alwaysOpen: true,
    autoHeight: false,
    active: "a.link-wrong"
    });*/

    var count = $('#result-list ul li').length + 1;
    for (i = 1; i < count; i++) {
        if ($('#answer-' + i + ' a').hasClass('link-right')) {
            $('#answer-' + i + ' div').hide();
        }
        $('#answer-' + i + ' a').click(function () {
            $(this).next().toggle('fast');
        });
    }

    /* SELECT CONTENT INPUT-FIELD */
    $('#t-url').click(function () {
        $(this).focus().select();
    })

    /* SITESEEKER */

    $(".search-tab-ul a[href^='#']").click(function () {
        var tag = $(this).attr('href');
        $(".search-container .search").hide();
        $(".search-container " + tag).show();
        $('#search-menu li').removeClass('ui-tabs-selected');
        $(this).parent('li').addClass('ui-tabs-selected');
        return false;
    });

    /***** BLUR ALL LINKS AND BUTTONS *****/
    $('a, #submit-site, #submit-activities, #submit-faq, #submit-forum').click(function () {
        $(this).blur();
    });

    /***** TOOLTIP *****/
    $('#site-question, #activities-question, #faq-question, #forum-question').tooltip({
        track: true,
        delay: 0,
        showURL: false,
        extraClass: 'question',
        top: -120,
        left: -140
    });

    /* $('#sort-relevans-site, #sort-relevans-activities, #sort-relevans-faq').addClass('active'); */

    //$('#container > ul#search-menu').tabs();	

    $('#more-options').hide();

    $('#site-search-result-relevans ul li:last, #site-search-result-date ul li:last, #activities-search-result-relevans ul li:last, #activities-search-result-date ul li:last, #faq-search-result-relevans ul li:last, #faq-search-result-date ul li:last, #forum-search-result-relevans ul li:last, #forum-search-result-date ul li:last, #empty-search-result li:last').addClass('last');

    /***** SELECT ALL *****/
    $("a[href='#select_all']").click(function () {
        $("#" + $(this).attr('rel') + " INPUT[type='checkbox']").attr('checked', true);
        $(this).attr('href', '#select_none');
        return false;
    });

    /***** TOGGLE ALL *****/
    $("a[href='#toggle_all']").toggle(function (event) {
        $("#" + $(this).attr('rel') + " INPUT[type='checkbox']").attr('checked', true);
        $(this).attr('title', 'Avmarkera alla');
        event.preventDefault();
    }, function (event) {
        $("#" + $(this).attr('rel') + " INPUT[type='checkbox']").attr('checked', false);
        $(this).attr('title', 'Markera alla');
        event.preventDefault();
    });

    /***** SELECT NONE *****/
    $("a[href='#select_none']").click(function () {
        $("#" + $(this).attr('rel') + " INPUT[type='checkbox']").attr('checked', false);
        $(this).attr('href', '#select_all');
        return false;
    });

    /***** INVERT SELECTION *****/
    $("a[href='#invert_selection']").click(function () {
        $("#" + $(this).attr('rel') + " INPUT[type='checkbox']").each(function () {
            $(this).attr('checked', !$(this).attr('checked'));
        });
        return false;
    });

    /***** TOGGLE MORE LOCAL DIVISIONS *****/
    $('#more-options-link').toggle(function (event) {
        $(this).addClass('active');
        $('#local-division').attr('disabled', 'disabled');
        $('#more-options').show();
        event.preventDefault();
    }, function (event) {
        $(this).removeClass('active');
        $('#local-division').removeAttr('disabled');
        $('#more-options').hide();
        event.preventDefault();
    });

    /***** AUTOCOMPLETE, LOCAL DIVISIONS *****/
    //var divisions = '';
    //$("#more-options input:checkbox").each( function(){
    //	divisions += $(this).val() + ',';
    //});
    //    var divisions = 'Alingsås,Alvesta,Arvika/Eda,Bengtsfors/Ed,Bergslagen,Boden,Bollnäs/Voxnadalen,Borås,Bromma/Mälaröarna,Burlöv,Danderyd,Eksjö,Enköping/Bålsta/Sala,Eskilstuna,Falkenberg,Falköping,Falun/Borlänge,Finnveden,Gotland,Gällivare/Malmberget,Gävle,Göteborg City,Göteborg Hisingen,Göteborg Väst,Göteborg Öst,Habo/Mullsjö,Halmstad,Haninge/Nynäshamn/Tyresö,Haparanda/Övertorneå,Helsingborg,Herrljunga/Vårgårda,Hjo/Tibro/Karlsborg,Huddinge,Hudiksvall,Härnösand,Hässleholm,Höganäs,Järfälla/Kungsängen,Jönköping,Kalix,Kalmar/Nybro,Karlshamn/Olofström,Karlskoga,Karlskrona,Karlstad,Katrineholm/Flen/Vingåker,Kind,Kiruna,Klippan/Perstorp/Åstorp,Kramfors,Kristianstad,Kristinehamn/Filipstad,Kungsbacka,Kungälv/Ale,Laholm,Landskrona,Lerum,Lidingö,Lidköping/Götene,Limhamn,Linköping,Ljungby/Markaryd,Ljusdal,Lomma/Kävlinge,Ludvika/Smedjebacken/Fagersta,Luleå,Lund,Lycksele,Lysekil,Malmö,Mariestad,Mark,Mellanskåne,Mjölby,Motala/Vadstena,Mölndal,Nacka/Värmdö/Saltsjöbaden,Nordvästra Skåne,Norra Värmland,Norrköping,Norrtälje,Nyköping,Nässjö,Oskarshamn/Högsby,Partille,Piteå,Ronneby,Sandviken,Siljansbygden,Skara,Skellefteå,Skillingaryd/Vaggeryd,Skövde,Sollefteå,Solna/Sundbyberg,Spånga/Vällingby,Staffanstorp,Stenungsund/Orust/Tjörn,Stockholm Globen,Stockholm Kungsholmen,Stockholm Norrort,Stockholm Sydväst,Stockholm Södermalm,Stockholm Vasa,Stockholm Östermalm/Djurgården,Strängnäs,Strömstad/Tanum,Strömsund,Sundsvall,Svalöv,Svedala,Sydnärke,Säffle/Åmål,Söderhamn,Södertälje,Södra Dalarna,Sölvesborg,Tidaholm,Tingsryd,Tranås,Trelleborg,Trollhättan,Täby/Vallentuna,Uddevalla,Ulricehamn,Umeå,Uppsala,Vara/Nossebro,Varberg,Vellinge,Vetlanda/Sävsjö,Vimmerby/Hultsfred,Vänersborg,Västervik,Västerås,Växjö,Ystad,Åkersberga/Vaxholm,Årjäng/Töcksfors,Älmhult/Osby,Öland,Örebro,Örnsköldsvik,Österlen,Östersund'.split(',');
    //	$('#local-division').autocomplete(divisions, {
    //		matchContains: true,
    //		minChars: 2
    //	});

    /***** AUTOCOMPLETE *****/
    var analyzedata = 'Daniel Andersson,Maria Wikdahl,Carl Bjurling,2 Entertain,3 L System,360 Holding,Aarhus Karlshamn,ABB,Academedia,Acando,Acap Invest,Accelerator,A-com,ACSC,Active Biotech,Addnode'.split(',');
    $('#analyze-search').autocomplete(analyzedata, {
        matchContains: true,
        minChars: 2
    });


    /***** ANALYZE QUESTION MARK - INFO *****/
    $('.analyzes').append('<div class="analyze-tooltip" id="analyze-tooltip"><p></p></div>');
    $('.analyze span.info').each(function () {
        var text = $(this).attr('alt');
        $(this).bind('mousemove', function (e) {
            var left = e.pageX + -300;
            var top = e.pageY + -132;
            $('#analyze-tooltip').css('top', top).css('left', left).show().find('p').html(text);
        }).bind('mouseout', function () {
            $('#analyze-tooltip').hide();
        });
    });


    /***** RESIZE IMAGE *****/
    $('.resize img[rel]').overlay({
        color: '#fff',
        left: 190
    }).css('cursor', 'pointer').parent().find('small').append(' <i>Klicka på bilden för en förstoring.</i>');


    $('#more-options input[type=checkbox], #more-options #select-north a, , #more-options #select-east a, #more-options #select-south a, #more-options #select-west a').click(function () {
        var ldsArr = new Array();
        $('#more-options input[type=checkbox][checked]').each(function () {
            ldsArr.push($(this).val());
        });
        $('#selected-ld').html('');
        if (ldsArr.length > 0) {
            $('#selected-ld-container').show();
            var ldsStr = '';
            for (i = 0; i < ldsArr.length; i++) {
                ldsStr += ldsArr[i] + ', ';
            }
            ldsStr = ldsStr.slice(0, -2)
            $('#selected-ld').append(ldsStr + '.');
        } else {
            $('#selected-ld-container').hide();
        }
    });

    /* TAB-MODULE */
    $('.module-tab').each(function () {
        $(this).find('.content').hide();
        $(this).find('ul li:first').addClass('active');
        $(this).find('div:first').show();
        $(this).find('.content').each(function () {
            $(this).find('li:even').addClass('even');
        });
        $(this).find('ul li a').each(function () {
            $(this).bind('click', function () {
                var tabLink = $(this).parent();
                var tabContent = $(this).attr('href');
                var tabContainer = $(this).parent().parent().parent();
                $(tabContainer).find('.content').hide();
                $(tabContainer).find('ul li').removeClass('active');
                $(tabLink).addClass('active');
                $(tabContent).show();
                return false;
            });
        });
    });

});

function addDOMLoadEvent(func) {
    if (!window.__load_events) {
        var init = function () {
            if (arguments.callee.done) return;
            arguments.callee.done = true;
            if (window.__load_timer) {
                clearInterval(window.__load_timer);
                window.__load_timer = null;
            }
            for (var i = 0; i < window.__load_events.length; i++) {
                window.__load_events[i]();
            }
            window.__load_events = null;
        };
        if (document.addEventListener) {
            document.addEventListener("DOMContentLoaded", init, false);
        }
        /*@cc_on@*/
        /*@if (@_win32)
        document.write("<scr" + "ipt id=__ie_onload defer src=//0><\/scr" + "ipt>");
        var script = document.getElementById("__ie_onload");
        script.onreadystatechange = function () {
            if (this.readyState == "complete") {
                init(); // call the onload handler
            }
        };
        /*@end@*/
        if (/WebKit/i.test(navigator.userAgent)) {
            window.__load_timer = setInterval(function () {
                if (/loaded|complete/.test(document.readyState)) {
                    init();
                }
            }, 10);
        }
        window.onload = init;
        window.__load_events = [];
    }
    window.__load_events.push(func);
}

function switchTab(TabContainer, ShowTab, StartTab, EndTab, BaseName) {
    if (document.getElementById) {
        var tabs = document.getElementById(TabContainer).getElementsByTagName("li");
        var tab = document.getElementById(ShowTab);
        var tabcontent = document.getElementById(BaseName + "_" + ShowTab + "_content");
        if (tab.className == "") {
            for (var i = 0; i < tabs.length; i++) {
                if (tabs[i].className == "") {
                    tabs[i].className = "";
                } else if (tabs[i].className == "current") {
                    tabs[i].className = "";
                }
            }
            tab.className = "current";
        } else if (tab.className == "current") {
            for (var i = 0; i < tabs.length; i++) {
                if (tabs[i].className == "current")
                    tabs[i].className = "";
            }
            tab.className = "current";
        }
        for (var i = StartTab; i <= EndTab; i++) {
            document.getElementById(BaseName + "_tab" + i + "_content").className = "hidden";
        }
        tabcontent.className = "content";
    }
}

// Copyright 2006,2007 Bontrager Connection, LLC
// http://bontragerconnection.com/ and http://willmaster.com/
// Version: July 28, 2007
var cX = 0; var cY = 0; var rX = 0; var rY = 0;
function UpdateCursorPosition(e) { cX = e.pageX; cY = e.pageY; }
function UpdateCursorPositionDocAll(e) { cX = event.clientX; cY = event.clientY; }
if (document.all) { document.onmousemove = UpdateCursorPositionDocAll; }
else { document.onmousemove = UpdateCursorPosition; }
function AssignPosition(d) {
    if (self.pageYOffset) {
        rX = self.pageXOffset;
        rY = self.pageYOffset;
    }
    else if (document.documentElement && document.documentElement.scrollTop) {
        rX = document.documentElement.scrollLeft;
        rY = document.documentElement.scrollTop;
    }
    else if (document.body) {
        rX = document.body.scrollLeft;
        rY = document.body.scrollTop;
    }
    if (document.all) {
        cX += rX;
        cY += rY;
    }
    d.style.left = (cX + 12) + "px";
    d.style.top = (cY + 12) + "px";
}
function HideContent(d) {
    if (d.length < 1) { return; }
    document.getElementById(d).style.display = "none";
}
function ShowContent(d) {
    if (d.length < 1) { return; }
    var dd = document.getElementById(d);
    AssignPosition(dd);
    dd.style.display = "block";
}
function ReverseContentDisplay(d) {
    if (d.length < 1) { return; }
    var dd = document.getElementById(d);
    AssignPosition(dd);
    if (dd.style.display == "none") { dd.style.display = "block"; }
    else { dd.style.display = "none"; }
}

/* 
Simple JQuery menu.
HTML structure to use:

Notes: 

Each menu MUST have a class 'menu' set. If the menu doesn't have this, the JS won't make it dynamic
If you want a panel to be expanded at page load, give the containing LI element the classname 'expand'.
Use this to set the right state in your page (generation) code.

Optional extra classnames for the UL element that holds an accordion:

noaccordion : no accordion functionality
collapsible : menu works like an accordion but can be fully collapsed

<ul class="menu [optional class] [optional class]">
<li><a href="#">Sub menu heading</a>
<ul>
<li><a href="http://site.com/">Link</a></li>
<li><a href="http://site.com/">Link</a></li>
<li><a href="http://site.com/">Link</a></li>
...
...
</ul>
// This item is open at page load time
<li class="expand"><a href="#">Sub menu heading</a>
<ul>
<li><a href="http://site.com/">Link</a></li>
<li><a href="http://site.com/">Link</a></li>
<li><a href="http://site.com/">Link</a></li>
...
...
</ul>
...
...
</ul>

Copyright 2007-2010 by Marco van Hylckama Vlieg

web: http://www.i-marco.nl/weblog/
email: marco@i-marco.nl

Free to use any way you like.
*/


jQuery.fn.initMenu = function () {
    return this.each(function () {
        var theMenu = $(this).get(0);
        $('.acitem', this).hide();
        $('li.expand > .acitem', this).show();
        $('li.expand > .acitem', this).prev().addClass('active');
        $('li h3', this).click(
            function (e) {
                e.stopImmediatePropagation();
                var theElement = $(this).next();
                var parent = this.parentNode.parentNode;
                if ($(parent).hasClass('noaccordion')) {
                    if (theElement[0] === undefined) {
                        window.location.href = this.href;
                    }
                    $(theElement).slideToggle('normal', function () {
                        if ($(this).is(':visible')) {
                            $(this).prev().addClass('active');
                        }
                        else {
                            $(this).prev().removeClass('active');
                        }
                    });
                    return false;
                }
                else {
                    if (theElement.hasClass('acitem') && theElement.is(':visible')) {
                        if ($(parent).hasClass('collapsible')) {
                            $('.acitem:visible', parent).first().slideUp('normal',
                            function () {
                                $(this).prev().removeClass('active');
                            }
                        );
                            return false;
                        }
                        return false;
                    }
                    if (theElement.hasClass('acitem') && !theElement.is(':visible')) {
                        $('.acitem:visible', parent).first().slideUp('normal', function () {
                            $(this).prev().removeClass('active');
                        });
                        theElement.slideDown('normal', function () {
                            $(this).prev().addClass('active');
                        });
                        return false;
                    }
                }
            }
    );
    });
};



/*
* 	loopedSlider 0.5.6 - jQuery plugin
*	written by Nathan Searles	
*	http://nathansearles.com/loopedslider/
*
*	Copyright (c) 2009 Nathan Searles (http://nathansearles.com/)
*	Dual licensed under the MIT (MIT-LICENSE.txt)
*	and GPL (GPL-LICENSE.txt) licenses.
*
*	Built for jQuery library
*	http://jquery.com
*	Compatible with jQuery 1.3.2+
*
*/

/*
*	markup example for $("#loopedSlider").loopedSlider();
*
*	<div id="loopedSlider">	
*		<div class="container">
*			<div class="slides">
*				<div><img src="01.jpg" alt="" /></div>
*				<div><img src="02.jpg" alt="" /></div>
*				<div><img src="03.jpg" alt="" /></div>
*				<div><img src="04.jpg" alt="" /></div>
*			</div>
*		</div>
*		<a href="#" class="previous">previous</a>
*		<a href="#" class="next">next</a>	
*	</div>
*
*/

if (typeof jQuery != 'undefined') {
    jQuery(function ($) {
        $.fn.extend({
            loopedSlider: function (options) {
                var settings = $.extend({}, $.fn.loopedSlider.defaults, options);

                return this.each(
					function () {
					    if ($.fn.jquery < '1.3.2') { return; }
					    var $t = $(this);
					    var o = $.metadata ? $.extend({}, settings, $t.metadata()) : settings;

					    var distance = 0;
					    var times = 1;
					    var slides = $(o.slides, $t).children().size();
					    var width = $(o.slides, $t).children().outerWidth();
					    var position = 0;
					    var active = false;
					    var number = 0;
					    var interval = 0;
					    var restart = 0;
					    var pagination = $("." + o.pagination + " li a", $t);

					    if (o.addPagination && !$(pagination).length) {
					        var buttons = slides;
					        $($t).append("<ul class=" + o.pagination + ">");
					        $(o.slides, $t).children().each(function () {
					            if (number < buttons) {
					                $("." + o.pagination, $t).append("<li><a rel=" + (number + 1) + " href=\"#\" >" + (number + 1) + "</a></li>");
					                number = number + 1;
					            } else {
					                number = 0;
					                return false;
					            }
					            $("." + o.pagination + " li a:eq(0)", $t).parent().addClass("active");
					        });
					        pagination = $("." + o.pagination + " li a", $t);
					    } else {
					        $(pagination, $t).each(function () {
					            number = number + 1;
					            $(this).attr("rel", number);
					            $(pagination.eq(0), $t).parent().addClass("active");
					        });
					    }

					    if (slides === 1) {
					        $(o.slides, $t).children().css({ position: "absolute", left: position, display: "block" });
					        return;
					    }

					    $(o.slides, $t).css({ width: (slides * width) });

					    $(o.slides, $t).children().each(function () {
					        $(this).css({ position: "absolute", left: position, display: "block" });
					        position = position + width;
					    });

					    $(o.slides, $t).children(":eq(" + (slides - 1) + ")").css({ position: "absolute", left: -width });

					    if (slides > 3) {
					        $(o.slides, $t).children(":eq(" + (slides - 1) + ")").css({ position: "absolute", left: -width });
					    }

					    if (o.autoHeight) { autoHeight(times); }

					    $(".next", $t).click(function () {
					        if (active === false) {
					            animate("next", true);
					            if (o.autoStart) {
					                if (o.restart) { autoStart(); }
					                else { clearInterval(sliderIntervalID); }
					            }
					        } return false;
					    });

					    $(".previous", $t).click(function () {
					        if (active === false) {
					            animate("prev", true);
					            if (o.autoStart) {
					                if (o.restart) { autoStart(); }
					                else { clearInterval(sliderIntervalID); }
					            }
					        } return false;
					    });

					    //if (o.containerClick) {
					    //						$(o.container,$t).click(function(){
					    //							if(active===false) {
					    //								animate("next",true);
					    //								if(o.autoStart){
					    //									if (o.restart) {autoStart();}
					    //									else {clearInterval(sliderIntervalID);}
					    //								}
					    //							} return false;
					    //						});
					    //					}

					    $(pagination, $t).click(function () {
					        if ($(this).parent().hasClass("active")) { return false; }
					        else {
					            times = $(this).attr("rel");
					            $(pagination, $t).parent().siblings().removeClass("active");
					            $(this).parent().addClass("active");
					            animate("fade", times);
					            if (o.autoStart) {
					                if (o.restart) { autoStart(); }
					                else { clearInterval(sliderIntervalID); }
					            }
					        } return false;
					    });

					    if (o.autoStart) {
					        sliderIntervalID = setInterval(function () {
					            if (active === false) { animate("next", true); }
					        }, o.autoStart);
					        function autoStart() {
					            if (o.restart) {
					                clearInterval(sliderIntervalID);
					                clearInterval(interval);
					                clearTimeout(restart);
					                restart = setTimeout(function () {
					                    interval = setInterval(function () {
					                        animate("next", true);
					                    }, o.autoStart);
					                }, o.restart);
					            } else {
					                sliderIntervalID = setInterval(function () {
					                    if (active === false) { animate("next", true); }
					                }, o.autoStart);
					            }
					        };
					    }

					    function current(times) {
					        if (times === slides + 1) { times = 1; }
					        if (times === 0) { times = slides; }
					        $(pagination, $t).parent().siblings().removeClass("active");
					        $(pagination + "[rel='" + (times) + "']", $t).parent().addClass("active");
					    };

					    function autoHeight(times) {
					        if (times === slides + 1) { times = 1; }
					        if (times === 0) { times = slides; }
					        var getHeight = $(o.slides, $t).children(":eq(" + (times - 1) + ")", $t).outerHeight();
					        $(o.container, $t).animate({ height: getHeight }, o.autoHeight);
					    };

					    function animate(dir, clicked) {
					        active = true;
					        switch (dir) {
					            case "next":
					                times = times + 1;
					                distance = (-(times * width - width));
					                current(times);
					                if (o.autoHeight) { autoHeight(times); }
					                if (slides < 3) {
					                    if (times === 3) { $(o.slides, $t).children(":eq(0)").css({ left: (slides * width) }); }
					                    if (times === 2) { $(o.slides, $t).children(":eq(" + (slides - 1) + ")").css({ position: "absolute", left: width }); }
					                }
					                $(o.slides, $t).animate({ left: distance }, o.slidespeed, function () {
					                    if (times === slides + 1) {
					                        times = 1;
					                        $(o.slides, $t).css({ left: 0 }, function () { $(o.slides, $t).animate({ left: distance }) });
					                        $(o.slides, $t).children(":eq(0)").css({ left: 0 });
					                        $(o.slides, $t).children(":eq(" + (slides - 1) + ")").css({ position: "absolute", left: -width });
					                    }
					                    if (times === slides) $(o.slides, $t).children(":eq(0)").css({ left: (slides * width) });
					                    if (times === slides - 1) $(o.slides, $t).children(":eq(" + (slides - 1) + ")").css({ left: (slides * width - width) });
					                    active = false;
					                });
					                break;
					            case "prev":
					                times = times - 1;
					                distance = (-(times * width - width));
					                current(times);
					                if (o.autoHeight) { autoHeight(times); }
					                if (slides < 3) {
					                    if (times === 0) { $(o.slides, $t).children(":eq(" + (slides - 1) + ")").css({ position: "absolute", left: (-width) }); }
					                    if (times === 1) { $(o.slides, $t).children(":eq(0)").css({ position: "absolute", left: 0 }); }
					                }
					                $(o.slides, $t).animate({ left: distance }, o.slidespeed, function () {
					                    if (times === 0) {
					                        times = slides;
					                        $(o.slides, $t).children(":eq(" + (slides - 1) + ")").css({ position: "absolute", left: (slides * width - width) });
					                        $(o.slides, $t).css({ left: -(slides * width - width) });
					                        $(o.slides, $t).children(":eq(0)").css({ left: (slides * width) });
					                    }
					                    if (times === 2) $(o.slides, $t).children(":eq(0)").css({ position: "absolute", left: 0 });
					                    if (times === 1) $(o.slides, $t).children(":eq(" + (slides - 1) + ")").css({ position: "absolute", left: -width });
					                    active = false;
					                });
					                break;
					            case "fade":
					                times = [times] * 1;
					                distance = (-(times * width - width));
					                current(times);
					                if (o.autoHeight) { autoHeight(times); }
					                $(o.slides, $t).children().fadeOut(o.fadespeed, function () {
					                    $(o.slides, $t).css({ left: distance });
					                    $(o.slides, $t).children(":eq(" + (slides - 1) + ")").css({ left: slides * width - width });
					                    $(o.slides, $t).children(":eq(0)").css({ left: 0 });
					                    if (times === slides) { $(o.slides, $t).children(":eq(0)").css({ left: (slides * width) }); }
					                    if (times === 1) { $(o.slides, $t).children(":eq(" + (slides - 1) + ")").css({ position: "absolute", left: -width }); }
					                    $(o.slides, $t).children().fadeIn(o.fadespeed);
					                    active = false;
					                });
					                break;
					            default:
					                break;
					        }
					    };
					}
				);
            }
        });
        $.fn.loopedSlider.defaults = {
            container: ".container", //Class/id of main container. You can use "#container" for an id.
            slides: ".slides", //Class/id of slide container. You can use "#slides" for an id.
            pagination: "pagination", //Class name of parent ul for numbered links. Don't add a "." here.
            containerClick: true, //Click slider to goto next slide? true/false
            autoStart: 0, //Set to positive number for true. This number will be the time between transitions.
            restart: 0, //Set to positive number for true. Sets time until autoStart is restarted.
            slidespeed: 300, //Speed of slide animation, 1000 = 1second.
            fadespeed: 200, //Speed of fade animation, 1000 = 1second.
            autoHeight: 0, //Set to positive number for true. This number will be the speed of the animation.
            addPagination: false //Add pagination links based on content? true/false
        };
    });
}


var makeLastAdSticky = function (parentContainer) {
    var parentContainer = $(parentContainer),
	kids = $('.ad', parentContainer),
	offset = 8;

    if (kids.length == 1) {
        kids.css('position', 'fixed');
    } else if (kids.length > 1) {
        var lastKid = kids.eq(-1),
		pos = lastKid.position(),
		pos = pos.top,
		win = $(window),
		fixed = 0;

        win.scroll(function () {
            var scroll = win.scrollTop();
            if (!fixed && pos < scroll) {
                lastKid.css({ 'position': 'fixed', 'top': offset });
                fixed = 1
            } else if (fixed && pos > scroll) {
                lastKid.removeAttr('style');
                fixed = 0;
            }
        });
    }
}

jQuery(function ($) {
    $.datepicker.regional['sv'] = {
        closeText: 'Stäng',
        prevText: '&laquo;Förra',
        nextText: 'Nästa&raquo;',
        currentText: 'Idag',
        monthNames: ['Januari', 'Februari', 'Mars', 'April', 'Maj', 'Juni',
        'Juli', 'Augusti', 'September', 'Oktober', 'November', 'December'],
        monthNamesShort: ['Jan', 'Feb', 'Mar', 'Apr', 'Maj', 'Jun',
        'Jul', 'Aug', 'Sep', 'Okt', 'Nov', 'Dec'],
        dayNamesShort: ['Sön', 'Mån', 'Tis', 'Ons', 'Tor', 'Fre', 'Lör'],
        dayNames: ['Söndag', 'Måndag', 'Tisdag', 'Onsdag', 'Torsdag', 'Fredag', 'Lördag'],
        dayNamesMin: ['Sö', 'Må', 'Ti', 'On', 'To', 'Fr', 'Lö'],
        weekHeader: 'Ve',
        dateFormat: 'yy-mm-dd',
        firstDay: 1,
        isRTL: false,
        showMonthAfterYear: false,
        yearSuffix: ''
    };
    $.datepicker.setDefaults($.datepicker.regional['sv']);
});

$(document).ready(function () {

    $('.menu').initMenu();


    $(function () {
        $('#slide-widget-v1').loopedSlider({
            autoStart: 10000
        });
    });

    $(function () {
        $('#slide-widget-v2').loopedSlider({
            autoStart: 9000
        });
    });

    setTimeout("makeLastAdSticky('#owc-ads')", 600);

    $(".datepicker").datepicker();
});
