﻿/* ========================  ======================== */
/* ------------------------  ------------------------ */
/* ........................  ........................ */

/* ======================== General ======================== */

/* ------------------------ Set global namespace ------------------------ */

var pnt = {};


/* ------------------------ check display:inline-block support in Gecko browsers (false in FF<3) ------------------------ */


if ($.browser.mozilla) {
    var ver = parseFloat($.browser.version);
    if (ver < 1.9) {
        pnt.mozInlineBlock = true;
    }
}

/* ------------------------ IE 6 detection ------------------------ */

if ($.browser.msie) {
    var ver = parseFloat($.browser.version);
    if (ver < 7) {
        pnt.ie6 = true;
    }
}

/* ------------------------ Force rendering of IE 6 ------------------------ */

pnt.forceIE6rendering = function(which_jQSel) {
    $(this).css('height', '1px');
    $(this).css('height', 'auto');
}

/* ------------------------ DOM load indicator ------------------------ */
pnt.domLoading = function(hasLoaded) {
    if (hasLoaded == 'pageload') {
        $(document.body).removeClass('sys_pageLoading');
    } else if (hasLoaded == 'load') {
        $(document.body).removeClass('sys_domLoading');
    } else {
        $(document.body).addClass('sys_jsActive').addClass('sys_domLoading').addClass('sys_pageLoading');
    }
}

/* ------------------------ Non framed page redirector ------------------------ */
pnt.frameMaker = function(redirectUrl) {
    if (redirectUrl != '') {
        if (parent == self) {
            document.location.href = redirectUrl
        }
    }
}

/* ------------------------ Tab control ------------------------ */

pnt.tab_show = function(me) {
    var tabId = $(me).attr('href');
    $('.section_tabs a').removeClass('sys_tabActive');
    $(me).addClass('sys_tabActive');

    $('#section_content .sys_tabContentActive').removeClass('sys_tabContentActive');
    $(tabId).addClass('sys_tabContentActive');

    $('.pageCtrl_article, .pageCtrl_images, .pageCtrl_video').hide();

    if (tabId == '#tab_article') {
        $('.pageCtrl_article').show();
    }

    if (tabId == '#tab_images') {
        $('.pageCtrl_images').show();
    }

    if (tabId == '#tab_video') {
        $('.pageCtrl_video').show();
        if ($('#tab_video div#articleVideo').length > 0) {
            pnt.videoArticle_play();
        }
    }
    else {
        if (tabId != '#tab_video' && pnt.videoArticle_play.initialized == true) {
            $('#articleVideo').remove();
            $('#tab_video .tab_articleVideo').prepend('<div id="articleVideo"></div>');
        }
    }


}


/* ------------------------ Article image control ------------------------ */

pnt.articleImg_init = function() {
    $('.articleImage_ctrl a').click(function() {
        pnt.articleImg_nav(this);
        return false;
    });

    $('.articleImage:first-child').each(function() {
        pnt.articleImg_set(this);
    });

    $('.tab_articleImages').each(function() {
        var currentIndex = $('.articleImage', this).index($('.articleImage.mark', this));
        $('.articleImage_ctrl .current', this).html(currentIndex + 1);

        $('.articleImage_ctrl .total', this).html($('.articleImage', this).length);
    });
}

pnt.articleImg_set = function(me, index) {
    var scope = $(me).parents('.tab_articleImages').eq(0);
    var byline = $('img', me).attr('title');
    var nl = /\n/g;
    byline = byline.replace(nl, '<br />');

    $(me).siblings().removeClass('mark');
    $(me).addClass('mark');
    $('.articleImage_byline', $(me).parent()).html(byline);

    $('.articleImage_ctrl .current', scope).html(index + 1);

    // 2do - ta bort tidigare markering. Sätt rätt index i kontrollen
}

