var rt = rt || {};

rt = {
    vars: {},
    culture: $('meta[http-equiv=Content-Language]').attr('content'),
    language: null,

    init: function () {
        this.print.init();
        this.eraseInput.init();
        this.toggleLogIn.init();
        this.showFaqText.init();
        this.toggleCategories.init();
        this.faq.init();
        this.imgfix();
        this.startPageTeaserAutoSize();
        this.mobileMenu();

        $(window).load(function () {
            rt.startpageSlideShow();
        });

        rt.language = rt.culture.split('-')[0];
    },

    startPageTeaserAutoSize: function () {
        var maxHeight = 0;
        $('#bottomTeasers > div').each(function () {
            var height = $(this).outerHeight();
            if (height > maxHeight)
                maxHeight = height;
        }).css({ height: maxHeight + 'px' });
    },

    startpageSlideShow: function () {
        if ($('body').hasClass('fluidMode'))
            return;

        var slideShow = new SlideShow();
        slideShow.init('#brandingSlides', '#brandingSlides .branding');
    },

    imgfix: function () {
        var paragraph = $('.body *:eq(0)');
        if (paragraph.hasClass('caption')) {
            paragraph.css('marginTop', '3px');
        }
    },
    mobileMenu: function () {
        $('ul.nav-supp-login').mobileMenu({
            switchWidth: 780,                   //width (in px to switch at)
            topOptionText: 'V&auml;lj tj&auml;nst',     //first option text
            indentString: '&nbsp;&nbsp;&nbsp;'  //string for indenting nested items
        });
    },

    eraseInput: {
        init: function () {

            $('#search input').focus(function () {
                if ($(this).val() === $(this).attr('title')) {
                    $(this).val("");
                }
            }).blur(function () {
                if ($(this).val() === "") {
                    $(this).val($(this).attr('title'));
                }
            });
            $("form").submit(function () {
                if ($('#search .search-main').val() == $('#search .search-main').attr('title')) {
                    $('#search .search-main').val("");

                }
            });
        }
    },
    print: {
        init: function () {
            $('.print').show().click(function () {
                _gaq.push(['_trackEvent', 'Links', 'Print']);
                window.print();
                return false;
            });
        }
    },
    faq: {
        init: function () {
            rt.faq.paging();
        },

        paging: function () {
            $('#show-next').live('click', function (e) {
                e.preventDefault();

                var data = $(this).data();
                service.pagingList(data.pageId, data.page, data.query, data.categories, rt.language, function (resp) {
                    $('#page').html(resp.value);
                });
            });
        }
    },
    showFaqText: {
        init: function () {
            $('.faqArticleLink').live('click', function (e) {
                e.preventDefault();
                $(this).prev().removeClass("shortenedFaqArticleText");
                $(this).remove();
            });

        }
    },
    toggleCategories: {
        init: function () {
            $('#search-block #allResults').click(function (e) {
                e.preventDefault();

                if (!$(this).hasClass('current')) {
                    $('#search-block .tags a.current:not(#allResults)').removeClass('current');
                    $(this).addClass('current');
                    $('#Categories').val('');

                    pageInfo.categories = '';

                    service.pagingList(pageInfo.pageId, 1, pageInfo.query, pageInfo.categories, rt.language, function (resp) {
                        $('#page').html(resp.value);
                        $('.totalHits').text(pageInfo.totalCount);
                    });
                }
            });
            $('#search-block .tags a:not(#allResults)').click(function (e) {
                e.preventDefault();
                $(this).toggleClass('current');

                if ($('#search-block .current').length == 0)
                    $('#allResults').addClass('current');
                else
                    $('#allResults').removeClass('current');

                var categories = '';
                $('#search-block .tags a.current:not(#allResults)').each(function (i, element) {
                    categories += $(element).data('category') + ',';
                });
                $('#Categories').val(categories);
                pageInfo.categories = categories;

                service.pagingList(pageInfo.pageId, 1, pageInfo.query, pageInfo.categories, rt.language, function (resp) {
                    $('#page').html(resp.value);
                    $('.totalHits').text(pageInfo.totalCount);
                });
            });

        }
    },
    toggleLogIn: {
        resource: null,

        init: function () {
            var login = $('#login');
            var loginLink = $('#login a.login');

            rt.toggleLogIn.resource = loginLink.data();

            if (!login.hasClass('open')) {
                login.css({ "margin-top": "-98px" });
                loginLink.toggle(rt.toggleLogIn.open, rt.toggleLogIn.close);
            } else {
                loginLink.text(rt.toggleLogIn.resource.hideText);
                loginLink.toggle(rt.toggleLogIn.close, rt.toggleLogIn.open);
            }
        },

        open: function () {
            $("#login").animate({ marginTop: 0 }, 400);
            $("#login input:first").focus();
            $("#login a.login").text(rt.toggleLogIn.resource.hideText);
            $.cookie('HideLoginBar', null, { path: '/' });
            _gaq.push(['_trackEvent', 'MemberServiceBar', 'OpenBar']);
        },

        close: function () {
            $("#login").animate({ marginTop: -98 }, 400);
            $("#login a.login").text(rt.toggleLogIn.resource.openText);
            $.cookie('HideLoginBar', true, { path: '/' });
            _gaq.push(['_trackEvent', 'MemberServiceBar', 'CloseBar']);
        }
    }

};

