// 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(
  'https://secure.eplica.is/codecentre/concat/?utils_1.1.js;ragga_1.0.js;ragga_1.0-e2.js|||utf-8',
  'eutils',
  'fontsizer',
  'autovalidate',
  'equalizeheights',
  'labelizor',
  'mailtoenabler',
  'imgpop',
  'mediaplayer',
  'listscroller',
  'tabswitcher',
  'anchortags',

  function(){
    var $ = jQuery,
        isIS = $('html').attr('lang') == 'is',
        pgm = $('.pgmain'),
        article = pgm.find('.article');

    var texts = {
        is: {
            topofpagetext: 'Aftur upp'
          },
        en: {
            topofpagetext: 'Top of page'
          }
      };
    texts = texts[ $.lang() ]  ||  texts.en;

    // labelize search input
    $('#qstr').labelizor();

    //Hide/show wildcard amount in "donate" forms.
    if ($('.styrkja, .minningarkort').length)
    {
      var otheramount = $('#oamnt');
      otheramount.is(':checked') ? otheramount.trigger('click') : ''
      otheramount.bind('change', function (e) {
          var subreq = $('.subreq'),
              sel = $('.fi_sel');
          
          sel.toggleClass('req');
          subreq.toggleClass('req');
          sel.is(':visible') ? sel.hide() : sel.show()
          subreq.is(':visible') ? subreq.hide() : subreq.show()
      });
    }

    if (!window.EPLICA_loggedin)
    {

      if ( $('body').is('.home') ) {

        $('.tnav').prepend('<span class="icn" />');

        var booklist = pgm.find('.booklist');

        booklist
            .each(function(){
                $(this)
                  .listscroller({ 
                      item:        '.item',
                      aspect:      'horizontal',
                      paging:      true,
                      statusPager: true,
                      itemStatusPager: true,
                      jumpPager:   false,
                      animation:   'carousel',
                      windowSize:  2,
                      stepSize:    2,
                      labelNext:   'Næstu',
                      labelPrev:   'Fyrri',
                      titleNext:   'Næstu bækur',
                      titlePrev:   'Fyrri bækur',
                      statusLabel: 'Bækur '

                    })
              })
            .makeTabbox()
                .tabSwitcher();

        //Wrap articlelists in 'eqheight' and equalize it's height with .pgmain articlelist
        pgm.find('.wrap').append('<div class="eqheight" />');
        pgm.find('.booklist, .tab-box').appendTo('.eqheight');
        pgm.find('.articlelist, .eqheight').equalizeHeights();

      } else {

        $('.booklist')
              .filter(function() { return $(this).find('.item').length > 6 })
              .listscroller({ 
                    item:        '.item',
                    aspect:      'horizontal',
                    paging:      true,
                    statusPager: true,
                    itemStatusPager: true,
                    jumpPager:   false,
                    animation:   'carousel',
                    windowSize:  6,
                    stepSize:    6,
                    labelNext:   'Næstu',
                    labelPrev:   'Fyrri',
                    titleNext:   'Næstu bækur',
                    titlePrev:   'Fyrri bækur',
                    statusLabel: 'Bækur '
                  });
      }
      
      //Create facebook sharer link.
      $('p.buttons')
                .append(
                    $('<a class="btnfacebook">Senda á Facebook</a>')
                        .attr(
                            'href',
                            'http://www.facebook.com/sharer.php?u='+encodeURIComponent(document.location.href)+'&t='+encodeURIComponent($('h1').text()+' | '+$('img.logo:first').attr('alt') )
                          )
                        .bind('click', function() {
                            window.open($(this).attr('href'),'sharer','toolbar=0,status=0,width=626,height=436');
                            return false;
                          })
                  );

      //tag external urls
      pgm.find('.article a, .articlelist a').not('.buttons a')
          .anchorTags({
              usePatterns:  ['doc', 'pdf', 'xls', 'audio']
            })
          .filter('.external, .file_pdf, .file_doc, .file_xls, .file_audio')
              .each(function() {
                  var match = $(this)[0].className.match(/(^| )file_([a-z]+)( |$)/);
                  if ( match ) 
                  {
                    var text = match[2],
                        text = text == 'audio' ? "MP3" : text;
                    $(this).attr('title', text+' skjal').append(' <span class="icon">('+ text +')</span>');
                  }
                  else if ( $(this).is('.external') )
                  {
                    var externalText = isIS ? 'Opnast í nýjum vafraglugga' : 'Open in new window';
                    $(this).attr('title', externalText).append(' <span class="icon">('+ externalText +')</span>');
                  }
                });

      
      // pngfix for IE6
      if ($.browser.msie && $.browser.version < 7) {
        $('img[src$=".png"]').Req('x/ifixpng', function(){
            $(this).ifixpng();
          });
      }

      //zebra tables
      pgm.find('tbody tr:nth-child(2n-1)').addClass('odd');


      //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
            });