pnt.articleImg_nav = function(me) {
    var scope = $(me).parents('.tab_articleImages');
    var currentIndex = $('.articleImage', scope).index($('.articleImage.mark', scope));
    var direction = ($(me).hasClass('nav_prev')) ? 'prev' : 'next';
    var byline;
    var nl = /\n/g;

    /* Nedan - gör en extra if på varje... kolla currentIndex där */

    if (direction == 'prev') { // if backward...
        $('.articleImage.mark', scope).removeClass('mark');
        if (currentIndex == 0) { // current is the first item
            $('.articleImage', scope).eq($('.articleImage', scope).length - 1).addClass('mark');
            $('.articleImage_ctrl .current', scope).html($('.articleImage', scope).length);
        } else {
            $('.articleImage', scope).eq(currentIndex - 1).addClass('mark');
            $('.articleImage_ctrl .current', scope).html(currentIndex);
        }
        byline = $('.articleImage.mark img', scope).attr('title');
        byline = byline.replace(nl, '<br />');
        $('.articleImage_byline', scope).html(byline);
        $('.btn_downloadImage').attr('href', $('.articleImage.mark .origSrc').html());

    } else if (direction == 'next') { // if forward...
        $('.articleImage.mark', scope).removeClass('mark');
        if (currentIndex == ($('.articleImage', scope).length - 1)) { // if current is the last item
            $('.articleImage', scope).eq(0).addClass('mark');
            $('.articleImage_ctrl .current', scope).html(1);
        } else {
            $('.articleImage', scope).eq(currentIndex + 1).addClass('mark');
            $('.articleImage_ctrl .current', scope).html(currentIndex + 2);
        }
        byline = $('.articleImage.mark img', scope).attr('title');
        byline = byline.replace(nl, '<br />');
        $('.articleImage_byline', scope).html(byline);
        $('.btn_downloadImage').attr('href', $('.articleImage.mark .origSrc').html());

    }
}


/* ------------------------ Stack accordion control ------------------------ */

pnt.stackAcc_init = function() {
    $('.stack_header').each(function() {
        if ($(this).attr('href') == '#') {
            $(this).click(function() {
                if (!$(this).parent().hasClass('sys_stackItemMark')) {
                    pnt.stackAcc_nav(this);
                }
                return false;
            });
        }
    });
}

pnt.stackAcc_nav = function(me) {
    $('.sys_stackItemMark .stack_content', $(me).parent().parent()).hide('fast');
    $('.sys_stackItemMark', $(me).parent().parent()).removeClass('sys_stackItemMark');

    $(me).parent().addClass('sys_stackItemMark');
    $('.stack_content', $(me).parent()).show('normal');
}


/* ------------------------ Stack box paging control ------------------------ */

pnt.stackPaging_init = function() {
    $('.stack_nav a').click(function() {
        pnt.stackPaging_nav(this);
        return false;
    });
}

pnt.stackPaging_nav = function(me) {
    var scope = $(me).parents('.stack_content');
    var currentIndex = $('.stackPage', scope).index($('.stackPageMark', scope));
    var direction = ($(me).hasClass('nav_prev')) ? 'prev' : 'next';

    if ((direction == 'prev') && (currentIndex != 0)) { // if backward, and current is not the first item
        $('.stackPageMark', scope).removeClass('stackPageMark');
        $('.stack_nav span', scope).removeClass('mark');

        $('.stackPage', scope).eq(currentIndex - 1).addClass('stackPageMark');

        $('.stack_nav span', scope).eq(currentIndex - 1).addClass('mark');

    } else if ((direction == 'next') && (currentIndex != ($('.stackPage', scope).length - 1))) { // if forward, and current is not the last item
        $('.stackPageMark', scope).removeClass('stackPageMark');
        $('.stack_nav span', scope).removeClass('mark');

        $('.stackPage', scope).eq(currentIndex + 1).addClass('stackPageMark');

        $('.stack_nav span', scope).eq(currentIndex + 1).addClass('mark');
    }
}

/* ------------------------ Check height of comment entrys, add collapsability if needed ------------------------ */

pnt.comments_chkHeight = function() {
    var chkHeight = $('.comment_info:first').height();
    chkHeight = chkHeight * 5.5;

    $('.comment_item:not(.sys_readMoreComment)').each(function() {
        if ($(this).height() >= chkHeight) {
            $(this).addClass('sys_readMoreComment');

            var textTotal = $('.comment_text', this).text();
            var textStart = textTotal.substring(0, 320);
            textTotal = textTotal.replace(textStart, '');

            textStart = '<span class="comment_readMore">' + textStart + '<a href="#">...</a></span>';
            textTotal = '<span class="comment_totalText">' + textTotal + '</span>';
            textTotal = textStart + textTotal;
            $('.comment_text', this).html(textTotal);
            $('.comment_readMore a', this).click(function() {
                $(this).parents('.comment_item').toggleClass('sys_dudeImReadingHere');
                return false;
            });
        }
    });
}

