  // 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',
  'fontsizer',
  'autovalidate',
  'anchortags',
  'curtain',
  'labelizor',
  'imgpop',
  'equalizeheights',
  'mailtoenabler',
  'fickle',
  'tabswitcher',
  'virtualbrowser',
  'x/ui-fxcore',
  'q-alistdatesplit',
  
  
  function(){
    var $ = jQuery,
        MSIEver = parseFloat($.browser.verson),
        isMSIE = $.browser.msie && MSIEver<9,
        bdy = $('body').addClass('jsactive');

    // labelize search input
    $('#qstr, #fkt, #fpw, #f5').labelizor();

    //equalize heights
    $('body:not(.home) .mwrap > div').equalizeHeights();

    //tabswitcher
    $('.topboxes > div')
        .each(function(){
            $(this).find('.tab')
                .makeTabbox()
                    .tabSwitcher();
          });

    var texts = {
        is: {
            newWindow:        'Opnast í nýjum vafraglugga',
            fileText:         'skjal'
          },
        en: {
            newWindow:        'Opens in new window',
            fileText:         'file'
          }
      };
    texts = texts[ $.lang() ]  ||  texts.en;

    // give h3 and syblings indent in .article .yfirlit
    //$('.yfirlit h3').nextUntil('h3, h2, .buttons').andSelf().wrap('<div class="indent" />');
                  
        /*
        //hide tr of each table 
        var tr = $('.sala table tbody tr'),
            i = 2,
            sTable = $('.sala table');

        sTable.each(function(){
             var i = 2,
              trChild = $(this).children('tbody').children('tr');
                tr.each(function(){
                    $(trChild[i]).hide();
                    i++;
                  });
          });
         
         //hmm, do you need two 'each' functions? ^,^
         
        //add more button to table
        sTable.each(function(){
              var text = $(this).prev('h2').text().toLowerCase(),
                      trChild = $(this).children('tbody').children('tr'),
                      trCount = trChild.length;
            if ( trCount > 2 ) {
              $(this).children('tfoot')
                  .children('tr').children('th')
                      .append('<a href="#" class="more">Sjá fleiri '+text+' til sölu</a>')
                          .bind('click', function(){
                              var trChild = $(this).closest('table').children('tbody').children('tr'),
                                      i = 2;

                              $(trChild[i]).is(':hidden') ? 
                                  $(this).html('<a href="#" class="more">Sjá færri '+text+' til sölu</a>').addClass('open')
                                      .closest('table').children('tbody').children('tr').show():
                                  $(this).html('<a href="#" class="more">Sjá fleiri '+text+' til sölu</a>').removeClass('open')
                                      .parents('table')
                                          .children('tbody').children('tr')
                                              .each(function(){ // try to trigger the function above which does the exact same thing
                                                  $(trChild[i]).hide();
                                                  i++;
                                                });
                            $('body .mwrap > div').equalizeHeights();
                            return false;
                          });
            }
        });*/
                
    var popupCont,
        f = isMSIE ? 0 : 1,
        getPopup = function () {
            var curtainElm = $.curtain({
                          className: 'popup-curtain',
                          bg:        '#ffffff',
                          opacity:   .90,
                          fixed:     true
                        }),

                popupCont = $('<div class="virtualiframe-container" />')
                                .fickle({
                                    fadein: 250*f,
                                    fadeout: 250*f,
                                    closeOnEsc: false,
                                    trapFocus: true,
                                    onOpen: function(){
                                        $(this)
                                            .appendTo('body')
                                            .before(curtainElm)
                                            .css({ marginLeft: - $.toInt( popupCont.outerWidth() ) / 2 })
                                            .find('.virtualiframe')
                                                .css( 'top', '50px' );
                                        curtainElm.show();
                                      },
                                    onClosed: function(){
                                        popupCont.remove();
                                        curtainElm.remove();
                                      },
                                    focusTarget: ''
                                  }),

                frameElm =  $('<div class="virtualiframe">' +
                            '<a href="#" class="focustarget">.</a>' +
                            '<div class="wrap" />' +
                          '</div>')
                            .bind('click', function (e) { e.stopPropagation(); })
                            .appendTo( popupCont ),

                body =  frameElm.find('.wrap')
                            .virtualBrowser({
                                params:       'justPicPos=pgmain',
                                loadmsgMode:  'replace',
                                onBeforeload: function (e, request) {
                                    var url = request.url;
                                    if ( request.elm.is('form') && !request.elm.is('.terms') )
                                    {
                                      e.passThrough = true;
                                    }
                                  },
                                onLoad: function (e, request) {
                                    var box =  $.getResultBody(request.result)
                                                   .find( '.pgmain .wrap > *' );
                                    if (box.length)
                                    {
                                      box.wrap('<div />').filter('form').autoValidate();
                                      request.resultDOM = box;
                                      box.find('#fkt, #fpw').labelizor();
                                    }
                                    else
                                    {
                                      request.resultDOM = $('<div class="nothingfound">Nothing found...</div>');
                                      setTimeout(function(){ popupCont.fickle('close'); }, 1000);
                                    }
                                    if (box.filter('.terms').length) {
                                        box.filter('.login').hide();
                                    }
                                  }
                              });

            // make a close button.
            $('<a href="#" class="closebtn" title="Loka">Loka</a>')
                .appendTo( frameElm )
                .bind('click', function (e) {
                    popupCont.fickle('close');
                    return false;
                  });

            popupCont.data( 'popup-body', body );

            return {
                container: popupCont,
                body: body
              };
          };



    $('.buy a, a.contactform, .mailinglist, .sala .imglink')
        .each(function(i, link){
            var buyLink = $(this);
                isFile = $.trim(buyLink.attr('href')).match(/\.(pdf|doc?x|xls?x)$/);

            //chech if user is logged in or if link is to no page at all(.ie if this is an image link and goes nowhere).
            if ( !isFile && !buyLink.is('.isloggedin > *')  &&  buyLink.attr('href') != '#' )
            {
              var linkId = buyLink.attr('class').split(' ')[0]+'-window',
                   linktext = buyLink.text();
              buyLink
                  .bind('click', function (e) {
                      var popup = getPopup(); // <-- returns popup object with container and body (.wrap) elemets
                      popup.container
                          .addClass(linkId)
                          .fickle('open', { opener: buyLink }); // opener is the link/button that receives the focus back when the fickle window is closed
                      popup.body
                          .bind('VBloaded', function (e) {
                              $(this).find('form').bind('submit', function (e) {
                                  if (!$(this).isValid())
                                  {
                                    return false;
                                  }
                                });
                            })
                          .virtualBrowser('load', this);
                      return false;
                    });
            }
            if (isFile)
            {
              buyLink.attr('target', '_blank')
            }
          });

     /* $('.buy input').each(function(i, link){
           var buyLink = $(this);
           if ( !buyLink.is('.isloggedin > *') ) {
             var linkId = buyLink.attr('class').split(' ')[0]+'-window';
             buyLink // the form
                 .bind('click', function (e) {
                     var popup = getPopup(); // <-- returns popup object with container and body (.wrap) elemets
                     popup.container
                     .addClass(linkId)
                         .fickle('open', { opener: buyLink }); // opener is the link/button that receives the focus back when the fickle window is closed
                     popup.body
                         .virtualBrowser('load', this);
                     return false;
                   });
             }
         });*/
        
        

                
    //remove the open class when a tab is clicked, otherwise 
    $('body.home .tabs li a')
        .bind('click', function(){
            $(this).closest('.boxbody').removeClass('open');
          });
         
      
    //add more button to thead > tcol3 
    var thead = $('.thead'),
         table = $('table.closed'),
         morebtn = '<a class="more" href="#">Sjá meira</a>';

    if ( !table.closest('.article').is('.yfirlit') ) 
    {
      table
        .each(function(){
            $(this).hide();
        });
      thead.find('.open')
        .each(function(){
          $(this).append(morebtn);
        });
      thead
          .each(function(){
              var openA = $(this).find('.open a'),
                  tTable =  $(this).closest('.item').children('table');
              $(this).bind('click', function (e) {
                  $(this).toggleClass('open').closest('.item').find('table').toggle();
                  openA.text( tTable.is(':hidden') ? 'Sjá meira' : 'Sjá minna' );
                  $.equalizeHeights;
                  return false;
                });
            });
              
    }


    //toggle list items
    var mapNav = $('.rlist');
    mapNav.find('.level1 > li > a.more').each(function(){
        var levelOneLink = $(this),
            thisLevelTwo = levelOneLink.nextAll('.level2'),
            isOpen = false;
        mapNav.find('.level2').hide();
        levelOneLink.click(function(){
            levelOneLink.toggleClass('less').html( isOpen ? 'Sjá meira' : 'Sjá minna' );
            thisLevelTwo.slideToggle();
            isOpen = !isOpen;
            return false;
          });
      });


    if (!window.EPLICA_loggedin)
    {

      // pngfix for IE6
      if (isMSIE  &&  MSIEver < 7)
      {
        $('img[src$=".png"]').Req('x/ifixpng', function(){
            $(this).ifixpng();
          });
      }

      //zebra tables
      $('tbody tr:nth-child(2n-1)').addClass('odd');
      //$('tbody tr:nth-child(2n)').addClass('even');


      //popup in articles
      $('.article .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
            });
            
      //init videolist script
      $('.articlelist.lbox')
          .alistDateSplit({
              monthAfterDate: 0
            });

      //animate between classess 
      $('.topboxes .boxbody')
          .append('<a class="moreboxbtn" href="#">Sjá fleiri</a>')
          .find('.moreboxbtn')
              .bind('click', function () {
                var morebbtn = $(this),
                    btnparent = $(this).parent('.boxbody');
                  btnparent.toggleClass('open');
                  btnparent.hasClass('open') ? morebbtn.text('Sjá færri') : morebbtn.text('Sjá fleiri');
                  return false;
                });

      //add border to utbod
      $('.utbod .item:odd')
          .after('<span class="utline"/>')

      //mailto enabler
      $('.netfang').mailtoEnabler();

      //tag external urls <- added 2011
      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() +' '+ texts.fileText;
                        }
                        else if ( $(this).is('.external') )
                        {
                          text = texts.newWindow;
                          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> ');
                        }
                      });

      //add pdf, xls and doc classes to "aukaskjöl" <- existed 2011
      $('.gogn a')
          .each(function () {
              var text = $(this).text(),
                   matchXls = /\.(xlsx?|csv|ods|sxc)(#|$|\?)/.exec(text),
                   matchDoc = /\.(docx?|rtf|wri|odt|sxw)(#|$|\?)/.exec(text),
                   matchPdf = /\.(pdf)(#|$|\?)/.exec(text);
              if (matchXls)
              {
                $(this).addClass('xls');
              }
              else if (matchDoc)
              {
                $(this).addClass('doc');
              }
              else if (matchPdf)
              {
                $(this).addClass('pdf');
              }
            });

      //adding the xls style can cause some problems, hence:
      $.equalizeHeights();

      bdy.find('.frog')
          .each(function () {
              var rand = function (min, max) {
                      return Math.floor(Math.random() * (max - min + 1)) +min;
                    },
                  fclass = $(this).attr('class').split(' '),
                  i = 0;
              
              while (i < fclass.length)
              {
                var x = 1;
                while (x < 6)
                {
                  if (fclass[i] != 'frog'+x )
                  {
                    $(this).addClass('frog'+rand(0,6));
                    return;
                  }
                  x++;
                }
                i++;
              }
            });
    }

    //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();

    // fontsizer
    $('.pagestyle').fontsizer();

    // validate all forms
    $('form').autoValidate();

  }
);
// **** /jqreq *****