/*
      $('div.spurt:not(.articlelist) .boxbody').run(function() {

          $('> h3', this).each(function(){
              var h3 = $(this);

              h3.add( h3.nextUntil('h2,, h3, p.buttons') ).wrapAll('<div class="question" />');
              h3.nextUntil('h2,, h3, p.buttons').wrapAll('<div class="answer" />');

              var answer = h3.next();
              answer.hide();

              h3.wrapInner('<a href="#" />').find('a').bind('click', function (e) {
                  answer.toggle();
                  answer.parent().toggleClass('answer-open');
                  return false;
                });
            });

        });
*/
      //ajaxlist ajax
      pgm.find('.ajaxlist .item').each(function() {
          var item =     $(this),
              link =     item.find('h3 a, .more a'),
              summary =  item.find('.summary'),
              moreLink = summary.find('.more a'),
              moreText = $.trim( moreLink.text() ) || '',
              closeText = moreText.length ? 'Loka' : '',
              isOpen =   false;

          link
              .bind('click', function (e) {
                  var summaryText = link.data('summaryText');
                  if (summaryText)
                  {
                    summaryText.slideToggle('fast');
                  }
                  else
                  {
                    item.addClass('ajaxload');
                    $.get(
                        link.attr('href'),
                        { justPicPos: 'pgmain' },
                        function(data){
                            var summaryText = $(data).find('.article .boxbody');
                            summaryText
                                .removeClass('boxbody')
                                .addClass('summwrap')
                                .find('h1, .buttons')
                                    .remove()
                                .end()
                                .hide()
                                .prependTo( summary )
                                .slideDown('fast');
                            link.data('summaryText', summaryText);
                            item.removeClass('ajaxload');
                          }
                      );
                  }
                  
                  item.toggleClass('open');

                  moreLink
                    .text( !isOpen ? closeText : moreText )
                    .toggleClass('open', !isOpen);
                  
                  isOpen = !isOpen;
                  return false;
                });
        }); // end ajaxlist


      //insert raggaplay into articles
      article.filter(':first').find('>.boxbody')
        .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 title="Hlusta á vefþuluna lesa textann" href="#">Hlusta á textann</a></div>');
      if (window.RaggaEasy) {
        RaggaEasy.init();
      }
      
       //init videolist script
      pgm.find('.videolist').Req(
          'http://codecentre.eplica.is/jquery/quickies/quicky-videoplayer-min.js',
          function() {
            $(this).videoList({
               vidWidth: 596,
               vidHeight: 354,
               autostart: 'all',
               //defaultImg: '/media/baejarstjornarfundir/defaultimg.png'
            });
          }
        );


      var ytTempl = '<object height="%{height}" width="%{width}">' +
                        '<param value="http://www.youtube.com/v/%{file}" name="movie"><param value="true" name="allowFullScreen"><param value="always" name="allowscriptaccess">' +
                        '<embed height="%{height}" width="%{width}" src="http://www.youtube.com/v/%{file}" allowfullscreen="true" allowscriptaccess="always" type="application/x-shockwave-flash"></object>';
      article.find('.ytlink')
                .each(function(){
                    var videoUrl = $(this).attr('href').split('?')[1].match(/v=([^&]+)/)[1],
                        vidWidth = 480,
                        vidHeight = 385;
                    $(this).wrap('<span class="ytvideo" />')
                                .parent().html(
                                            $.inject(ytTempl, {
                                                  file : videoUrl,
                                                  width : vidWidth,
                                                  height : vidHeight
                                                })
                                          );

                  });


    } // end loggedin

    //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      : 3,
        defaultSize  : 1
      });

    
    //sitemap collapser
    pgm.find('.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();
    $('form').autoValidate();
    $('.netfang').mailtoEnabler();

  }
);
// **** /jqreq *****