/* ------------------------ Layer control ------------------------ */

pnt.layer_show = function(which_jQSel) {
    $(which_jQSel).each(function() {
        if (this.offsetHeight > $(window).height()) {
            var top = pnt.getScrollXY()[1];
        } else {
            var top = 50 + pnt.getScrollXY()[1];
        }

        $('#layershade').show();
        $(this).css('top', top + 'px');
        $(this).addClass('sys_layerActive').show('fast');
        $('#articleVideo').css('visibility', 'hidden');

        $('body').addClass('sys_layerMode');

        //location.hash = 'section_main';  // jump to top of iframe
    });
}

pnt.layer_close = function() {
    $('.sys_layerActive').hide('fast');
    $('#layershade').hide();
    $('#articleVideo').css('visibility', 'visible');

    $('body').removeClass('sys_layerMode');
}

/* ------------------------ Get scrolled distance ------------------------ */

pnt.getScrollXY = function() {
    var scrOfX = 0, scrOfY = 0;
    if (typeof (window.pageYOffset) == 'number') { //Netscape compliant
        scrOfY = window.pageYOffset;
        scrOfX = window.pageXOffset;
    } else if (document.body && (document.body.scrollLeft || document.body.scrollTop)) { //DOM compliant
        scrOfY = document.body.scrollTop;
        scrOfX = document.body.scrollLeft;
    } else if (document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollTop)) { //IE6 standards compliant mode
        scrOfY = document.documentElement.scrollTop;
        scrOfX = document.documentElement.scrollLeft;
    }
    return [scrOfX, scrOfY];
}


/* ------------------------ Home template initialization ------------------------ */

pnt.home_init = function() {
    $('.headline').eq(0).css('background-image', 'none');

    $('#header_search input[type=text]').keyup(function(e) {
        if (e.keyCode == 13) {
            $(this).siblings('.btn_searchHidden').click();
            return false;
        }
    });
}

/* ------------------------ Category tab switch ------------------------ */

pnt.catTabSwitch = function(me) {
    var myIndex = $('.catTabs a').index(me);
    $('.catContent.active', $(me).parents('.area').eq(0)).removeClass('active').slideUp('fast');
    $('.catContent', $(me).parents('.area').eq(0)).eq(myIndex).addClass('active').slideDown('fast');
}


/* ------------------------ persistant Input Values ------------------------ */

pnt.persistantInputValues = function() {
    $('.valLabel').each(function() {
        var prevInput = $(this).prev('input[type=text]');
        if (prevInput.val() == '') {
            prevInput.val($(this).text());
        } else {
        }
        prevInput.focus(function() {
            var valLabel = $(this).next('.valLabel');
            if ($(this).val() == valLabel.text()) {
                $(this).val('');
            }
        });
        prevInput.blur(function() {
            if ($(this).val() == '') {
                $(this).val($(this).next('.valLabel').text());
            }
        });
    });
}

/* ------------------------ Sneak-peek browsing, Company News ------------------------ */

pnt.sneakPeekBrowse_init = function() {
    $('.sneakPeekBrowse .headline_img').hide();
    $(".sneakPeekBrowse .stack_content:has('.headline_img') a").click(function() {
        if (!$(this).hasClass('mark')) {
            $('.stack_content a', $(this).parents('.sneakPeekBrowse').eq(0)).removeClass('mark');
            $(this).addClass('mark');
            $('.headline_img', $(this).parents('.sneakPeekBrowse').eq(0)).slideUp('fast');
            $('.headline_img', $(this).parent()).slideDown('fast', function() {
                pnt.whenISayJumpYouSayHowHigh('.stack_pad', $("#area_companyNews:not('.single')"));
                if ($.browser.msie && !pnt.ie6) {
                    $(this).css('height', this.offsetHeight + 'px');
                    setTimeout(function() {
                        $(this).css('height', 'auto');
                    }, 30);
                }
            });

            $('.sneakPeekBrowse .stack_content').removeClass('sneakActive');
            $(this).parent().addClass('sneakActive');
            return false;
        }
    });
    if ($(".sneakPeekBrowse .stack_content:has('.headline_img') a")[0] == $('.sneakPeekBrowse .stack_content a')[0]) {
        $('.sneakPeekBrowse .stack_content a').eq(0).click();
    }
}

