// 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',
  'labelizor',
  'imgpop',
  'easing-mini',
  'equalizeheights',
  'mailtoenabler',
  'anchortags',
  'listscroller',

  function(){
    var $ = jQuery;

    // labelize search input
    $('#qstr').labelizor();

    if (!window.EPLICA_loggedin)
    {

      // pngfix for IE6
      if ($.browser.msie && $.browser.version < 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
            });
            

      //Article collapser
      var collapsearticle = $('.collapse');
      if ( collapsearticle.length) {
        $('h4', collapsearticle).each(function() {
            var heading = $(this);
            heading.wrapInner('<a href="#" />');
            heading.add( heading.nextUntil('h2, h4') ).wrapAll('<div class="collapsebox" />');
          });
        $('.collapsebox', collapsearticle)
            .each(function() {
                var collapsebox = $(this);
                collapsebox.find('> *:not(h4)').wrapAll('<div class="collapsecontent" />').parent().hide();
                collapsebox
                    .find('h4 a').bind('click', function() {
                        collapsebox.find('.collapsecontent').slideToggle(100);
                        collapsebox.toggleClass('collapse-open');
                        return false;
                      });
              });
      }
      
      //Grab related files list at end of article pattern, wrap it, and prepend it
      $('.pgmain .relatedfileslist')
          .each(function() {
              $(this)
                  .insertBefore('.pgmain .article .boxbody p:eq(0)')
                  .wrap('<div class="relatedfiles" />')
                  .before('<h2>Fylgiskjöl</h2>')
                  .after('<span class="deco"></span>');
            });
            
            
    //Anchortags
    $('.relatedfileslist a')
          .anchorTags({
              usePatterns:  ['doc', 'pdf', 'xls', 'audio']
            })
          .filter('a.external, a.file_pdf, a.file_doc, a.file_xls, a.file_audio')
              .each(function() {
                  var match = $(this)[0].className.match(/(^| )file_([a-z]+)( |$)/);
                  //var action = $(this).closest('.pgmain').length ? 'append' : 'prepend';
                  if ( match ) 
                  {
                    var text = match[2];
                    //$(this).attr('title', text+' skjal')[action](' <span class="icon">('+ text +')</span>');
                      $(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)[action](' <span class="icon">('+ externalText +')</span>');
                    $(this).attr('title', externalText).append(' <span class="icon">('+ externalText +')</span>');
                  }
                });
            
            
      //Listscroller
      //Requires that eutils-1-0.js also be present
        $('div.slidebox > .boxbody:has(.item)')
          .find('h3')
              .append('<a class="focustarget" href="#">.</a>')  // For accessibility
          .end()
          .listscroller({
              item: '.item',
              paging: true,
              windowSize: 1,
              stepSize: 1,
              autoScrollDelay: 7000,
              animation: 'crossfade',
              jumpLabel: 'Jump ',
              titleNext: 'Next',
              labelNext: 'Next',
              titlePrev: 'Previous',
              labelPrev: 'Prev',
              statusLabel: 'Status: '
            }); 
            
      //Making entire .item divs clickable 
      $('div.articlelist.multi .item').mouseover(function() { //Leveraging hover state for IE
            $(this).addClass('hovered');
              }).
          mouseout(function() {
            $(this).removeClass('hovered');
              });   
              
      $('div.articlelist.multi .item').click(function() {
            window.location = $(this).find('a').attr('href');
         });

            

    } // end not loggedin

    //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();
        
    // equalizeheights
    $('div.pgmain > div.wrap, div.pgextra2 > div.wrap').equalizeHeights();
    $('div.pgfoot .articlelist, div.pgfoot div.qnav').equalizeHeights();
    $('.home div.pgmain .articlelist .item').equalizeHeights();
    var boxes = $('.twocol .articlelist .item');
      for (var i=0, l=boxes.length; i<l; i+=2)
      {
        boxes.slice(i,i+2).equalizeHeights();
      }
     
    //Remove empty thead cells
    $('thead tr').each(function () {
        if ($.trim( $(this).text()) == "")
        {
          $(this).remove();
        }
      });      

    //Employee ajax loader        
    $('div.people ').Req('/bitar/common/personas/loadEmployee.js', function(){ this.eplicaEmployeeLoader(); });
    //$('div.people ').Req('http://www.samband.is/bitar/common/personas/loadEmployee.js', function(){ this.eplicaEmployeeLoader(); });
    
    $('.netfang').mailtoEnabler();
                
    //Mnav hover and current effect
          var mnav  = $('.mnav'),
              mnavCurr = mnav.find('li.parent, li.current'),
              overlay = $('<div class="overlay" />').appendTo( mnav.find('.boxbody') ),
              overlayOffset = overlay.width() / 2,

              navAnim = function (e, initial) {
                  var hoverElm = e.type=='mouseenter' ?
                                    $(this):
                                    mnavCurr,
                      speed = initial || overlay.is(':hidden') ?
                                  0:
                              e.type=='mouseenter' ?
                                  500:
                                  200;
                  if ( hoverElm[0] )
                  {
                    var offset = (hoverElm.width() / 2) - overlayOffset,
                        elmLeftPos = hoverElm.position().left,
                        tartgetPos = Math.round(elmLeftPos + offset ); 
                    overlay
                        .stop(true)
                        .css({  // like .show() - except better(tm)!
                            display: '',
                            opacity: ''
                          })
                        .animate(
                            { 'left': tartgetPos },
                            speed,
                            'easeOut'
                          );
                  }
                  else // this only occurs when !entering (i.e. there's no mnavCurr)
                  {
                    overlay
                        .stop()
                        .fadeOut(400);
                  }
                };

          overlay
              .hide();
          mnav.find('li')
              .bind('mouseenter mouseleave', navAnim);
          if ( mnavCurr[0] )
          {
            mnavCurr.trigger( 'mouseenter', true );  // first run
          }
/** /
      TODO: turn the above code into a neato reusable jQuery plugin!

      $('.mnav').slidingHover({
            overlayWidth: [fixed|dynamic]
            inspeed:  800,
            outspeed: 200,
            settings...
          });
/**/

  }
);
// **** /jqreq *****

