// 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(
  'eutils',
  'fontsizer',
  'labelizor',
  'autovalidate',
  'easing-mini',
  'equalizeheights',
  'mailtoenabler',
  'listscroller',
  'x/bookmark',
  
  function(){

    var $ = jQuery,
        body = $('body').addClass('js-active'),

        texts = {
            is: {
                closeLabel:     'Loka',
                shareBtnLabel:  'Deila',
                fieldLabelHelp: 'Uppskriftalistinn fyrir neðan leitarreitinn, uppfærist sjálfkrafa um leið og byrjað er að slá inn leitarorð.',
                noneFoundMsg:   'Engar uppskriftir fundust með þessu leitarstreng'
              },
            en: {
                closeLabel:     'Close',
                shareBtnLabel:  'Share',
                fieldLabelHelp: 'The list below the search-field, will automatically update as you start typing.',
                noneFoundMsg:   'No recipies were found matching this search string'
              }
          };
    texts = texts[$.lang()] || texts.en;
    body.toggleClass('alt-browser-fix', $.browser.webkit || $.browser.opera);


    // frontpage dropbox animation
    var dbheights = [];
    $('body.home .dropbox')
        .each(function(i) {
            dbheights.push( $(this).find('ul').height() );
            $(this).find('ul').hide()
                .end()
                .bind('mouseenter', function(e) {
                    $(this)
                        .addClass('dbhover')
                        .find('ul')
                            .stop()
                            .css({ 'height' : 0 })
                            .animate({ 'height' : Math.max( 60, dbheights[i] ) }, 300, 'easeOut');
                  })
                  .bind('mouseleave', function(e) {
                    $(this)
                        .removeClass('dbhover')
                        .find('ul')
                            .stop()
                            .animate({ 'height' : 0 }, 300, 'easeOut');
                  })
          });

    //Align img vertically to .fadeout img.left
    $('.home .scroll img').each(function () {
      var fdimg = $('.fadeout .left'),
          scimg = $(this);
        if ( scimg.height() < fdimg.height() )
        {
          scmarg = Math.abs((fdimg.height() - scimg.height()) / 2);
          $(this).css('padding-top', scmarg);
        } else if ( scimg.height() > fdimg.height() )
        {
          scmarg = (fdimg.height() - scimg.height()) / 2;
          $(this).css('margin-top', scmarg);
        }
      });

    //Front page logo scroller
    $('.home .scroll')
        .listscroller({
            item :            '.item',
            animation:        'crossfade',
            controls:         'none',
            windowSize:       1,
            stepSize:         1,
            autoScrollDelay:  5000
        });


    if (!window.EPLICA_loggedin)
    {

      //collapsers
      $('.dropmenu .boxbody ul')
          .hide()
          .parent()
          .parent()
          .find('h2.boxhead a')
              .click(function(){
                  $(this).parent().parent().find('div.boxbody ul').slideToggle(300);
                  return false;
              });
      $('.tengd_grein .boxbody')
          .hide()
          .parent()
          .find('h4')
              .click(function(){
                  $(this).parent().parent().find('div.boxbody').slideToggle(300);
                  return false;
              })
      


      //add classes for anchor icons for filelypes
      $('.article, .articlelist')
          .find('a[href$=".pdf"], a[href$=".PDF"]')
              .addClass('pdf')
          .end()
          .find('a[href$=".doc"], a[href$=".DOC"], a[href$=".docx"], a[href$=".DOCX"]')
              .addClass('doc')
          .end()
          .find('a[href$=".xls"], a[href$=".XLS"], a[href$=".xlsx"], a[href$=".XLSX"]')
              .addClass('xls')
          ;



      $('.article a.videolink').Req(
          'q-videolinks.js',
          function() {
            $(this).videoLinks();
          }
        );



      //articlelist image wrapper
      $('.pgmain .articlelist img')
          .not('.research-project-list img')
          .each(function() {
            $(this).wrap('<div class="img-wrap-outer"><div class="img-wrap-inner"><span class="imgcropfix"></span></div></div>')
        });
      
      $(window).bind('load', function (e) {
          $('.pgmain .uppskriftir img')
              .each(function(){ 
                  $(this).bind('load readystatechange', function (e) {
                      $(this).css({ 'margin-top' : 40 - ($(this).height() / 2)  })
                    });
                  this.src += ''; //IE force readystate hack
                });
        });
      
      //disable anchors in quickbox headings
      $('.quickbox h3 a')
          .click(function() {
              return false;
          });
      
      // imgpopup
      $('.imgbox a img')
          .parent()
          .bind('click', function() {
              var imghref = $(this);
              $('div.pgwrap').append(
                  $('<div class="popup-wrapper" style="display:none;">' +
                      '<div class="popup-inner-wrapper">' +
                      '<div class="imgcontainer">' +
                        
                        '<img src="' + imghref.attr('href') + '" alt="" />' +
                        
                        '<div class="imgcontent">' +
                          '<div class="imgname">' + imghref.find('img').attr('title') + '</div>' +
                          '<div class="imgtext">' + imghref.find('img').attr('alt')  + '</div>' +
                        '</div>' +
                        
                        '<div class="act">' +
                          '<a class="close">' +
                            '<strong>' + texts.closeLabel + '</strong>' +
                          '</a>' +
                        '</div>' +
                        
                      '</div>' +
                      '</div>' +
                    '</div>')
                        .fadeIn(500)
                        .bind('click', function() {
                            $(this)
                                .fadeOut(500, function() {
                                    $(this).remove();
                                })
                        })
              );
              return false;
          });


      // research project article element manipulation
      $('.research-project .boxbody')
          .each(function(){
              var boxbody = $(this);

              boxbody.find('.framed')  // creates a set of all .framed elements
                  .prev('h2') // creates a set of all h2's preceding each .framed element
                      .andSelf() // creates a set of pairs of h2 + .framed 
                          .wrapAll('<div class="col2" />'); // wraps the resulting array in a div of class .col2

              boxbody.find('h1') // finds h1
                  .nextUntil('.project-dates, .buttons', true)  // creates set of elements after h1 but before .project-dates and .buttons
                      .not('.imagebox, .meta, .col2') // elements to exclude from the set 
                          .wrapAll('<div class="col1" />'); // wraps the resulting set in a div of class .col1

              //find img with rlogo class and append to rlogos and then append that to col2 -  a wee bit hackish.
              ('.rlogo')
                  .wrapAll('<div class="rlogos" />');
              $('.rlogos').appendTo('.col2');
            });



      //Homepage splash box cloner with text cropping of original content             
      var showText     = $('.splash p').text().split('.'),
          showTextZero = showText[0],
          showTextOne  = showText[1],
          showTextTwo  = showText[2];
      
      if (showText.length > 4) {
          var cloned = $('.splash').clone(),
             cropElm = $('<p>'+ showTextZero + '. ' + showTextOne + '. ' + showTextTwo + '.</p>');
        
           $('.splash p').hide();
            cropElm.appendTo('.splash');
            cloned.prependTo('.pgmain')
                       .hide()
                       .addClass('cloned')
                          .delegate('a.close', 'click', function (e) {
                                cloned
                                    .hide()
                                return false;
                          })
                        .append('<a href="#" class="close">' + texts.closeLabel + '</a>');

            $('.splash')
                .bind('mouseenter', function() {
                      setFN = setTimeout(function() {
                                       cloned.show()
                                            }, 500);
                })
                .bind('mouseleave', function() {
                      if (cloned.is(':visible')) {
                          setTimeout(function() {
                                       cloned.hide()
                                            }, 500);
                          }
                       else {clearTimeout(setFN)}
                      
                });
                
      };


    } // END if !window.EPLICA_loggedin

    
    var yearindex = $('.yearindex');
    if (yearindex.length)
    {
      var docLoc = document.location.toString(),
          date = new Date();

      var year = docLoc.match(/\/(\d{4})/);
      year = year && year[1] || date.getFullYear();
      
      var month = docLoc.match(/\/\d{4}\/(\d{2})/);
      month = month && parseInt(month[1], 10)-1;

      yearindex.find('h3 a').each(function () {
          if ($.trim($(this).text()) == year)
          {
            $(this).closest('li').addClass('current');
          }
        });

      if (month != null)
      {
        var months = 'janúar,febrúar,mars,apríl,maí,júní,júlí,ágúst,september,október,nóvember,desember'.split(',');
        yearindex.find('.current p a').log().each(function () {
            if ($.trim($(this).text()) == months[month])
            {
              $(this).addClass('current');
            }
          });
      }

      if ($.trim($('.pgmain .articlelist .boxhead').text()) == 'Fréttir')
      {
        $('.pgmain .articlelist .boxhead').hide();
      }
    }


    //flicker trick
    $('#noflickerCSS').remove();


    $('.buttons:has(.btnback, .prenta, .senda)')
        .each(function(){
            var buttons = $(this)
                              .append('<div class="share"><span class="sharetxt">'+ texts.shareBtnLabel +'</span><a class="facebook" href="http://www.facebook.com/sharer.php?u='+window.location+'" target="_blank">Facebook</a><a class="twitter" href="http://twitter.com/home?status='+window.location+'" target="_blank">twitter</a><a class="gbm" href="http://www.google.com/bookmarks/mark?op=edit&bkmk='+window.location+'" target="_blank">google bookmarks</a><a class="share" href="#">'+ texts.shareBtnLabel +'</a></div>'),
                bookmarks,
                bookmarksOpen;

            buttons.find('.share a.share')
                .bind('click', function (e) {
                    var clickedLink = this;
                    bookmarks = bookmarks || 
                                $('<div class="share-menu">')
                                    .insertAfter(clickedLink)
                                    .hide()
                                    .bookmark({
                                        sites:      ['yahoobm', 'stumbleupon', 'digg', 'reddit', 'delicious', 'spurl'],
                                        title:      $('h1:first').text() || $('.boxhead:first:is(h1, h2)').text(),
                                        compact:    false, // defaults to `true`
                                        icons:      Req.localPath + 'design/i/icons.png'
                                      });
                    bookmarksOpen ?
                        bookmarks.slideUp(250):   // close
                        bookmarks.slideDown(150); // open
                    bookmarksOpen = !bookmarksOpen;
                    $(this.parentNode).toggleClass('share-open', bookmarksOpen)
                    return false;
                  });
          });




    //file filter
    $('.articlelist-filter')
        .Req( Req.localPath+'js/filterfiles.js', function(){
            //this.quickFilterList();
          });


    //AJAX SIMPLE
    var ajaxContainer,
        setFN;
    $('.ajaxstaff')
        .delegate('td:not(.netfang) > a', 'mouseenter', function (e) {
            var popLink  = this;
            setFN = setTimeout(function() {
                ajaxContainer = $('<div class="ajax-container" />')
                    .appendTo( popLink )
                    .load( $(popLink).attr('href') +'?justPicPos=pgmain .persona .imgbox' )
              }, 100);    
          })
        .delegate('td:not(.netfang) > a', 'mouseleave', function() {
            ajaxContainer  &&  ajaxContainer.remove();
            setFN && clearTimeout(setFN);
            setFN == ajaxContainer == undefined;
          });


      $('#qstr, #s_email, #faeda').labelizor();
      $('.netfang').mailtoEnabler();
      $('form').autoValidate();
      $('.pagestyle').fontsizer();

  }
);
//init xfbml like button
FB.XFBML.parse();