/* ------------------------ whenISayJumpYouSayHowHigh ------------------------ */

pnt.whenISayJumpYouSayHowHigh = function(selector, scope) {
    var howHigh = 0;
    $(selector, scope).each(function() {
        this.style.height = 'auto';
        if (this.offsetHeight > howHigh) {
            howHigh = this.offsetHeight;
        }

    });
    $(selector, scope).each(function() {
        $(this).css('height', howHigh + 'px');
    });
}

/* ------------------------ image viewer init ------------------------ */

pnt.imageView_init = function() {
    $('.imageView_ctrl a').click(function() {
        if ($(this).hasClass('active') == false) {
            $(this).siblings().removeClass('active');
            $(this).addClass('active');

            $('.imageViewArea').hide();
            $($(this).attr('href')).show();

            if ($(this).next().length > 0) {
                $('.imageView_footer, .btn_downloadImages').show();
                $('.btn_downloadImage').hide();
            } else {
                $('.imageView_footer, .btn_downloadImages').hide();
                $('.btn_downloadImage').attr('href', $('.articleImage.mark .origSrc').html());
                $('.btn_downloadImage').show();
            }
        }
        return false;
    });
    $('.imageView_ctrl a').eq(0).click();

    $(window).load(function() {
        $('.iWThumb .title').each(function(i) {
            var imgTitle = $('#imageView_fullsize .articleImage img').eq(i).attr('title');
            if (imgTitle == '') {
                $(this).addClass('blank');
            } else {
                if (imgTitle.length > 100) {
                    imgTitle = imgTitle.substring(0, 100);
                    imgTitle = imgTitle + ' ...';
                }
                $(this).html(imgTitle);
            }
            $(this).click(function() {
                pnt.imageView_goToSlide(i);
            });
        });
    });

    if ($.browser.msie) {
        $('.iWThumb').hover(function() {
            $(this).addClass('hover');
        }, function() {
            $(this).removeClass('hover');
        });
    }

    $('.imageView_ctrl_checkAll').click(function() {
        $('.iWThumb input[type=checkbox]').attr('checked', 'checked');
        return false;
    });

    $('.imageView_ctrl_uncheckAll').click(function() {
        $('.iWThumb input[type=checkbox]').attr('checked', '');
        return false;
    });

    $('#tab_images .btn_downloadImages').click(function() {
        if ($('#imageView_thumbs input:checked').length == 0) {
            alert($(this).attr('title'));
            return false;
        }
    });
}

/* ------------------------ go to image in slideshow ------------------------ */

pnt.imageView_goToSlide = function(index) {
    $('.imageView_ctrl a').eq(1).click();
    pnt.articleImg_set($('.articleImage').eq(index), index);
    $('.btn_downloadImage').attr('href', $('.articleImage.mark .origSrc').html());
}


/* ------------------------ go to image in slideshow ------------------------ */

pnt.miniSlideShow_init = function() {
    if (($('#tab_article').length > 0) && ($('.iWThumb').length > 0)) {

        //$('#tab_article .rcb').eq(0).prepend('<div id="articleMiniSlideShow" class="loading"></div>');

        $('.iWThumb img').each(function() {
            $(this).clone().appendTo('#articleMiniSlideShow');
        });

        //$('#articleMiniSlideShow').append('<span class="imgRc_sw"></span><span class="imgRc_se"></span><span class="imgRc_nw"></span><span class="imgRc_ne"></span>');

        $('#articleMiniSlideShow img').each(function() {
            $(this).addClass('loading');
            $(this).load(function() {
                $(this).removeClass('loading');
                if ($(this).siblings().hasClass('loading') == false) {
                    $(this).parent().removeClass('loading');
                    $('#articleMiniSlideShow img').eq(0).show().addClass('showing');
                    pnt.miniSlideShow();

                    $('#articleMiniSlideShow').click(function() {
                        $('.section_tabs a').eq(1).click();
                    });
                }
            });
        });

    }
}

