// encoding: utf-8
/*@cc_on/*@if(@_jscript_version<5.7)try{document.execCommand('BackgroundImageCache',0,1)}catch(e){}/*@end@*/

Req.localPath = Req.localPath || '/skin/basic/';

Req(
  'autovalidate',
  'eutils',
  'curtain',
  'equalizeheights',
  'fickle',
  'fontsizer',
  'imgpop',
  'jquery',
  'listscroller',
  'ontime',
  'simplecarousel',
  'tabswitcher',
  //'x/resize',
  Req.localPath+'js/jquery.minitabs.js',
  Req.localPath+'js/jquery.displaybox.js',
  Req.localPath+'js/jquery.popupdiv.js',
  function(){
    var $ = jQuery;

    var body = $('body').addClass('js-active');


    // *** logolisti (middle images on y-axis)
    $('div.logolisti li img, div.companyinfo div.thumblist img')
        .each(function(){
            $(this)
              .css('backgroundImage', 'url(' + this.src + ')')
              .attr('src', '/skin/basic/design/i/blank.gif'); // inn á servernum á að vera '/skin/basic/design/i/blank.gif'
          });



    // *** logolisti (carousel wrappers)
    var ll = $('div.logolisti'),
        ul = ll.find('ul');

    ll.find('li').each(function(i){

        if (i % 8 == 0) {
          ul = $('<ul></ul>');
          $( this ).parent().before( ul );
        }
        ul.append( this );

      });

    ll.find('ul:not(:has(li))')
      .remove();



    // *** carousel init
    if (jQuery.fn.simpleCarousel)
    {
      ll.find('.boxbody').simpleCarousel({
        item            : 'ul',
        nextBtnTemplate : '<a href="#" class="next">Næsta síða</a>',
        prevBtnTemplate : '<a href="#" class="prev">Fyrri síða</a>',
        wrap            : true
      });
    }



    // *** subscr popupdiv
    var subscr = $('div.subscr');

    var spop = subscr
        .find('> form.boxbody')
            .popupdiv()
                .parent()
                    .addClass('subscr-popup')
                    .hide();


    subscr
        .after( spop )
        // fix the subscr box on the frontpage after the popupdiv has been built
        .append('<div class="boxbody">'+
                  '<p class="more moreolder">'+
                    '<a href="#subscr_popup">' + spop.find('p.desc').text() + '</a>'+
                  '</p>'+
                '</div>')
        .find('p.moreolder a')
            .click(function(e){
                spop.pop();
                return false;
              });


    // extras link/links that can open the popup
    $('div.quicknav li.cat3 a')
        .attr('href', '#')
        .click(function(){
            spop.pop();
            return false;
          });

    $('div.pgfoot div.subscr').remove(); // throw the box away as we use a different link as trigger


    // *** contact popup (with the tabswitch)
    var contactbox = $('.contactnav')
          .add('.contactpane')
          .wrapAll('<div class="contactbox"></div>')
          .parent()
          .popupdiv();
          

    var contactpop = contactbox
        .parent()
            .addClass('contact-popup')
            .hide();

    if( $('html').attr('lang') === 'is' )
    {
      $('div.footer div.boxbody')
          .append(
            $('<div class="act"><a href="#" class="contact">Hafðu samband</a></div>')
              .click(function(){
                contactpop.pop();
                return false;
              })
          );
    }


    // *** companyinfo browser
    var ci = $('div.companyinfo');
    function setImg ( thumbitem, ldesc )
    {
      thumbitem.parents('.thumblist').find('.current').removeClass('current');
      thumbitem.parents('li').eq(0).addClass('current');
      
      // make new fullimage
      var alt   = thumbitem.find('img').attr('alt'),
          title = thumbitem.find('img').attr('title'),
          desc  = '',
          src   = thumbitem.attr('href'),
          newImg = $( '<div class="image"><span class="img"><img alt="' + alt + '" src="' + src + '"/></span></div>' );
      
      if ( title || desc ) {
        var longdesc = $('<div class="longdesc"></div>');
        newImg.append( longdesc );
        if ( title ) {
          longdesc.append( '<strong class="title">'+title+'</strong>' );
        }
        if ( desc ) {
          longdesc.append( '<div class="desc">'+desc+'</div>' );
        }
      }
      
      newImg.hide();
      ci.find( '.fullsizeimg .image:first') .before( newImg );
      
      var img = newImg.find('img');
      var runner = function () {
        ci.find( '.fullsizeimg .image:not(:first)' ).slideUp( 400, function () { $( this ).remove(); });
        newImg.slideDown( 400 );
      };
      
      $(img).load( runner );
      return newImg;
    };

    if ( ci.length )
    {
          // get big image
      var fullimage  = ci.find('.fullsizeimg .image'),
          currentSrc = fullimage.find('img').attr('src'),
          // get thumbnails
          thumblist = $('.thumblist', ci),
          thumbs = $('li', thumblist),
          // animate in
          delay = 0;
      
      thumbs.each(function (i) {
        var item = $(this);
        item.hide();
        
        setTimeout(function () {
          thumbs.eq(i).fadeIn();
        }, (70 * i));
        
        item.find('a').click(function () {
          if ($(this).parent().is('.current')) {
            return false;
          }
          var thumb = $(this),
              // has longdesc
              desc = $('img', this).attr('longdesc');
          if (desc) {
            $.ajax({
              type : 'GET',
              url : desc,
              dataType : 'text',
              cache : true,
              success : function ( ret ) { fullimage = setImg( thumb, '' ); }
            })
          }
          else {
             fullimage = setImg( thumb, '' );
          }
          
          return false;
        });
      });
      
      ci.find('p.more').clone().appendTo(thumblist)
    }

    
    

    // *** minitabs
    $('ul.tabs').minitabs();


    // *** fontsizer
    $('div.pagestyle').fontsizer();



    /* *** article imagelist & galleries (carousel & lightbox) *** */
    var imagelist = $('.article ul.imagelist');

    imagelist
        .removeClass('imagelist')
        .wrap('<div class="imagelist" />')
        .find('a')
            .each(function(){
                var img = $('img', this)[0];
                //this.href = img.src.replace(/\/[^\/]+\/([^\/]+)$/, '/glarge/$1');
                var longDesc = $(this).parent().find('div.longdesc');
                img.title = $('.title', longDesc).text();
                img.alt =   $('.descr', longDesc).text();
              })
            .imgPopper();

    if (imagelist.find('li').length>1)
    {
      imagelist
          .simpleCarousel({
              // labelNext: '>>',
              // labelPrev: '<<',
              // wrap: true,
              item : 'li'
            });
    }



    if (!window.EPLICA_loggedin)
    {
      $('body.home').find('.sbox-mappa').each(function(){
          var imgCont = $(this).find('.boxbody > div:first'),
              imgs = imgCont.find('a:has(img), img:not(:descof(a))').detach().get().sort(function(){ return Math.random()>.5 }),
              i = imgs.length;

          imgCont
              .addClass('crossfader-active')
              .empty()
              .append( imgs[0] )
              .ontime({
                  interval: 5000,
                  bubble:   false,
                  fn:       function (e) {
                                var lastimg = $(imgs[0]).fadeOut(500, function(){ $(this).detach(); });
                                imgs.push( imgs.shift() );
                                $(imgs[0])
                                    .hide()
                                    .appendTo( this )
                                    .fadeIn(500);
                              }
                });
        });
    }


/* BEGIN: e2focus */
    $('body.home').find('.e2focusbox').each(function(){
        var box = $(this),
            ulElm = box.find('ul').fin(),
            items = box.find('li').fin(),
            realClick,
            i = items.length-1;
        items
            .each(function(){
                  $(this).find('a').append( $(this).find('i,em') )
                })
            .append('<span class="timer" />')
            .find('i,em')
                .hide()
                .bind('mouseenter', function (e) { ulElm.ontime('pause', 'ticker'); })
                .bind('mouseleave',  function (e) { ulElm.ontime('resume', 'ticker'); })
                .bind('click', function (e) { e.stopPropagation(); })
            .end()
            .bind('click', function (e) { realClick = true; })
            .bind('click.switcher', function (e) {
                var thisIdx = items.index(this);
                if (thisIdx != i)
                {
                  realClick  &&  ulElm.ontime('end', 'ticker');
                  i = thisIdx;
                  ulElm
                      .ontime({
                          label:    'ticker',
                          start:    0,
                          interval: 1000,
                          reps:     7,
                          bubble:   false,
                          fn:       function(e, count, cfg){
                                        (count===0)  &&  items.eq(i).addClass('current').find('i,em').fadeIn(900);
                                        ulElm.removeClass('tick-'+(count-1));
                                        (count < cfg.reps-1)  &&  ulElm.addClass('tick-'+count);
                                        (count == cfg.reps-2) && items.eq(i).find('i,em').fadeOut(900);
                                      },
                          end:      function(e, cfg){
                                        items.eq(i).removeClass('current').find('i,em').hide();
                                        if (!realClick)
                                        {
                                          var next = (i+1) % items.length;
                                          setTimeout(function(){
                                              items.eq(next).trigger('click.switcher');
                                            }, 0);
                                        }
                                      }
                        });
                }
                realClick = false;
                return false;
              })
            .eq(0)
                .trigger('click.switcher');

      });
      


/*
    $('.e2blackbox').each(function(){
      
        var box = $(this),
            objects = $([]);

        box.find('.contact-us h3 a')
            .bind('click', function (e) {
                $('.footer a.contact').trigger('click');
                return false;
              });
        box.find('.item')
            .equalizeHeights()
            .each(function(){
                objects = objects.add( $(this).find('img, object, embed').filter(':last').detach()[0] );
              })
            .each(function(i){
                this.itemIndex = i;
              })
            .bind('click', function (e) {
                popupCont
                    .fickle('open', { opener: this })
                    .find('.jump a:eq('+this.itemIndex+')')
                        .trigger('click');
                return false;
              })
            .find('h3')
                .wrapInner('<a href="#" />');

        var f = $.browser.msie ? 0 : 1,
            popupCont = $('<div class="lightbox"><div class="box"><h2>Eplica kerfið</h2> <a href="#" class="closebtn">Loka</a></div></div>')
                              .appendTo('body')
                              .fickle({
                                  onOpen: function(e){ $(this).curtain(); }, // to get correct curtain height - otherwise too tall
                                  fadein:  600*f,
                                  fadeout: 600*f
                                })
                              .bind('click', function (e) {
                                  $(this).fickle('close');
                                });
            popup = popupCont.find('.box').fin()
                        .bind('click', function (e) {
                            return false;
                          });
            popupHead = popup.find('h2').fin();

        popup.find('.closebtn')
            .bind('click', function (e) {
                popupCont.fickle('close');
              });

        objects = objects
                      .insertAfter(popupHead)
                      .wrap('<div class="item" />')
                      .parent()
                          .fin()
                          .listscroller({
                              windowSize:  1,
                              wrap:        'none',
                              animation:   'crossfade',
                              paging:      true,
                              statusPager: true,
                              statusLabel: 'Myndband '
                            });
      });

*/

      var blackboxitms = $('.e2blackbox .item');
      
      blackboxitms.eq(0).addClass('focus-platforms');
      blackboxitms.eq(1).addClass('focus-issearch');
      blackboxitms.eq(2).addClass('focus-media');
      blackboxitms.eq(3).addClass('focus-simple');

/* END: e2focus */




    // *** removeflicker
    $('#noflickerCSS').remove();
      
      
    $('div.companyinfo-tabpane').makeTabbox().tabSwitcher({ showFirst: true });


    // *** autoValidator
    if ($.av)
    {
      var excludes = $('#cp_email form, #cp_call form, div.popup form, div.qsearch form').get();
      $( 'form' ).not( excludes ).autoValidate();
    }


    // helper function that trims a html doc for use as jquery object
    jQuery.cleanDoc = function ( r ) {
      r = r.replace(/<(script).*?<\/\1>/g, '')
           .replace(/ +/g, ' ');
      r = (r.indexOf('<body') !== -1) ? r.match(/<body[^>]*>([\s\S]*?)<\/body>/)[1] || '': r;
      return jQuery.trim( r ) || "";
    };


    /* *** contactpane ajax forms *** */
    $('div.contactpane form')
        .bind('submit', function(e) {
            var theForm = $(this);
            if (theForm.isValid()) {
              var action = theForm.attr('action') || document.location.toString().replace(/([?#].*)?$/, '');
              $.post(action, theForm.serialize(), function(response) {
                if ( /ekki svarað rétt/.test( response ) ) {
                  var ctrl = theForm.find( 'input[name=spm_answer]' ).parents( 'div.fi_txt' ).eq( 0 );
                  var msg = $( $.cleanDoc(response) ).find( 'div.box .boxbody' ).eq( 1 ).text();
                  ctrl.addClass( 'typeerror' );
                  var lbl = ctrl.find( 'label:first' ).text().replace( /(^[:*]|[:]$)/g, '' );
                  alert( lbl + "\n\n" + $.trim( msg ) );
                }
                else {
                  var newDoc = $(response).find('div.box .boxbody').eq(1).html();
                  theForm.before('<div class="boxbody" id="response"><p>' + newDoc + '</p></div>');
                  theForm.remove();
                }
              });
            }
            return false;
          });


    /* *** postlisti ajax forms *** */
    $('div.subscr-popup form')
        .bind('submit', function(e) {
            var theForm = $(this);
            if (theForm.isValid()) {
              var action = theForm.attr('action') || document.location.toString().replace(/([?#].*)?$/, '');
              $.get(action, theForm.serialize(), function(response) {

                var tst = /<form[^>]*?name="formMailingListRegistration"[^>]*?>([\s\S]*?)<\/form>/g.exec( response );
                if ( /staðfesting var send/i.test( tst[1] ) )
                {
                  var newDoc = $( $.cleanDoc(response) ).find('div.subscr .boxbody').eq(0).html();
                  window.newDoc = newDoc;
                  window.response = response;
                  theForm.before('<div class="boxbody" id="response"><p>' + newDoc + '</p></div>');
                  theForm.remove();
                }
                else
                {
                  var ctrl = theForm.find( 'input[name=VIS_Email]' ).parents( 'div.fi_txt' ).eq( 0 );
                  ctrl.addClass( 'typeerror' );
                  var lbl = ctrl.find( 'label:first' ).text().replace( /(^[:*]|[:]$)/g, '' );
                  alert( 'Þessir liðir eru rangt útfylltir:\n\n' + lbl );
                }

              });
            }
            return false;
          });


    // fix for when to call
    $('#cp_call div.fi_email').eq(0).removeClass('fi_email').addClass('req');


    // fix look for contactform in popup
    $('#cp_call, #cp_email').each(function(){
        $('.fi_txt', this).wrapAll('<fieldset />');
      });
      
      
    //sitemap collapser
    $('div.sitemap').Req('treecollapse', function() { 
        $(this).treeCollapse({ 
            branch: 'li:has(ul)', 
            doTogglers: 1, 
            toggler: '> a.expand',
            startOpen: 'ul.level1 > li:has(ul)'
          }); 
        });
        
        
        
        
    // Listscroller
      $('div.fbox > .boxbody:has(.item)')
        .find('h3')
            .append('<a class="focustarget" href="#">.</a>')  // For accessibility
        .end()
        .listscroller({
            item: '.item',
            paging: true,
            windowSize: 1,
            stepSize: 1,
            autoScrollDelay: 5000,
            animation: 'crossfade',
            /*jumpLabel: 'Vert að sjá ',
            titleNext: 'Fletta í næstu frétt',
            labelNext: 'Næsta frétt',
            titlePrev: 'Fletta í fyrri frétt',
            labelPrev: 'Fyrri frétt',
            statusLabel: 'Frétt: '*/
          });
          
    // Listscroller
      $('div.fbox > .boxbody:has(li)')
        .listscroller({
            item: 'li',
            paging: true,
            windowSize: 1,
            stepSize: 1,
            autoScrollDelay: 5000,
            animation: 'crossfade'
          });
          
          
          
     // Append More link, wrap detail info, hide detail info, set toggle function, etc. 
          var coreInfo =  $('.core-info');         
          coreInfo.each(function() {
              $(this).append('<div class="toggler"><a href="#">More</a></div>');
              $(this).children().not('.summary, .toggler, h2').wrapAll('<div class="details-toggle" />'); 
            });
          var toggleDiv = $('div.toggler', coreInfo),
              toggler = $('a', toggleDiv), 
              details = $('.details-toggle', coreInfo); 
              details.hide();
              toggler.toggle(
                  function () {
                      $(this)
                          .parent()
                              .addClass('active')
                              .prev(details)
                                  .show()
                              .end()
                          .end()
                          .html('Less');
                    },
                  function () {
                      $(this)
                          .parent()
                              .removeClass('active')
                              .prev(details)
                                 .hide()   
                              .end()
                          .end()
                          .html('More');
                    }
                );
                    
            
     // Carousel - About
    $('div.marquee.about img')
        .each(function(){
            $(this)
              .css('backgroundImage', 'url(' + this.src + ')')
              //.attr('src', '/skin/basic/design/i/blank.gif'); // inn á servernum á að vera '/skin/basic/design/i/blank.gif'
          });

    // Carousel init
    var mq = $('div.marquee.about');
    mq.find('li:nth-child(3n+3)').css('margin-right','0');  //nth-child selector for IE which can't handle CSS3 for this.
    mq.find('li:nth-child(3n+1) span').css('display','block');  //nth-child selector for IE...        
    if (jQuery.fn.simpleCarousel)
    {
      mq.find('.boxbody')
          .simpleCarousel({
              item            : 'ul',
              nextBtnTemplate : '<a href="#" class="next">Næsta síða</a>',
              prevBtnTemplate : '<a href="#" class="prev">Fyrri síða</a>',
              wrap            : true
            });
    }
  
    /* *** Lightbox from carousel *** */
    var marqueelist = $('.marquee ul');

    marqueelist
        .wrap('<div class="imagelist" />')
        .find('a')
            .each(function(){
                var img = $(this).find('img');
              })
            .imgPopper({
                curtainColor : '#ffffff',
                curtainOpacity : '0.75'
              });


              
              
              
              

              
              
              
              
              
              
              
              
     //popup windows
      $.fn.popup = function ( cfg ) {
          var popupElm = this;
          if ( popupElm.length) { 
            var curtainElm = $.curtain({
                        className: 'popup-curtain',
                        bg:        '#ffffff',
                        opacity:   .70
                      });
            popupElm
                .hide()
                .appendTo('body')
                .addClass('popupbox')
                .prepend('<a class="focustarget" href="#">#</a>')
                .before(curtainElm)
                .css({
                      top:        100 + $(window).scrollTop(),
                      marginLeft: - $.toInt( popupElm.outerWidth() ) / 2
                    })
                .fickle({
                    fadein: 350,
                    onOpen:   function (e) { $(this).prev().fadeIn(100)  },
                    onClose:  function (e) { popupElm.fadeOut(200, function() { $(this).prev().fadeOut(100); }) },
                    onClosed: function (e) {  }
                  })
                .append('<a class="close" href="#">Loka glugga <span>x</span></a>')
                .find('a.close')
                    .bind('click', function (e) {
                        popupElm.fickle('close');
                        return false;
                      })
                .end()
                .fickle('open');
          }
          return popupElm;
      };


     //Ajax
     // Any link with class "popup" will trigger the Ajax get event.
     var popanchors = $('a')
      popanchors.filter('.popup')
          .bind('click', function (e) {
              var link = $(this),
                  popupForm = link.data('popupForm');
              if (popupForm)
              {
                popupForm.fickle('open');
              }
              else
              {
                $.get(
                    link.attr('href'),
                    { justPicPos: 'pgmain' },
                    function(data){
                        var popData = $(data).find('.box:first');  // Gets the very first .box on the linked page.
                        popData.popup();
                        link.data('popupForm', popData); // store for later
                      }
                  );
              }
              return false;
            });              
              
              
              
              
              
              

              
              
              
              
              
              
              
              
              
              

    // fix the top position of a button within the scrolling window
    // - while making sure it nevers gets too close to the top of the document.
    // requires: x/resize
    var originalButton = $('a.upward'),
        winHeight = $(window).height();
        button = originalButton.clone()
                      .addClass('scripted')
                      .appendTo('body'),
        idealTopPos = winHeight - (button.outerHeight()+ (winHeight*.20)),
        updateButtonPosition = function (e) {
            if ( button.is(':visible') )
            {
              var newPos = Math.max( idealTopPos+$(window).scrollTop(), winHeight+100 );
              button.offset({ top: newPos });
            }
          },
        updateWinHeight = function (e) {
            var newHeight = $(window).height();
            if ( winHeight != newHeight )
            {
              if ( newHeight*2 < $(document).height() )
              {
                if ( button.is(':hidden') )
                {
                  button.show();
                }
                winHeight = newHeight;
                updateButtonPosition();
              }
              else
              {
                button.hide();
              }
            }
          };
    originalButton.addClass('hidden');
    updateWinHeight();
    updateButtonPosition();
    $(document)
        .bind('resize', updateWinHeight);
    $(window)
        .bind('scroll', updateButtonPosition);


// end    
        
  }
);



