// 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',
  'mailtoenabler',
  'tabswitcher',
  'listscroller',
  'fontsizer',
  'autovalidate',
  'labelizor',
  'imgpop',
  'anchortags',
  'equalizeheights',
  'makepagestyles',
  'x/bookmark',
  'q-videolinks',

  function(){
    var $ = jQuery,
        body = $('body').addClass('js-active'),
        article = $('.article'),
        msie =   $.browser.msie   &&  parseInt($.browser.version,10)<9;

    $.makePageStyles({
        fontsizeBtns: false,
        userstyles:   true,
        appendTo:    '.pgfoot'
      });

    var texts = {
        is: {
            newWindow:        'Opnast í nýjum vafraglugga',
            fileText:         'skjal',
            backText:         'Til baka',
            printText:        'Prenta',
            shareText:        'Segja frá',
            emailTextText:    'Senda í pósti',
            emailSubjectText: ' ', //outlook encoding icelandic text incorrectly
            emailBodyText:    ' ',
            openText:         'Opna',
            closeText:        'Loka',
            gridview:         'Grid view',
            listview:         'List view'
          },
        en: {
            newWindow:        'Opens in new window',
            fileText:         'file',
            backText:         'Go back',
            printText:        'Print',
            shareText:        'Share / Bookmark',
            emailTextText:    'Send as e-mail',
            emailSubjectText: 'Interesting article on harpa.is',
            emailBodyText:    'I thought you might find this page interesting:\n\n{t}\n{u}',
            openText:         'Open',
            closeText:        'Close',
            gridview:         'Grid view',
            listview:         'List view'
          }
      };
    texts = texts[ $.lang() ]  ||  texts.en;



    if ( $('#pgnav').height() > 350 ) {
      $('#pgnav, .pgmain').equalizeHeights();
    }
    
    if (body.is('.twocol2'))
    {
      $('.pgmain, .pgextra1').equalizeHeights();
    }


    // labelize search input
    $('#qstr').labelizor();

    if (!window.EPLICA_loggedin)
    {
      if (article.length)
      {
        //zebra tables
        article.find('tbody tr:nth-child(2n)').addClass('odd');

        //popup in articles
        article.find('.imagebox a.img')
            .each(function() {
              var imgsrc = $(this).find('img').attr('src').replace(/\/[^\/]+\/([^\/]+)$/, '/popp/$1');
              $(this).attr('href', imgsrc)
            })
            .imgPopper({
                curtainColor : '#000000',
                curtainOpacity : '0.85',
                yOffset: 100
              });


        //enable video links
        article.find('a.videolink').videoLinks();


        //tag external urls
        var link, text, useappend, match, vidCn;
        article.find('a:not(.buyticket)')
            .anchorTags({
                usePatterns:  ['doc', 'pdf', 'xls']
              })
            .filter('.external, .file_pdf, .file_doc, .file_xls')
                .not(':has(img)')
                    .each(function() {
                        link = $(this);
                        text = '';
                        useappend = false;
                        match = this.className.match(/(^| )file_([a-z]+)( |$)/);
                        if ( match )
                        {
                          if  ( !link.find('span').length ) 
                          {
                            text = match[2].toUpperCase() +' '+ texts.fileText;
                          }
                        }
                        else if ( $(this).is('.external') )
                        {
                          text = texts.newWindow;
                          useappend = true;
                          vidCn = link.attr('href').match(/(youtube|vimeo|facebook|twitter)/);
                          if (vidCn && vidCn[1]) 
                          {
                            useappend = false;
                            $(this).addClass('external-' + vidCn[1]);
                          }
                        }
                        if (text)
                        {
                          link
                              .attr('target', '_blank')
                              .attr('title', (link.attr('title')||link.text()) +' ('+ text+')')
                              [useappend ? 'append' : 'prepend'](' <span class="icon">('+ text +')</span> ');
                        }
                      });


        //content collapsing
        article.find('.collapse-header').each(function(){
            var head = $(this),
                isOpen = false;
            head
                .nextUntil('h2, h3')
                .wrapAll('<div class="collapseouter" />').wrapAll('<div class="collapsebox" />')
                    .parent().parent()
                        .hide();
            head
                .addClass('collapse-active collapse-closed')
                .wrapInner('<a href="#" />')
                .find('a')
                    .append('<span class="icn">'+ texts.openText +'</span>')
                    .bind('click', function (e) {
                        head
                            .toggleClass('collapse-closed', isOpen)
                            .next().slideToggle('fast');
                        head
                            .find('span')
                                .text( isOpen ? texts.openText : texts.closeText );
                        
                        isOpen = !isOpen;
                        return false;
                      });
          });
      }

      $('.articlelist').find('h3 > a, h4').append('<span class="fadeout" />');


      //link companyintro image
      $('.companyintro').each(function () {
          var link = $(this).find('.summary a').detach().attr('href');
          $(this).find('.imagebox img').wrap('<a href="'+ link +'" />')
        });


      if (msie)
      {
        $('.soldout').each(function () {
            $(this).find('.img').append('<span class="after" />');
          });
      }

    } // end loggedin


    if (body.is('.home')) 
    {
      if (!body.is('.userstyles-on')) {
        $('.fp-banbox')
            .find('.item')
                .each(function () {
                    $(this).find('h3, h4, .summary').wrapAll('<div class="plate" />')
                  })
            .end()
            .filter(function() { return $(this).find('.item').length > 1 })
            .listscroller({ 
                  item       : '.item',
                  paging     : true,
                  statusPager: false,
                  jumpPager: true,
                  animation  : 'crossfade',
                  autoScrollDelay  : 6000,
                  windowSize : 1,
                  stepSize   : 1/*,
                  labelNext  : nextText,
                  labelPrev  : prevText,
                  statusLabel  : pageText,
                  titleNext  : nextTitle,
                  titlePrev  : prevTitle*/
              });

        $('.fp-eventlist')
            .find('.summary').bind('click', function (e) {
                window.location = $(this).find('.more a:not(.buyticket)').attr('href');
              })
            .end()
            .filter(function() { return $(this).find('.item').length > 4 })
            .listscroller({ 
                  item       : '.item',
                  paging     : true,
                  statusPager: false,
                  jumpPager  : false,
                  aspect     : 'horizontal',
                  animation  : 'carousel',
                  autoScrollDelay  : 7000,
                  windowSize : 4,
                  stepSize   : 1,
                  wrap       : 'loop'/*,
                  labelNext  : nextText,
                  labelPrev  : prevText,
                  statusLabel  : pageText,
                  titleNext  : nextTitle,
                  titlePrev  : prevTitle*/
              });

        $('.purple .tab').makeTabbox()
        $('.purple .tabs')
            .find('a')
                .bind('click', function (e) {
                    //funky stuff (needs to run before tabswitcher to get corrent event order)
                    if ( $(this).parent().is('.current') )
                    {
                      var title = $(this).attr('title');
                      if (title == 'Viðburðir') { window.location = "/midasala/framundan/" }
                      else if (title == 'Ráðstefnur') { window.location = "/adstadan/radstefnur/radstefnuadstada/" }
                      else if (title == 'Box Office') { window.location = "/events/upcoming-events/" }
                      else if (title == 'Conferences') { window.location = "/facilities/conferences/conference-facilities/" }
                    }
                  })
            .end()
            .tabSwitcher({ setFragment: false });
        $('.pgmain .tabpane')
            .wrapAll('<div class="tabcol" />')
            .makeTabbox()
                .tabSwitcher({ setFragment: false })
                .find('a')
                    .bind('click', function (e) {
                        $.equalizeHeights();
                      });
        $('.tabcol, .blog').equalizeHeights();
      } 
      else 
      {
        $('.purple').remove();
      }

    }
    else if (body.is('.milli')) 
    {
      if (!body.is('.userstyles-on')) 
      {
        $('.imgrot')
            .find('.item')
                .each(function () {
                    $(this).find('h3, .summary').wrapAll('<div class="plate" />')
                  })
            .end()
            .filter(function() { return $(this).find('.item').length > 1 })
            .listscroller({ 
                  item       : '.item',
                  paging     : true,
                  statusPager: false,
                  jumpPager  : false,
                  animation  : 'crossfade',
                  autoScrollDelay  : 6000,
                  windowSize : 1,
                  stepSize   : 1/*,
                  labelNext  : nextText,
                  labelPrev  : prevText,
                  statusLabel  : pageText,
                  titleNext  : nextTitle,
                  titlePrev  : prevTitle*/
              });

        //s-grid stuff
        var sitms = $('.s-grid .item');
        for (var i=0, l=sitms.length; i<l; i+=2)
        {
          sitms.eq(i).css('clear', 'left').end().slice(i,i+2).equalizeHeights();
        }
        sitms.bind('click', function (e) {
            window.location = $(this).find('a:first').attr('href');
          });

      }
    }
    else 
    { // !home !milli

      if (body.is('.blogtempl'))
      {
        var imagelist = article.find('.imagebox li');
        if (imagelist.length > 1)
        {
          var galleryCont = $('<div class="bloggallery"><ul></ul></div>')
          galleryCont.append( imagelist.slice(1) )
        }
      }
      
      $('.pgmain .tabpane').makeTabbox({ boxTempl: '<div class="tab-box-pgm"><ul class="tabs" /></div>' }).tabSwitcher({ setFragment: false });
        
      //buttons bar
      var buttons = $('<div class="buttons">'+
                        '<a class="btnback" href="javascript:history.back();">'+ texts.backText +'</a>'+
                        '<a class="prenta" href="javascript:window.print();">'+ texts.printText +'</a>'+
                      '</div>'),
          bookmarksOpen,
          shareHover = false,
          shareBtn = $('<span class="share"><a href="#">'+ texts.shareText +'</a></span>'),
          bookmarks = $('<div class="share-menu" />').bookmark({
                                                  title:   $('h1:first').text(),
                                                  addEmail: true,
                                                  emailText: texts.emailTextText,
                                                  emailSubject: texts.emailSubjectText,
                                                  emailBody: texts.emailBodyText + '\n' + document.location,
                                                  sites:   ['facebook', 'twitter', 'google', 'yahoobm', 'stumbleupon', 'digg', 'reddit', 'delicious'],
                                                  compact: false, // defaults to `true`
                                                  icons:   '/skin/basic/design/i/icons.png'
                                                });

      bookmarks.hide().appendTo(shareBtn);

      shareBtn
          .find('> a')
              .bind('click', function (e) {
                  bookmarksOpen ?
                      bookmarks.slideUp(200):
                      bookmarks.slideDown(300);
                  bookmarksOpen = !bookmarksOpen;
                  shareBtn.toggleClass('share-open', bookmarksOpen);
                  return false;
                })
          .end()
          .bind('mouseleave focusout', function(e){
              shareHover = false;
              setTimeout(function(){
                  if(!shareHover) {
                    bookmarks.slideUp(200);
                    bookmarksOpen = false;
                    shareBtn.removeClass('share-open');
                  }
                }, 1000);
            })
          .bind('mouseenter focusin', function(e){
              shareHover = true;
            });

      buttons.prepend(shareBtn).appendTo('.pgmain > .wrap');


      $('.poplink a')
          .imgPopper({
              curtainColor : '#000000',
              curtainOpacity : '0.85',
              yOffset: 100
            });

      if ($('.imagebox-fullview .imagelist li').length > 1)
      {
        $('.imagebox-fullview .imagelist').innerfade({
          animationtype: 'fade',
          speed: 1500,
          timeout: 5000,
          type: 'sequence',
          containerheight: '343px'
        });
      }
    }
    
    
    var footer = $('.footer .boxbody');
    if (!window.EPLICA_loggedin)
    {
      footer
          .find('#opnunartimi')
              .hide().addClass('opnun-active')
              .append('<a class="close" href="#">'+ texts.closeText +'</a>')
              .prepend('<a href="#" class="focustarget">.</a>')
              .bind('click', function(e) {e.stopPropagation()});

      $('.pgfoot .subscr')
          .hide()
          .addClass('subscr-active')
          .append('<a class="close" href="#">'+ texts.closeText +'</a>')
          .prepend('<a href="#" class="focustarget">.</a>')
          .appendTo(footer.find('.f-informed'))
          .find('.fi_txt input')
              .labelizor()
          .end()
          .bind('click', function(e) {e.stopPropagation()});

      footer.find('.hours a, .nl-link a').bind('click', function (e) {
          $( $(this).attr('href') )
              .data('link', $(this))
              .fadeIn('fast')
              .find('.focustarget')
                  .focus();
          return false;
        });

      footer.find('.close').bind('click', function (e) {
          $(this).parent().fadeOut('fast').data('link').focus();
          return false;
        });

      body.bind('click', function (e) {
          footer.find('.close:visible').trigger('click');
        });
      $(window).bind('keyup', function (e) {
          if (e.which == 27)
          {
            body.trigger('click');
          }
        });
        /*
      footer.find('.subscr form').bind('submit', function (e) {
          var form = $(this);
          $.post(
              form.attr('action'),
              form.serialize(),
              function(responce) {
                var resp = $(responce).find('.subscr .boxbody').html();
                form.replaceWith('<div class="boxbody">'+ resp +'</div>');
              }
            );
          return false;
        });
        */
    }


    //view toggler
    var gridview = $('.gridview, .listview'),
        views = $('<div class="viewchanger"><ul>'+
                    '<li class="gridbtn active"><a href="#" title="'+ texts.gridview +'">'+ texts.gridview +'</a></li>'+
                    '<li class="listbtn"><a href="#" title="'+ texts.listview +'">'+ texts.listview +'</a></li>'+
                  '</ul></div>');
    if ($.cookie('viewtype') == 'list') {
      gridview.removeClass('gridview').addClass('listview');
      views.find('li').removeClass('active').filter('.listbtn').addClass('active');
    }
    gridview.addClass('views-active');
    views.find('.gridbtn a').bind('click', function (e) {
        $.cookie('viewtype', 'grid', { path:'/', expires:365 });
        gridview.removeClass('listview').addClass('gridview');
        views.find('li').removeClass('active').filter('.gridbtn').addClass('active');
      });
    views.find('.listbtn a').bind('click', function (e) {
        $.cookie('viewtype', 'list', { path:'/', expires:365 });
        gridview.removeClass('gridview').addClass('listview');
        views.find('li').removeClass('active').filter('.listbtn').addClass('active');
      });
    gridview.filter(':first').before(views);


    //equalize gridview items
    $('.gridview').each(function () {
        var gridItms = $(this).find('.item'),
            cols = body.is('.fullwidth') ? 4 : 3;
        for (var i=0, l=gridItms.length; i<l; i+=cols)
        {
          gridItms.eq(i).css('clear', 'left').end().slice(i,i+cols).equalizeHeights();
        }
      });

    
    $('.box-left').each(function () {
        $(this).nextUntil('.box-left').andSelf().filter('.box-1_1, .box-1_2, .box-1_3, .box-1_4').equalizeHeights();
      });

    //init calendar pager
    $('.monthlist').Req(
        '/bitar/common/calendar/calendarPager.js',
        '/skin/basic/js/prettyloader.js',
        function(){
            this.eplicaCalendarLoader();
            $.prettyLoader();
        });

    //init employee scripts
    $('div.people').Req('/bitar/common/personas/loadEmployee.js', function(){ this.eplicaEmployeeLoader({emailSelector:'.netfang span'}); });

    //sitemap collapser
    $('.sitemap').Req('treecollapse', function() { 
        $(this).treeCollapse({ 
            branch: 'li:has(ul)', 
            doTogglers: 1, 
            toggler: '> a.expand',
            startOpen: 'ul.level1 > li:has(ul)'
          }); 
        });

    if (!window.EPLICA_loggedin)
    {
      //activate mailto links
      $('.people .netfang, .persona .netfang span, .article .netfang').mailtoEnabler();
    }

    //init gallery script
    $('.gallery .boxbody ul.thumbsview').Req(
        'jsgallery-1.0.js',
        function() {
            $(this).jsgallery({ 
                curtColor: '#ffffff',
                smallImgSize: 'mpreview',
                medImgSize: 'mlarge',
                largeImgSize: 'popp',
                useImgText: true
              }) 
        }
      );


    //default
    $('#noflickerCSS').remove();
    $('.pagestyle').fontsizer();
    $('form').autoValidate();

    //loading body class scripts 
    Req.loadPageScripts();

    //recalc box heights
    setTimeout(function(){
        $.equalizeHeights();
      }, 500);

  }
);
// **** /jqreq *****