pnt.miniSlideShow = function() {
    pnt.miniSlideShow.nowRunning = setTimeout(function() {
        if ($('#articleMiniSlideShow .showing').next('img').length == 1) {
            $('#articleMiniSlideShow .showing').next().addClass('showing').fadeIn(2300, function() {
                $('#articleMiniSlideShow .showing').eq(0).hide().removeClass('showing');
                pnt.miniSlideShow();
            });

        } else {
            $('#articleMiniSlideShow img').eq(0).show().addClass('showing');
            $('#articleMiniSlideShow .showing').eq(1).removeClass('showing').fadeOut(2300, function() {
                pnt.miniSlideShow();
            });
        }
    }, 500);
}

/* ------------------------ link <select> ------------------------ */

pnt.autoLocationSelects_init = function() {
    $('.gotoLocation').change(function() {
        var goTo = $(this).val()
        if (goTo != '') {
            window.open(goTo, '_blank');
        }
    });
};


/* ------------------------ Video, homepage ------------------------ */

pnt.videoHome_init = function() {
    $('#video_links .stack_item').eq(0).css('background-image', 'none');
    $('#video_links .stack_item').click(function() {
        $('#video_links .stack_item').removeClass('active');
        $(this).addClass('active');
        pnt.videoHome_play(this);
    });
    $('#video_links a').not('.videoUrl')
      .each(function() {
          $(this).attr('rel', $(this).attr('href'));
          $(this).attr('href', 'javascript:void(0);');
      })
      .click(function() { // necessary for avoiding the default link behaviour.
          $(this).parent().click();
          return false;
      });
    $('#video_links .stack_item').eq(0).click();
}



pnt.videoHome_play = function(me) {
    $('#video_articleLink a').attr('href', $('a', me).attr('rel'));
    var homeFlvUrl = $('.videoUrl', me).attr('href');
    var playTxt = $('.videoIntro', me).text();
    var preview = $('.videoPreviewUrl', me).text();

    $('#video_summary .video_text').text(playTxt);

    playTxt = encodeURI(playTxt);
    var fv = {
        flvUrl: homeFlvUrl,
        //introText: playTxt,
        //thumbnailCaptureTime: '4',
        thumbnailUrl: preview,
        autoPlay: 'false'
    };
    var fp = {
        wmode: 'transparent',
        loop: 'false',
        quality: 'high',
        bgcolor: '#000000',
        allowScriptAccess: 'always',
        allowFullScreen: 'true'
    };
    var fa = {};

    swfobject.embedSWF(pnt.videoHome_play.SwfUrl, 'video_element', "336", "205", '9', false, fv, fp, fa);
}

//pnt.videoHome_play.SwfUrl = '../flash/video336.swf';
pnt.videoHome_play.SwfUrl = '../flash/VTCMediaPlayer.swf';

/* ------------------------ Video, article ------------------------ */

pnt.videoArticle_play = function() {
    var articleFlvUrl = $('#tab_video .videoUrl').attr('href');
    var fv = {
        flvUrl: articleFlvUrl
    };
    var fp = {
        wmode: 'transparent',
        loop: 'false',
        quality: 'high',
        bgcolor: '#EDEDED',
        allowScriptAccess: 'sameDomain',
        allowFullScreen: 'true'
    };
    var fa = {};

    swfobject.embedSWF(pnt.videoArticle_play.SwfUrl, 'articleVideo', "544", "332", '9', false, fv, fp, fa);
    pnt.videoArticle_play.initialized = true;
}

pnt.videoArticle_play.SwfUrl = '../flash/video544.swf';
pnt.videoArticle_play.initialized = false;

/* ------------------------ Style calendar ------------------------ */

