// encoding: utf-8
/*@cc_on/*@if(@_jscript_version<5.7)try{document.execCommand('BackgroundImageCache',0,1)}catch(e){}/*@end@*/

Req(
  'eutils', // fontresize
  'fontsizer',
  'autovalidate',
  'equalizeheights',
  'roundcorners',
  'popups',
  'treecollapse',
  'easing-mini',
  'labelizor',
  'tabswitcher',
  'anchortags',
  'mailtoenabler',
  Req.joinUrl.split('?')[0]+'?utils_1.1.js;blockpopper_1.0.js;ragga_1.0.js;ragga_1.0-e2.js;pngfix_1.0.js|||utf-8',

  function(){
    var $ = jQuery,
        ver = parseInt($.browser.version, 10),
        msie = $.browser.msie  &&  ver < 9,
        msie6 = msie && ver<7,
        isIS = $('html').attr('lang') == 'is';

    $('body').addClass('js-active');


    $('#spurlsearch-simple').Req('tabswitcher', '/skin/basic/js/spurlsearch.js');


    $('body.milliforsida #raggaplay').remove();
    if (!window.EPLICA_loggedin) {
      RaggaEasy.init();
    }


    $('#qstr').labelizor();
    


    if (!window.EPLICA_loggedin)
    {

      blockPopper.linkSelector = 'a.help';
      blockPopper.init();


      $('.netfang').mailtoEnabler();


      $('div.article').run(function(){
        
          if (!msie6)
          {
            this
                .find('.highlight, .highlight-smu, .highlight-arrows')
                    .addClass('roundbox-active')
                    .roundCorners({ out:1, prefix:'highlight-c_ highlight-c_' })
                .end()
                .find('.related')
                    .addClass('roundbox-active')
                    .roundCorners({ out:1, prefix:'related-c_ related-c_' })
                .end()
                .find('.highlight-blue')
                    .addClass('roundbox-active')
                    .roundCorners({ out:1, prefix:'highlight-blue-c_ highlight-blue-c_' })
                .end()
                .find('.highlight-green')
                    .addClass('roundbox-active')
                    .roundCorners({ out:1, prefix:'highlight-green-c_ highlight-green-c_' })
                .end();
          }

          this
            .find('div.chapters') // Cuz of floating buggery - swap placement of .chapters and .summary elements inside `.article`s
                .each(function(){
                    $(this).prevAll('p.meta, div.summary').eq(0).before( this );
                  });
        });



      $('div.pagestyle').fontsizer();

      $('a.popup').popUps({ target: '_blank' });
      



      $('body.home').each(function(){

          $('.endurreisnnav').find('li a').append('<span class="t" /><span class="b" />');


          $('div.dirlist, div.headlines')
              .equalizeHeights();

          $('.mininews')
              .slice(0,2)
                  .log()
                  .equalizeHeights()
              .end()
              .slice(2,2)
                  .equalizeHeights()
              .end();


          /* *** front page article rotator *** */
          var rotator = $('div.rotator div.boxbody', this),
              newsitems = rotator.find('> div.item'),
              numNews = newsitems.length,
              lastIdx = 0,
              visIdx = 0,
              stopText = isIS ? 'Stöðva' : 'Stop',
              startText = isIS ? 'Ræsa' : 'Start',

              pagingElm = $('<div class="paging"><ul>' +
                              '<li class="jump"></li>' +
                              '<li class="stop"><a href="url">'+ stopText +'</a></li>' +
                              '</ul></div>')
                              .appendTo(rotator),

              jumperElm = pagingElm.find('li.jump');

          $('p.moreolder', rotator).after( $('a.rss-link') );

          newsitems
              .each(function(i){
                  jumperElm
                      .append('<a href="#"'+ (!i?' class="current"':'') +'>' +  (i+1) + '</a>')
                  i && $(this).hide();
                });

          var jumpLinks = jumperElm.find('a'),
              marqueeTimer,

              runMarquee = function () {
                  visIdx++;
                  if (visIdx >= numNews) { visIdx = 0; }
                  jumpLinks.eq(visIdx).trigger('click'); // start the next transition;
                };

          jumpLinks.each(function(i){

              $(this)
                  .bind('click', function () {
                      newsitems.eq(lastIdx).fadeOut(300, 'easeOut');
                      jumpLinks.eq(lastIdx).removeClass('current');

                      newsitems.eq(i).pause(300).fadeIn(300, 'easeIn');
                      $(this).addClass('current');

                      lastIdx = i;
                      return false;
                    });

            });

          var isPaused = false;
          var startDelay = 4000;

          rotator
              // pause interval when we mouse over the container
              .bind('mouseenter', function(e){
                  clearInterval(marqueeTimer);
                })
              // start interval when we mouse out of the container
              .bind('mouseleave', function(e){
                  if (!isPaused) {
                    marqueeTimer = setInterval(runMarquee, 10000);
                  }
                })
              // kick-start the marquee;
              .trigger('mouseleave');

          pagingElm.find('li.stop a')
              .bind('click', function (e) {
                  $(this)
                      .toggleClass('current')
                      .text(isPaused ? stopText : startText);
                  isPaused = !isPaused;
                  return false;
                });

        });
        
        
      $('ul.tabs').tabSwitcher();

        
      var newWindowText = isIS ? 'Opnast í nýjum vafraglugga' : 'Opens in new window',
          fileText =  isIS ? 'skjal' : 'file';

      // Mark external links as such
      $('body:not(.home)').find('.pgmain a')
          .filter(function() { return $(this).attr('href') != undefined })
              .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() +' '+ fileText;
                      }
                      else if ( $(this).is('.external') )
                      {
                        text = newWindowText;
                        useappend = true;
                      }
                      if (text)
                      {
                        link
                            .attr('target', '_blank')
                            .attr('title', (link.attr('title')||link.text()) +' ('+ text+')')
                            .not(':has(img)')
                                .append(' <span class="icon">('+ text +')</span>');
                      }
                    });


      // Faux title tag sem alt
      $('img').each(function() {
          if (!$(this).attr('title') && $(this).attr('alt'))
          {
            $(this).attr('title', $(this).attr('alt'));
          }
        });


      var subcatText = isIS ? 'Sjá undirflokka' : 'View subcatigories';
      $('.sitemap ul.level2 li:has(ul.level3)')
          .each(function() {
              $('ul.level3', this).hide();
              $(this).find('> a').after('<a title="' + subcatText + '" class="ultoggle" href="#">+</a>');
              $(this).find('a.ultoggle')
                  .bind('click', function() {
                      $(this).parent().find('ul.level3').toggle();
                      ($(this).text() == '+') ? $(this).html('-') : $(this).html('+')
                      return false;
                    })
            });
      
      
    
      // qa
      $('div.qa div.boxbody')
          .find('h4')
          .wrapInner('<a href="#"></a>')
          .map(function(){
              var h = $( this );
              return [
                h.add([
                  h.nextAll('p')[0], 
                  h.nextAll('ul')[0]
                ])
              ];
            })
          .wrap( '<div class="group"></div>' );



      

    } // end not logged in
    
    
    $('div.group')
        .find('h4:not(:has(a))')
            .wrapInner('<a href="#" />')
        .end()
        .treeCollapse({
            rootClass:    'collapse-active',
            openClass:    'collapse-open',
            closedClass:  'collapse-closed',
            toggler:      'h4 > a',
            branch:       null  // use self as branch
          });

    $('div.glossarylist div.item')
        .find('h3:not(:has(a))')
            .wrapInner('<a href="#" />')
        .end()
        .treeCollapse({
            rootClass:    'faq-active',
            openClass:    'faq-open',
            closedClass:  'faq-closed',
            toggler:      'h3 > a',
            branch:       null  // use self as branch
          });
    

    $('#noflickerCSS').remove();



    // Add "send to facebook" link to articles
    var fbText = isIS ? 'Senda á Facebook' : 'Send to Facebook',
        toTopText = isIS ? 'Efst á síðu' : 'Top of page';
    $('p.buttons')
        /*.append(
            $('<a href="#" class="btnreply">Skrifa athugasemd</a>')
          )*/
        .append(
            $('<a class="btnfacebook"><span>'+ fbText +'</span></a>')
                .attr(
                    'href',
                    'http://www.facebook.com/sharer.php?u='+encodeURIComponent(document.location.href)+'&t='+encodeURIComponent($('h1').text()+' | '+$('img.logo:first').attr('alt') )
                  )
          )
        .append(
              '<a class="btntop" href="#pghead">'+ toTopText +'</a>'
            );



    if (!window.EPLICA_loggedin)
    {

      // Sérvirkni fyrir flokkinn Endurreisn í þágu þjóðar
      $('.attentionbox-about, .attentionbox-info').find('.boxbody').equalizeHeights();
      $('.navbox')
          .find('.boxbody')
              .equalizeHeights()
          .end()
          .equalizeHeights();



      // TEMP: js fix for dirnav summaries (remove when fixed in JSP)
      $('div.dirnav td')
        .each(function(){
        
            var lastp = $(this).find('p:last'),
                link = $(this).find('h3 a').attr('href'),
                title = $(this).find('h3 a').text(),
                moreText = isIS ? 'Nánar' : 'More';

            lastp.after('<span class="more"><a title="'+ title +'" href="'+ link +'">'+ moreText +'</a></span>')
          });


      // qa groups
      $('div.qa div.group:odd').addClass('group-odd');


      // "fanstu það sem þú leitaðir að" collapsing virkni í formi í leit
      $('.foundit ').Req('/skin/basic/js/foundIt.js');


      $('form').autoValidate();
    }


  }
);


