// encoding: utf-8
/*@cc_on/*@if(@_jscript_version<5.7)try{document.execCommand('BackgroundImageCache',0,1)}catch(e){}/*@end@*/

// ***** jqreq *****
Req.localPath = Req.localPath || '/skin/basic/'
Req(
  'eutils',
  'equalizeheights',
  'fontsizer',
  'autovalidate',
  'labelizor',
  'listscroller',
  'imgpop',
  'anchortags',
  'x/bookmark',
  'x/ui-accordion 1.7',

  function(){
    var $ = jQuery,
          ver = parseInt($.browser.version, 10),
          msie = $.browser.msie && ver < 9,
          ie6 = msie && ver < 7,
          isIS = $('html').attr('lang') == 'is',
          body = $('body'),
          article = body.find('.article');

    body.addClass('js-active');

    if ( msie ) { body.addClass('msie') }

    // labelize search input
    $('#qstr').labelizor();

    // mnav decoration
    var mnavLine = $('<div class="mnav-line" />'),
        mnav = $('.mnav .boxbody').append(mnavLine),
        mnavCurrent = mnav.find('.parent, .current');
    
    function mnavLineAni(hoverElm) {

      if(hoverElm) {
        var newWidth = hoverElm.width() + 'px',
            newLeftPos = hoverElm.find('a').position().left + 'px';
      } else {
        var newWidth = 0,
            newLeftPos = 0;
      }

      mnavLine
          .stop()
          .animate({
              'width': newWidth,
              'left': newLeftPos
          });
    }
    
    if ( mnavCurrent[0] )
    {
      mnavLine
          .appendTo(mnav)
          .css({
            'width': mnavCurrent.find('a').width(),
            'left':  mnavCurrent.find('a').position().left
            });
    }
        
    mnav.find('li')
        .hover(function () {
            mnavLineAni($(this));
          },
          function () {
            if(mnavCurrent.length) {
              mnavLineAni(mnavCurrent); // back to current
            } else {
              mnavLineAni(false); // if no current to begin with
            }
          });


    if (!window.EPLICA_loggedin)
    {
      //equalize heights
      $('body.twocol .mwrap > div').equalizeHeights();

      //find the height of the summary
      article.find('.imgbox').css('margin-top', article.find('.summary').height() + 21 );

      //zebra tables
      $('tbody tr:nth-child(2n-1)').addClass('odd');

      // frontpage image carousel
      $('body.home .carousel .boxbody')
            .listscroller({
                item :       '.item',
                windowSize:  1,
                stepSize:    1,
                startPos: 'random',
                animation: 'crossfade',
                autoScrollDelay: 4000
            });
            
            
      //tag external urls
      var link, text, useappend, match;
      $('a')
          .anchorTags({
              usePatterns:  ['doc', 'pdf', 'xls']
            })
          .filter('.external, .file_pdf, .file_doc, .file_xls')
              .each(function() {
                  link = $(this);
                  text = '';
                  useappend = false;
                  match = this.className.match(/(^| )file_([a-z]+)( |$)/);
                  if ( match )
                  {
                    text = match[2].toUpperCase() +' Skjal';
                  }
                  else if ( $(this).is('.external') )
                  {
                    text = 'Opnast í nýjum vafraglugga';
                    useappend = true;
                  }
                  if (text)
                  {
                    link
                        .attr('target', '_blank')
                        .attr('title', (link.attr('title')||link.text()) +' ('+ text+')')
                        .not(':has(img)')
                            [useappend ? 'append' : 'prepend'](' <span class="icon">('+ text +')</span>');
                  }
                });


      //accordion gaur
      $('.accordion').accordion({
            header: 'h3',
            icons: { 'header': 'ui-icon-closed-triangle', 'headerSelected': 'ui-icon-open-triangle' }
          });
            
      //share / bookmark
      !ie6 && $('.buttons').each(function(){
          var btnbar = $(this),
              bookmarksOpen,
              shareText = isIS ? 'Segja frá' : 'Tell a friend',
              emailTextText = isIS ? 'Senda í­ pósti' : 'Send as e-mail',
              emailSubjectText = isIS ? ' ' : 'Interesting article',
              emailBodyText = isIS ? '\n{u}' : 'I thought you might find this page interesting:\n\n{t}\n{u}',
              shareHover = false,
              shareBtn = $('<span class="share"><a href="#">'+ shareText +'</a></span>'),
              bookmarks = $('<div class="share-menu" />').bookmark({
                                                      title:   $('h1:first').text(),
                                                      addEmail: true,
                                                      emailText: emailTextText,
                                                      emailSubject: emailSubjectText,
                                                      emailBody: emailBodyText,
                                                      sites:   ['facebook', 'twitter', 'google', 'yahoobm', 'stumbleupon', 'digg', 'reddit', 'delicious', 'spurl'],
                                                      compact: false, // defaults to `true`
                                                      icons:   '/skin/basic/design/i/icons.png'
                                                    }).hide();

            shareBtn
                .prependTo( btnbar )
                .append(bookmarks)
                .find('> a')
                    .bind('click', function (e) {
                        bookmarksOpen ?
                            bookmarks.slideUp(200):
                            bookmarks.slideDown(300);
                        bookmarksOpen = !bookmarksOpen;
                        shareBtn.toggleClass('share-open', bookmarksOpen);
                        return false;
                      })
                .end()
                .bind('mouseleave focusout', function(e){
                    shareHover = false;
                    setTimeout(function(){
                        if(!shareHover) {
                          bookmarks.slideUp(200);
                          bookmarksOpen = false;
                          shareBtn.removeClass('share-open');
                        }
                      }, 1000);
                  })
                .bind('mouseenter focusin', function(e){
                    shareHover = true;
                  });

          });//end btnbar


      //popup in articles
      article.find('.imagebox a.img')
          .each(function() {
            var imgsrc = $(this).find('img').attr('src').replace(/\/[^\/]+\/([^\/]+)$/, '/large/$1');
            $(this).attr('href', imgsrc)
          })
          .imgPopper({
              curtainColor : '#ffffff',
              curtainOpacity : '0.75',
              yOffset: 15
            });

    }

    //sitemap collapser
    $('.sitemap').Req('treecollapse', function() { 
        $(this).treeCollapse({ 
            branch: 'li:has(ul)', 
            doTogglers: 1, 
            toggler: '> a.expand',
            startOpen: 'ul.level1 > li:has(ul)'
          }); 
        });

    //remove flicker trick
    $('#noflickerCSS').remove();
    $('.pagestyle').fontsizer();
    $('form').autoValidate();
  }
);
// **** /jqreq *****