$(function () {
    rt.init();
});


var memberServices = {
    init: function () {
        $('#memberServices').bind('load', function () {
            $.getJSON('/services/member/Username?r=' + Math.random(), function (username) {
                if (username == undefined) {
                    $('#login a.login').removeClass('hide');
                    $('#login .loggedIn').addClass('hide');
                    return;
                }

                memberServices.showLoggedInUser(username);
            });
        });
    },

    showLoggedInUser: function (username) {
        $('#login a.login').addClass('hide');
        $('#login .loggedIn').removeClass('hide').show().find('.username').html(username);
    }
};


/**
* jQuery Cookie plugin
*
* Copyright (c) 2010 Klaus Hartl (stilbuero.de)
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
*/
jQuery.cookie = function (key, value, options) {

    // key and at least value given, set cookie...
    if (arguments.length > 1 && String(value) !== "[object Object]") {
        options = jQuery.extend({}, options);

        if (value === null || value === undefined) {
            options.expires = -1;
        }

        if (typeof options.expires === 'number') {
            var days = options.expires, t = options.expires = new Date();
            t.setDate(t.getDate() + days);
        }

        value = String(value);

        return (document.cookie = [
            encodeURIComponent(key), '=',
            options.raw ? value : encodeURIComponent(value),
            options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
            options.path ? '; path=' + options.path : '',
            options.domain ? '; domain=' + options.domain : '',
            options.secure ? '; secure' : ''
        ].join(''));
    }

    // key and possibly options given, get cookie...
    options = value || {};
    var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
    return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
};
/*
 * MBP - Mobile boilerplate helper functions
 */
(function(document){

window.MBP = window.MBP || {}; 

// Fix for iPhone viewport scale bug 
// http://www.blog.highub.com/mobile-2/a-fix-for-iphone-viewport-scale-bug/

MBP.viewportmeta = document.querySelector && document.querySelector('meta[name="viewport"]');
MBP.ua = navigator.userAgent;

MBP.scaleFix = function () {
  if (MBP.viewportmeta && /iPhone|iPad/.test(MBP.ua) && !/Opera Mini/.test(MBP.ua)) {
    MBP.viewportmeta.content = "width=device-width, minimum-scale=1.0, maximum-scale=1.0";
    document.addEventListener("gesturestart", MBP.gestureStart, false);
  }
};
MBP.gestureStart = function () {
    MBP.viewportmeta.content = "width=device-width, minimum-scale=0.25, maximum-scale=1.6";
};


// Hide URL Bar for iOS
// http://remysharp.com/2010/08/05/doing-it-right-skipping-the-iphone-url-bar/

MBP.hideUrlBar = function () {
    /iPhone/.test(MBP.ua) && !pageYOffset && !location.hash && setTimeout(function () {
      window.scrollTo(0, 1);
    }, 1000);
};
})(document);
/*
 * jQuery Responsive menu plugin by Matt Kersley
 * Converts menus into a select elements for mobile devices and low browser widths
 * github.com/mattkersley/Responsive-Menu
 */