pnt.cleanNetCalendar = function() {

    $('#eventCalendar table, #eventCalendar td').attr('style', '');
    $('#eventCalendar table').css('border', '0');
    $('#eventCalendar table table').css({
        backgroundImage: 'url(../Images/dots_beige1.gif)',
        backgroundRepeat: 'repeat-x',
        backgroundPosition: 'bottom'
    });

    $('#eventCalendar table table a').eq(0).html('').css({
        display: 'block',
        backgroundImage: 'url(../Images/evCal_prev.gif)',
        backgroundRepeat: 'no-repeat',
        backgroundPosition: 'center',
        width: '18px',
        height: '14px'
    });

    $('#eventCalendar table table a').eq(1).html('').css({
        display: 'block',
        backgroundImage: 'url(../Images/evCal_next.gif)',
        backgroundRepeat: 'no-repeat',
        backgroundPosition: 'center',
        width: '18px',
        height: '14px'
    });

    $('#eventCalendar table tr > td, #eventCalendar th').not('td.ev').css('padding', '1px');

}



/* ======================== On Page DOM ready ======================== */

$(document).ready(function() {
    
    /*if (document.referrer.indexOf(location.host) >= 0) {
        location.hash = 'section_main';
    }*/

    pnt.domLoading('load');
    $(window).load(function() {
        pnt.domLoading('pageload');
    });

    if ($('#tmpl_home').length > 0) {
        pnt.home_init();
    }

    // ------ inline-block fix for old Gecko browsers ------
    if (pnt.mozInlineBlock) {
        $('.section_tabs a, .btn_submit').css('display', '-moz-inline-box');
    }

    if ($('.section_tabs').length > 0) {
        $('.section_tabs a').click(function() { // article tabs
            pnt.tab_show(this);
            return false;
        });

        $('.section_tabs a').eq(0).click(); // activate first tab
    }


    pnt.articleImg_init();

    // ------ initialize layers ------
    $('#layershade').click(function() { pnt.layer_close(); });
    $('.layer_content').prepend('<a href="#" class="layer_close"></a>');
    $('.layer_close, .trig_formCancel').click(function() {
        pnt.layer_close();
        return false;
    });

    $('.trig_emailAlertBox').click(function() {
        pnt.layer_show('#layer_emailAlert');
        return false;
    });

    $('.btn_tellFriend').click(function() {
        pnt.layer_show('#layer_emailFriend');
        return false;
    });

    $('.btn_print').click(function() {
        //top.focus();
        window.print();
        return false;
    });

    $('#layer_emailAlert input[type=radio]').css('width', '15px');

    $('#pageMessage .close').click(function() {
        $(this).parent().slideUp();
        return false;
    });


    // ----- stacks handling ------
    //pnt.stackPaging_init();
    //pnt.stackAcc_init();

    $('.stack1').each(function() {  // activate first item per accordion, if it's not a link or trigs something else.
        if ($('.stack_header', this).eq(0).attr('href') == '#') {
            $('.stack_header', this).eq(0).click();
        }
    });


    $('.stackList .stack_links li a, #evCal_events a, #video_links .stack_item a').prepend('<span class="linkDec">&nbsp;&nbsp;</span>');


    $('.catTabs a').click(function() {
        $('a', $(this).parent()).removeClass('mark');
        $(this).addClass('mark');
        pnt.catTabSwitch(this);
        return false;
    });
    $('.catContent').hide();
    $('.catTabs a').eq(0).click();
    //$('.catContent .item:nth-child(4)').css('background', 'none');

    $(window).load(function() {
        pnt.sneakPeekBrowse_init();
    });

    pnt.persistantInputValues();

    pnt.imageView_init();

    pnt.miniSlideShow_init();

    if (pnt.ie6) {
        $('#eventCalendar td, .stack2 .stack_content, #video_links .stack_item, .stackList li').hover(function() {
            $(this).addClass('hover');
        }, function() {
            $(this).removeClass('hover');
        });
    }

    pnt.autoLocationSelects_init();

    pnt.videoHome_init();

    $('.btn_unsubscribe').click(function() {
        $('#subLayer_unsubscribe').show();
        $('#subLayer_subscribe').hide();
        return false;
    });

    $('.btn_subscribe').click(function() {
        $('#subLayer_unsubscribe').hide();
        $('#subLayer_subscribe').show();
        return false;
    });

    $('#search_params input[type=text]').keyup(function(e) {
        if (e.keyCode == 13) {
            $('.btn_searchHidden', $('#search_params')).click();
            return false;
        }
    });

    $("a.embed").click(function() { pnt.layer_show("#embedDialog"); return false; });

});
