// 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(
  //'http://codecentre.eplica.is/concat/?utils_1.1.js;ragga_1.0-source.js;ragga_1.0-e2.js|||utf-8',
  'eutils',
  'x/cookie',
  'fontsizer',
  'autovalidate',
  'equalizeheights',
  'tabswitcher',
  'labelizor',
  'imgpop',
  'anchortags',
  'mailtoenabler',
  'listscroller',
  'x/bookmark',
  'x/ui-accordion 1.7',

  function(){
    var $ = jQuery,
        ie6 = $.browser.msie && parseInt($.browser.version) < 7,
        isIS = $('html').attr('lang') == 'is',
        pgmain = $('.pgmain');

    $('#qstr').labelizor();
    
    $('#noflickerCSS').remove();

    //rightcol position fix for pages with multiple line title
    $('body.threecol .pgextra1').css({ 'margin-top' : $('h1').outerHeight() + 10 });

    //contactform category hack
    $('#formTag').run(function() {
        $(this)
            .bind('change', function (e) {
                $('#flokkur').val( $('#formTag').find('option:selected').text() );
              })
            .trigger('change');
      });

    if (!window.EPLICA_loggedin)
    {
      $('body').addClass('js-active');
      pgmain.find('tbody tr:nth-child(2n-1)').addClass('odd');
      $('body.milli div.sbox').equalizeHeights();

      $('body.home').run(function() {
          var home = $(this);

          //topscroller
          home.find('.slidebox > .boxbody:has(.item)')
              .find('.item')
                  .prepend('<a class="focustarget" href="#">.</a>')
              .end()
              .listscroller({
                  item: '.item',
                  paging: true,
                  windowSize: 1,
                  stepSize: 1,
                  autoScrollDelay: 5000,
                  animation: 'crossfade',
                  jumpLabel: 'Fletta í grein númer: ',
                  titleNext: 'Fletta í næstu frétt',
                  labelNext: 'Næsta frétt',
                  titlePrev: 'Fletta í fyrri frétt',
                  labelPrev: 'Fyrri frétt',
                  statusLabel: 'Frétt: '
                });

          //accordion widget
          home.find('.accnav')
              .find('h2.boxhead')
                  .wrapInner('<a href="#"/>')
              .end()
              .wrapAll('<div class="accbox box" />')
              .parent()
                  .accordion({ 
                      header: 'h2.boxhead'
                    })
                  //stupid jquery ui bug making headers not keyboard navigateable with tabindex: -1
                  .bind('accordionchange', function(event, ui) {
                      ui.oldHeader.attr('tabindex', '');
                    })
                  .find('h2.boxhead')
                      .attr('tabindex', '');

          //rss link inject
          home.find('.news .moreolder').each(function() {
              var moHref = $(this).find('a').attr('href')
              $(this).append('<a class="rss" href="'+ moHref +'/rss.xml">Áskrift að fréttum</a>')
            });

          //quicknav popper
          home.find('.quicknav .item').each(function(){
              $(this)
                  .find('.summary')
                      .wrapInner('<div class="summinner" />')
                  .end()
                  .bind('mouseenter focusin', function (e) {
                      $(this).addClass('active');
                    })
                  .bind('mouseleave focusout', function (e) {
                      $(this).removeClass('active');
                    })
            });

        }); // Home ends


      //hover effect for sbox headings
      $('.sbox > .boxhead:has(a), .sboxnav')
          .bind('mouseenter focusin', function (e) {
              $(this).addClass('hover');
            })
          .bind('mouseleave focusout', function (e) {
              $(this).removeClass('hover');
            });


      //tag external urls
      pgmain.find('.article a, .articlelist a, .catfiles a').add('.snav a')
          .anchorTags({
              usePatterns:  ['doc', 'pdf', 'xls']
            })
          .filter('.external, .file_pdf, .file_doc, .file_xls')
              .not(':has(img)')
                  .each(function() {
                      var link = $(this),
                          text = '',
                          match = this.className.match(/(^| )file_([a-z]+)( |$)/);
                      if ( match )
                      {
                        if  ( !link.find('span').length ) 
                        {
                          text = match[2].toUpperCase() +' '+ (isIS?'skjal':'file');
                        }
                      }
                      else if ( $(this).is('.external') )
                      {
                        text = isIS ? 'Opnast í nýjum vafraglugga' : 'Open in new window';
                      }
                      if (text)
                      {
                        link
                            .attr('title', (link.attr('title')||link.text()) +' ('+ text+')')
                            .append(' <span class="icon">('+ text +')</span>');
                      }
                    });


      pgmain.find('.article .boxbody').run(function() {

          //share / bookmark
          var article = $(this),
              bookmarksOpen,
              shareText = isIS ? 'Deila / Bókmerkja' : 'Share / Bookmark',
              emailTextText = isIS ? 'Senda í pósti' : 'Send as e-mail',
              emailSubjectText = isIS ? 'Áhugaverð grein á vef Sjúkratrygginga Íslands' : 'Interesting article on Icelandic social insurance website',
              emailBodyText = isIS ? 'Hugsa að þú hefðir áhuga á þessu:\n\n{t}\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'
                                                    });

          shareBtn.prependTo('.buttons', article);
          bookmarks.hide().appendTo(shareBtn);

          shareBtn
              .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;
                });


          /* insert raggaplay into articles -- 
          var narratetext = isIS ? 'Lesa texta' : 'Narrate text';
          article.prepend('<p class="stream">Vefþulan er vefþjónusta ætluð þeim sem einhverra hluta vegna eiga erfitt með að lesa texta af skjá</p>'+
                          '<div id="raggaplay"><a href="#">'+ narratetext +'</a></div>');
          if (window.RaggaEasy) {
            RaggaEasy.init();
          }
          */

          article.find('.naestaskref, .tengtefni')
              .each(function(){
                  var list = $(this),
                      heading = list.prev('h2, h3, h4').remove().text()  ||  (list.is('.tengtefni') ? 'Tengt efni:' : 'Næstu skref:');
                  $('<div class="sbox box"><div class="boxbody" /></div>')
                      .prepend( '<h2 class="boxhead">'+ heading +'</h2>' )
                      .find('.boxbody')
                          .append( list )
                          .find('em')
                              .remove()
                          .end()
                      .end()
                      .appendTo( '.pgextra1 .wrap' );
                });

          article.find('.tilvisun')
              .each(function(){
                  var list = $(this),
                      heading = list.prev('h2, h3, h4').remove();
                  list
                      .removeClass('tilvisun')
                      .wrap('<div class="tilvisun" />')
                      .before(
                          heading[0] ?
                              heading:
                              '<h2 class="title">Tilvísanir:</h2>'
                        )
                      .find('em')
                          .remove();
                      
                });
                
          article.find('table.filtered').Req('filtertable', function() { $(this).filterTable() });

        }); // Article ends


      //file filter
      pgmain.find('.catfiles')
          .Req('/skin/basic/js/filterfiles-min.js')
          .find('li')
              .each(function(){
                  var shortDesc = $('p.shortdesc', this),
                      longDesc = $('p.longdesc', this);
                  if (longDesc.text().length > 0) {
                    longDesc.hide();
                    shortDesc
                        .wrapInner('<a href="#" />')
                        .find('> a')
                            .attr('title', 'Sýna/fela lengri lýsingu')
                            .bind('click', function (e) {
                                longDesc.slideToggle(150);
                                $(this).toggleClass('open')
                                return false;
                              });
                  }
                });


      //maplist madness (/um-okkur/thjonustuleidir/umbodsskrifstofur-um-allt-land/)
      pgmain.find('.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
                      })
                    //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" />');
        });


      //flash video player injection
      pgmain.find('a.video').click(function () {
          $('#videoobj').remove();
          var href = $(this).attr('href');

          if( href.match(/youtube/i) ) {
              $(this).after('' +
                  '<span id="videoobj"><object width="640" height="385">' +
                    '<param name="movie" value="' + href + '"></param>' +
                    '<param name="allowFullScreen" value="true"></param>' +
                    '<param name="allowscriptaccess" value="always"></param>' +
                    '<embed src="' + href + '" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="640" height="385"></embed>' +
                  '</object></span>' +
                '');
          } else {
              $(this).after('' +
                  '<span id="videoobj"><object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8.0.0.0" width="640" height="398">' +
                  '<param name="movie" value="/bitar/common/media/mediaplayer.swf" /><param name="wmode" value="transparent" /><param name="allowScriptAccess" value="always" /><param name="allowFullScreen" value="true" />' +
                  '<param name="flashVars" value="file=' + href + '&type=video&bufferlength=4&autostart=true&skin=/media/videos/skin-dangdang.swf" />' +
                  '<embed src="/bitar/common/media/mediaplayer.swf"' +
                  'flashVars="file=' + href + '&type=video&bufferlength=4&autostart=true&skin=/media/videos/skin-dangdang.swf"' +
                  'width="640" height="398" wmode="transparent" allowScriptAccess="always" allowFullScreen="true" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />' +
                  '</object></span>' +
                '');
          }

          return false;
        });


      //radio button block toggler
      $('.rdotoggler').each(function(){
          var boxes = $(this).find('.togglebox');
          boxes.hide();
          $(this).find('input:radio').bind('change', function (e) {
              if (this.checked == true) {
                boxes.hide().find('.req').removeClass('req');
                $(this).parent().find('.togglebox').show().find('.subreq').addClass('req');
              }
            }).trigger('change');
        });
        
      //checkbox block toggler
      $('.chktoggler > input:checkbox').each(function(){
          var togglebox = $(this).parent().find('.togglebox');
          togglebox.hide();
          $(this).bind('change', function (e) {
              if (this.checked == true) {
                togglebox.show().find('.subreq').addClass('req');
              } else {
                togglebox.hide().find('.req').removeClass('req');
              }
            }).trigger('change');
        });


      //Accessability hacks

      //add bolding button to fontsizer
      var pagestyle = $('.pagestyle'),
          boldtext = isIS ? 'Feitletra texta á síðunni' : 'Bold website text';
      var boldButton = $('<li class="bold"><a href="#" title="'+ boldtext +'">b</a></li>')
              .bind('click', function() {
                  var boldOn = $('body').toggleClass('font-bold').hasClass('font-bold');
                  $.cookie('font-bold', (boldOn ? 'on' : null), { path:'/', expires:365 });
                  return false;
                })
              .prependTo( $('ul', pagestyle) );

      if ($.cookie('font-bold') == 'on') {
        boldButton.trigger('click');
      }
      
      pagestyle.fontsizer({
          minSize      : 0,
          maxSize      : 4,
          defaultSize  : 1
        });


      //sitemap splitter
      pgmain.find('.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" />');

        });



      // fixes for IE
      if (ie6) 
      {
        $('img[src$=".png"]').Req('x/ifixpng', function(){
            $(this).ifixpng();
          });

        //workaround for multiple classnames
        $('div.mnav li.current, div.mnav li.parent').each(function() {
            var ie6class = ' '+ $.trim(this.className.replace(/current|homecurrent|parent|milli|branch/g, '')) +'-ie6';
            this.className += ie6class;
          });
        
        //rendering kick
        $(window).bind('load', function (e) {
            $('body').addClass('kick');
          });
      }


      //rounded corners for browser that dont support border-radius
      if ( $.browser.msie && parseInt($.browser.version) < 9 && !ie6 )
      {
        //rounded corners for 
        Req('roundcorners', function(){
            $('.snav, .sbox .boxhead, .pgextra2 .boxhead').roundCorners();
          });
      }

      //enable mailto links
      $('.netfang').mailtoEnabler();

    } //end loggedin


    $('form').autoValidate();

  }
);
// **** /jqreq *****