(function(b){var c=0;b.fn.mobileMenu=function(g){function f(a){return a.attr("id")?b("#mobileMenu_"+a.attr("id")).length>0:(c++,a.attr("id","mm"+c),b("#mobileMenu_mm"+c).length>0)}function h(a){a.hide();b("#mobileMenu_"+a.attr("id")).show()}function k(a){if(a.is("ul, ol")){var e='<select id="mobileMenu_'+a.attr("id")+'" class="mobileMenu">';e+='<option value="">'+d.topOptionText+"</option>";a.find("li").each(function(){var a="",c=b(this).parents("ul, ol").length;for(i=1;i<c;i++)a+=d.indentString;
c=b(this).find("a:first-child").attr("href");a+=b(this).clone().children("ul, ol").remove().end().text();e+='<option value="'+c+'">'+a+"</option>"});e+="</select>";a.parent().append(e);b("#mobileMenu_"+a.attr("id")).change(function(){var a=b(this);if(a.val()!==null)document.location.href=a.val()});h(a)}else alert("mobileMenu will only work with UL or OL elements!")}function j(a){b(window).width()<d.switchWidth&&!f(a)?k(a):b(window).width()<d.switchWidth&&f(a)?h(a):!(b(window).width()<d.switchWidth)&&
f(a)&&(a.show(),b("#mobileMenu_"+a.attr("id")).hide())}var d={switchWidth:768,topOptionText:"Select a page",indentString:"&nbsp;&nbsp;&nbsp;"};return this.each(function(){g&&b.extend(d,g);var a=b(this);b(window).resize(function(){j(a)});j(a)})}})(jQuery);


//start:Kundo.se

var _kundo = _kundo || {};
_kundo["org"] = "radiotjanst";
_kundo["lang"] = "sv";
_kundo["btn-type"] = "1";
_kundo["image"] = "/Assets/Images/kundo.png";

(function () {
    function async_load() {
        var s = document.createElement('script');
        s.type = 'text/javascript';
        s.async = true;
        s.src = ('https:' == document.location.protocol ? 'https://static-ssl' : 'http://static') +
            '.kundo.se/embed.js';
        var x = document.getElementsByTagName('script')[0];
        x.parentNode.insertBefore(s, x);
    }
    if (window.attachEvent)
        window.attachEvent('onload', async_load);
    else
        window.addEventListener('load', async_load, false);
})();

//end:Kundo.se

function SlideShow() {
    this.container = null;
    this.slides = null;
    this.activeSlideIndex = 0;
    this.slideCount = 0;
    this.slideTimer = null;
    this.slideInterval = 10000; // ms
}

SlideShow.prototype.init = function (containerSelector, slideSelector) {
    var self = this;

    this.container = $(containerSelector);
    this.slides = $(slideSelector);

    this.container.addClass('active');
    this.scrollToSlide(0, false);

    this.slideCount = this.slides.length;

    if (this.slideCount == 1) {
        $('.slideNav', this.container).remove();
        return;
    }

    $('.slide-next', this.container).click(function (e) {
        e.preventDefault();
        self.nextSlide();
    });

    $('.slide-prev', this.container).click(function (e) {
        e.preventDefault();
        self.prevSlide();
    });

    $(window).resize(function () {
        self.scrollToSlide(self.activeSlideIndex, false);
    });

    self.makeUnselectable($('.slideNav', this.container)[0]);

    this.startTimer();
    this.container.hover(function () {
        self.stopTimer();
    }, function () {
        self.startTimer();
    });
};

SlideShow.prototype.startTimer = function () {
    var self = this;
    
    this.slideTimer = setInterval(function () {
        self.nextSlide();
    }, self.slideInterval);
};

SlideShow.prototype.stopTimer = function() {
    clearTimeout(this.slideTimer);
};

SlideShow.prototype.nextSlide = function() {
    this.activeSlideIndex += 1;
    if (this.activeSlideIndex == this.slideCount)
        this.activeSlideIndex = 0;
    this.scrollToSlide(this.activeSlideIndex, true);
};

SlideShow.prototype.prevSlide = function() {
    this.activeSlideIndex -= 1;
    if (this.activeSlideIndex < 0)
        this.activeSlideIndex = this.slideCount - 1;
    this.scrollToSlide(this.activeSlideIndex, true);
};

SlideShow.prototype.scrollToSlide = function(slideIndex, animateSlide) {
    var containerWidth = this.container.width();
    var maxHeight = 0;

    this.slides.each(function(i) {
        var height = $(this).height();

        if (height > maxHeight)
            maxHeight = height;

        var cssInfo = {
            left: ((i - slideIndex) * containerWidth) + 'px',
            width: containerWidth + 'px'
        };

        if (animateSlide) {
            $(this).stop().animate(cssInfo);
        } else {
            $(this).css(cssInfo);
        }
    });
    this.container.css({ height: (maxHeight + 15) + 'px' });
};

SlideShow.prototype.makeUnselectable = function(elem) {
    if (elem) {
        elem.onselectstart = function () { return false; };
        elem.style.MozUserSelect = "none";
        elem.style.KhtmlUserSelect = "none";
        elem.unselectable = "on";
    }
}
