// 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',
  'x/cookie',
  'fontsizer',
  'autovalidate',
  'equalizeheights',
  'tabswitcher',
  'labelizor',
  'imgpop',
  'anchortags',
  'mailtoenabler',
  'listscroller',
  'x/easing',
  'x/ui-accordion 1.7',
  'http://codecentre.eplica.is/jquery/quickies/quicky-alistdatesplit-min.js',

  function(){
    var $ = jQuery;
        ie6 = $.browser.msie && parseInt($.browser.version) < 7,
        bGrade = $.browser.msie && $.browser.version < 8,
        isIS = $('html').attr('lang') == 'is',
        userstyles = $('body').is('.userstyles-on');
    
    $('body:not(.home)').find('.pgmain, .pgextra1, .pgextra2').equalizeHeights();

    // equal height columns
    var lnavs = $('body:not(.home) div.lnav');
    for (var i=0, l=lnavs.length; i<l; i+=3)
    {
      lnavs.slice(i,i+3).equalizeHeights();
    }


    // labelize search input
    $('#qstr').labelizor();

    if (userstyles) { $('.pgtop').remove(); }

    //frontpage scripts
    !userstyles && $('body.home').each(function(){
        var home = $(this);
          
        $('.tabbox', home).wrapAll('<div class="tabgroup box-3_4 box" />').removeClass('box-3_4 box').makeTabbox().tabSwitcher();
        
        $('.accnav', home)
            .find('.boxhead').wrapInner('<a href="#"/>').end()
            .wrapAll('<div class="accbox box-1_4 box" />').removeClass('box-1_4 box')
                .parent()
                    .accordion({ 
                        header: '.boxhead'
                      })
                    //stupid jquery ui bug making headers not keyboard navigateable with tabindex: -1
                    .bind('accordionchange', function(event, ui) {
                        ui.oldHeader.attr('tabindex', '');
                      })
                    .find('.boxhead')
                        .attr('tabindex', '');
                      
                      
        home.find('.accbox, .mainarticle, .qnav').equalizeHeights();
        home.find('.tabgroup, .sjukra').equalizeHeights().filter('.tabgroup').before('<div class="clear">&nbsp;</div>');
        

        //frontpage banners
        !ie6 && $('.focuslist .boxbody', home)
            .each(function(){
                var box = $(this),
                    itms = $('> .item', this),
                    openTimeout,
                    closeTimeout,
                    openBox,
                    tabTempl = $('<div class="index" id="index"><ul></ul></div><div class="clear">&nbsp;</div>');

                itms.each(function(i){
                    var heading = $('h3', this).text() || '';
                    $(this).attr('id', 'slide-'+i);
                    $('<li class="idx'+i+'"><a href="#slide-'+ i +'"><strong>' + heading + '</strong></a></li>').appendTo( $('ul', tabTempl) );
                  });
              
                itms
                    .prepend('<a class="focustarget" href="#">.</a>')
                    .append('<a class="closebtn" href="#" title="Fela spjald">Fela</a>');
              

                tabTempl.appendTo( box );

                box
                    .bind('mouseleave', function (e) {
                        if (openBox)
                        {
                          clearTimeout(closeTimeout);
                          closeTimeout = setTimeout(function(){
                              tabTempl.removeClass('active').find('a:first').trigger('fade');
                            }, 800);
                        }
                      })
                    .bind('mouseenter', function (e) {
                        openBox && clearTimeout(closeTimeout);
                      })
                    .find('.index a')
                        .bind('mouseenter', function (e) {
                            var link = this;
                            clearTimeout(openTimeout);
                            openTimeout = setTimeout(function(){
                                $(link).trigger('fade');
                              }, 200);
                          })
                        .bind('mouseleave', function (e) {
                            clearTimeout(openTimeout);
                          })
                        .bind('fade', function (e) {
                            var linkElm = this,
                                id = linkElm.href.split('#')[1],
                                itmBox = $( id ? '#'+id : [] );

                            if ( itmBox[0] )
                            {

                              itmBox.find('a.closebtn')
                                  .bind('click', function (e) {
                                      itmBox.hide();
                                      $(linkElm).removeClass('current').focus();
                                      openBox = $('#slide-0');
                                      return false;
                                    });

                              if ( !openBox  ||  openBox[0] != itmBox[0] )
                              {
                                openBox && openBox.find('a.closebtn').trigger('click', [true]);

                                $(linkElm).addClass('current');
                                tabTempl.addClass('active');

                                itmBox.show().find('a.focustarget').focus();

                                openBox = itmBox;
                              }
                            }
                            return false;
                          })
                        .bind('click', function (e) {
                            var href = $(this).attr('href').split('#')[1]; //stupid IE6-7 bug
                            window.location = $( '#' + href ).find('h3 a').attr('href');
                            e.preventDefault();
                          });

                tabTempl.find('a:first').trigger('fade');
                tabTempl.removeClass('active')
              }); // end banner

      }); // end home


    if (!window.EPLICA_loggedin && !userstyles)
    {

      $('.newslist').alistDateSplit();


      $('.article').each(function(){
          var article = $(this);

          $('.meta', article).appendTo('h1');

          $('.naestaskref, .tengtefni', article)
              .each(function(){
                  var heading = $(this).is('.tengtefni') ? 'Tengt efni' : 'Næstu skref',
                      cName = this.className;
                  $(this)
                      .prependTo('.pgextra1 .wrap')
                      .wrap('<div class="'+ cName +' box" />')
                      .before('<h2 class="boxhead">'+ heading +'</h2>')
                      .wrap('<div class="boxbody" />')
                      .find('em')
                          .remove();
                });


          // Add "send to facebook" link to articles
          $('.buttons', article)
              .append(
                  $('<a class="btnfacebook" href="#">Senda á facebook</a>')
                      .bind('click', function()  {
                          window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(document.location.href)+'&t='+encodeURIComponent($('h1').text()),'sharer','toolbar=0,status=0,width=626,height=436');
                          return false;
                        })
                );


          //popup in articles
          $('.imagebox a.img', article)
              .each(function() {
                var imgsrc = $(this).find('img').attr('src').replace(/\/[^\/]+\/([^\/]+)$/, '/large/$1');
                $(this).attr('href', imgsrc)
              })
              .imgPopper({
                  curtainColor : '#ffffff',
                  curtainOpacity : '0.75',
                  yOffset: 15
                });


          $('table.filtered', article).Req('filtertable', function() { $(this).filterTable() });

        });



      //maplist madness (/tryggingastofnun/afgreidsla/umbodsskrifstofur/)
      $('.maplist').run(function() {
          var maplist = $('> .boxbody', this);

          $('> h2', maplist).each(function(){
              var h2 = $(this);
              h2.add( h2.nextUntil('h2, p.buttons') ).wrapAll('<div id="'+ h2.attr('id') +'" class="tabpane" />');
              h2.removeAttr('id');
            });

          $('> .tabpane', maplist).each(function(){
              $(this)
                  .find('> h4')
                      .wrapInner('<a href="#" />')
                      .each(function(){
                          $(this).nextUntil('h4').wrapAll('<div class="accpane" />');
                        })

              $(this).find('> .accpane, > h4').wrapAll('<div class="accbox" />');

              $('.accbox', this)
                    .accordion({ 
                        header: 'h4',
                        active: false,
                        alwaysOpen: false, 
                        autoHeight: false
                      })
                    //stupid jquery ui bug making headers not keyboard navigateable with tabindex: -1
                    .bind('accordionchange', function(event, ui) {
                        ui.oldHeader.attr('tabindex', '');
                      })
                    .find('h4')
                        .attr('tabindex', '');
            });

          $('> .chapters', maplist)
              .wrapInner('<div class="chapwrap" />')
              .find('ul')
                  .tabSwitcher({ showFirst: false })
                  .find('a')
                      .each(function(){
                          var href = $(this).attr('href').replace(/#/, '');
                          $(this).parent().addClass(href);
                        })
                      .append('<span class="part" />')
                      .append('<span class="hoverfix" /><span class="hoverfix2" />');
        });

      //zebra tables
      $('tbody tr:nth-child(2n-1)').addClass('odd');


      //tag external urls
      pendFunc = $('body').is('.home') ? 'prepend' : 'append';
      $('a')
          .anchorTags({
              usePatterns:  ['doc', 'pdf', 'xls']
            })
          .filter('a.external, a.file_pdf, a.file_doc, a.file_xls')
            .filter(function() { return !$('img', this).length })
              .each(function() {
                  var match = $(this)[0].className.match(/(^| )file_([a-z]+)( |$)/);
                  if ( match ) 
                  {
                    if ( $('span', this).length === 0 ) {
                      var text = match[2];
                      $(this).attr('title', text+' skjal')[pendFunc](' <span class="icon">('+ text +')</span>');
                    }
                  }
                  else if ( $(this).is('.external') )
                  {
                    var externalText = isIS ? 'Opnast í nýjum vafraglugga' : 'Open in new window';
                    $(this).attr('target','_blank').attr('title', externalText)[pendFunc](' <span class="icon">('+ externalText +')</span>');
                  }
                });


      //Ajax - For lists ( 1 at a time ) - spurt of svarað
      var ajaxItems = $('.ajaxlist .item'),
          openItem;

      ajaxItems.each(function(idx){
          var popper = $('a', this),
              popLoaded = false,
              thisSummary = $('.summary', this);

          thisSummary.hide();

          popper.bind('click', function (e) {

              ajaxItems.eq(openItem).find('h3').removeClass('active').end().find('.summary').hide();

              if ( openItem !== idx ) {
                if (!popLoaded) {
                  $.get(
                          popper.attr('href'),
                          { justPicPos: 'pgmain' },
                          function(data){
                              var articleText = $(data).find('.box .boxbody');
                              articleText.find('h1, .subtitle, .summary, .meta, .imagebox').remove();
                              thisSummary.html(articleText);
                            }
                        );
                  popLoaded = true;
                }
                thisSummary.show();
                popper.parent().addClass('active');
                openItem = idx;
              } else { 
                openItem = null;
              }

              return false;
            });
        });

      //file filter
      $('div.catfiles').Req(Req.localPath + 'js/filterfiles-min.js');


      // pngfix for IE6
      if (ie6) {
        $('img[src$=".png"]').Req('x/ifixpng', function(){
            $(this).ifixpng();
          });
        $('body').addClass('slap'); // render kick
      }

    } // end loggedin

    //sitemap splitter
    $('div.sitemap .boxbody').Req('treecollapse', function() {

        $(this).treeCollapse({ 
            branch: 'li:has(ul)', 
            doTogglers: 1, 
            toggler: '> a.expand',
            startOpen: 'ul.level1 > li:has(ul)'
          });

        var smScnd = $('<ul class="level1 scnd" />'),
            smLis = $('ul.level1 > li', this);
        smLis.each(function(i) {
            if ( i > (smLis.length/2) ) {
              $(this).appendTo(smScnd);
            }
          })
        smScnd.appendTo(this);
        $('ul.level1', this).wrap('<div class="smwrap" />');

      });



    $('.pagestyle').fontsizer({
          minSize      : 0,
          maxSize      : 4,
          defaultSize  : 1
        });
    $('form').autoValidate();
    $('#noflickerCSS').remove();
    $('.netfang').mailtoEnabler();

    //recalculate heights
    setTimeout(function() {
      $(window).trigger('resize.eqh');
    }, 500);

    //táknmáls popups
    $('.videolink a')
        .attr('title', 'Smelltu hér til að fá lýsingu á táknmáli')
        .bind('click', function (e) {

            var popupLink = this;
            var popWrapper = $(
                    '<div class="popup-curtain"></div>' +
                    '<div class="popup-wrapper">' +
                      '<div class="popup-inner-wrapper">' +
                      '<div id="popupvideocontainer" class="videocontainer">' +
                        '<div class="video">' +
                          '<div class="videoname"></div>' +
                        '</div>' +
                        '<div class="act">' +
                          '<a class="close">' +
                            '<strong>Loka glugga</strong>' +
                          '</a>' +
                        '</div>' +
                      '</div>' +
                      '</div>' +
                    '</div>'
                  );
            var videoPlayer = $(
                    '<object width="530" height="390" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0">' +
                      '<param name="movie" value="/bitar/common/media/mediaplayer.swf?file=' + popupLink.href + '&autostart=true&bufferlength=5" /><param name="wmode" value="transparent" /><param name="allowfullscreen" value="true" />' +
                      '<embed src="/bitar/common/media/mediaplayer.swf?file=' + popupLink.href + '&autostart=true&bufferlength=5" width="530" height="390" allowfullscreen="true" wmode="transparent" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />' +
                    '</object>'
                  );

            popWrapper
                .filter('.popup-curtain').css({ opacity: .7 }).end()
                .hide()
                .appendTo('body')
                .fadeIn(350, function () {
                    videoPlayer.prependTo('#popupvideocontainer');
                  })
                .bind('click', function(e){
                    videoPlayer.remove();
                    popWrapper
                        .fadeOut(250, function(){ $(this).remove(); });
                  })
                .find('.videoname')
                    .html( $('div.pagebody h2.boxhd:first').html() )
                .end()
                .find('a.close')
                    .bind('click', function(e){ popWrapper.trigger('click'); return false; })
                .end()
                // Contain clicks so they don't bubble up to the curtain element
                .find('> *')
                    .bind('click', function(e){  e.stopPropagation(); return false; });

            return false;
          });

  }
);
// **** /jqreq *****
