// encoding: utf-8
/*@cc_on/*@if(@_jscript_version<5.7)try{document.execCommand('BackgroundImageCache',0,1)}catch(e){}/*@end@*/

Req(
  'eutils', // focusin/focusout events etc.
  'fontsizer', 
  'autovalidate', 
  'labelizor', 
  'equalizeheights', 
  'x/ui-core', 
  'x/ui-fxcore', 
  'x/ui-accordion', 
  'x/easing', 
  'easing-mini', 
  'x/ifixpng', 
  'x/innerfade', 
  'tabswitcher', 
  'listscroller', 
  'imgpop',
  'q-videoplayer',

  function(){
    var $ = jQuery,
        isIS = $('html').attr('lang') == 'is',
        body = $('body').addClass('js-active'),
        mobile = $(document).width() < 750;

    //labelize
    $('#qstr, .pgextra4 .fi_txt input').labelizor();

    $('#noflickerCSS').remove();

    if (!window.EPLICA_loggedin)
    {

      $('.article').each(function(){
          var article = $(this);

          //zebra
          $('table tr:even', article).addClass('alt');

          //create tabs
          var tabarticle = $('.tab:first', article).parent(),
              tabsBoxes = tabarticle.find('div.tab'),
              nextTabText = isIS ? 'Næsti flipi' : 'Next tab';
          tabarticle
              .addClass('tabsactive')
              .find('.tab:first')
                  .before('<ul class="tabs"></ul>');
          tabsBoxes.each(function(i) {
              $(this)
                  .attr('id','tab'+ i +'')
                  .append('<a class="nexttab" href="#tab' + ((i+1) % tabsBoxes.length) +'">' + nextTabText + '</a>');
              lastTab = (i == tabsBoxes.length-1) ? ' last' : '';
              tabarticle
                  .find('ul.tabs')
                      .append('<li class="t' + i + '' + lastTab + '"><a href="#tab'+ i +'">' + $(this).find('h3:first').html() + '</a></li>');
            });


          //insert quotes into blockquote
          $('blockquote.quotes', article)
            .prepend('<span class="quotes-top"></span>')
            .append('<span class="quotes-bottom"></span>');


          //popup in articles
            
          var articleimages = $('.imagebox a.img', article);
            
          articleimages
            .each(function() {
              var imgsrc = $(this).find('img').attr('src').replace(/\/[^\/]+\/([^\/]+)$/, '/large/$1');
              $(this).attr('href', imgsrc)
            });
            
          if(!mobile) {
            
            var zoomtext = isIS ? 'Smelltu á myndina til að stækka' : 'Click image to zoom',
                moreImgs = isIS ? 'Smelltu á myndina til að sjá fleiri' : 'Click image to zoom and see more';
            
            articleimages
                .imgPopper({
                    curtainColor : '#ffffff',
                    curtainOpacity : '0.75',
                    yOffset: 15
                  })
                .eq(0).attr('title', zoomtext)
                .end()
                .eq(1).closest('div').prepend('<span class="zoomnote">'+ moreImgs +'</span>');
          }

          article.find('a.videolink').Req(
              'q-videolinks',
              function() {
                $(this).videoLinks();
              }
            );

        });

        
          
      // mediagallery
        
      $('.mediagallery .boxbody')
          .each(function(){
              
              $(this).find('.pgr').appendTo($(this));
            
              $(this)
                .find('li .summary')
                    .each(function(){
                
                        $(this)
                            .hide()
                            .prev()
                            .append('<span class="summary">' + $(this).find('.count').text() + '</span>');
                        
                  
                      });
            
            });


      //english event date fix
      var enEventDate = body.filter('.en').find('.pgmain .event .aboutevent h3:first'),
          enEventDateText = enEventDate.text().replace('.','');
      enEventDate.addClass('date').html( enEventDateText );


      //Tab switcher
      $('ul.tabs').tabSwitcher({ setFragment: false });


      // Add "send to facebook" link to articles
      var fbBtnTxt = isIS ? 'Senda á Facebook' : 'Send to Facebook';
      $('p.buttons')
          .append(
              $('<a class="btnfacebook">' + fbBtnTxt + '</a>')
                .bind('click', function()  {
                    window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(document.location.href)+'&t='+encodeURIComponent($('h1').text()),'sharer','toolbar=0,status=0,width=626,height=436');
                    return false;
                  })
          );


      //IE6 li hover effect
      if($.browser.msie && $.browser.version < 7) {
          $('div.mnav li')
              .bind('mouseenter', function(e){ $(this).addClass('hover') })
              .bind('mouseleave', function(e){ $(this).removeClass('hover') });
          $('ul.tabs li')
              .bind('mouseenter', function(e){ $(this).addClass('hover') })
              .bind('mouseleave', function(e){ $(this).removeClass('hover') });
        $('img').ifixpng();
      }


      //heightfixes
      
      if(!mobile) {
      
        body.filter('.twocol, .threecol').find('.pgextra2 > .wrap, .pgmain > .wrap').equalizeHeights();
        $('div.pgextra3 .box .boxbody').equalizeHeights();
        $('div.pastevents .item').equalizeHeights();
        $('div.sl-2d .item').each(function(i){ if (i%2 == 0) { this.className += ' sl-left'; } }).equalizeHeights();
        $('div.sl-3d .item').each(function(i){ if (i%3 == 0) { this.className += ' sl-left'; } }).equalizeHeights();
        $('div.sl-4d .item').each(function(i){ if (i%4 == 0) { this.className += ' sl-left'; } }).equalizeHeights();
        $('div.exevents .item:not(.firstitem)').equalizeHeights();
        body.filter('.home').find('div.pgextra4 .box').equalizeHeights();
        
      }

      // initialize the accordion widget (on the front page).
          /*
      $('div.accordion')
              .find('div.box h2.boxhead')
                  .wrapInner('<a href="#"></a>')
                  .find('a')
                      .bind('click', function(e){ e.preventDefault(); })
                  .end()
              .end()
              .find('.boxbody')
                  .wrapInner('<div class="accwrapper"></div>')
              .end()
              .accordion({
                  header         : 'h2.boxhead',
                  selectedClass  : 'boxhead-open',
                  animation      : 'easeInOut'
                });
                */
      if ($.fn.videoList)
      {
        //Videogallery
        $('.videolist').videoList({
            thumbnails: true,
            setfragment: true
          });
      }

    }; //end isloggedin


    body.filter('.home').each(function(){
        var home = $(this);

       //init newsticker
       $('div.newsticker div.boxbody ul', home)
          .innerfade({
              animationtype: 'fade',
              speed: 1000,
              timeout: 4000,
              type: 'random',
              containerheight: '25px'
            });


        //crossfader for frontpage articles
        var fpShowitem = $('div.showitem div.boxbody', home);
        if (fpShowitem.length)
        {
          fpShowitem
              .listscroller({ 
                        item       : '.item',
                        paging     : true,
                        statusPager: false,
                        jumpPager: true,
                        animation  : 'crossfade',
                        autoScrollDelay  : 8000,
                        windowSize : 1,
                        stepSize   : 1
                    })
              .find('span.date')
                  .each(function() {
                      var splitDate = $(this).html().split(' ');
                      $(this).html('<b>' + splitDate[0] + '</b> ' + splitDate[1]);
                    })
              .end()
              .find('div.summary')
                  .each(function() {
                      var summary = $.trim( $(this).text() ).replace(/\s+/g, ' ');
                      if (summary.length > 165) {
                        $(this).html(summary.substr(0,165) + '... ');
                      };
                    });
        } // end crossfader


       //frontpage imagelist crossfader
       $('.imglist .item', home)
          .each(function() {
              $(this).find('> *:not(.img)').wrapAll('<div class="imgcontent" />');
            })
          .parent()
          .innerfade({
              animationtype: 'fade',
              speed: 1000,
              timeout: 4000,
              type: 'random',
              containerheight: '241px'
            });


        // helper function that trims a html doc for use as jquery object
        $.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 $.trim( r ) || "";
        };


        // postlisti ajax forms
        $('.subscr form', home).submit(function() {
            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"><div class="accwrapper">' + newDoc + '</div></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;
          });

          //old imgbanner fadein function
          $('.imgbanner .imgcontent', home).show(700, 'easeOut');

      }); // end body.home



    //hover and click effect on pastevents and showlists
    $('.pastevents .item, .showlist .item')
        .bind('mouseenter', function(e){
          $(this)
              .addClass('hover')
              .stop()
              .animate({
                    borderLeftColor    : '#24BBDB', 
                    borderRightColor   : '#24BBDB',
                    borderTopColor     : '#24BBDB',
                    borderBottomColor  : '#24BBDB'
                }, 200)
        })
        .bind('mouseleave', function(e){
            $(this)
                .removeClass('hover')
                .stop()
                .animate({
                    borderLeftColor    : '#dfdfdf', 
                    borderRightColor   : '#dfdfdf',
                    borderTopColor     : '#dfdfdf',
                    borderBottomColor  : '#dfdfdf'
                }, 300)
          });


      //Use pdf link instead of h3 link
      $('.pastevents .item')
          .bind('click', function() {
          $(this).find('div.summary a:not([href$=".pdf"])')[0] ? window.location=$(this).find('div.summary a:not([href$=".pdf"])').attr('href') : window.location=$(this).find('div.summary a[href$=".pdf"]').attr('href'); 
              return false;
          });


      $('.sl-3d .item, .sl-4d .item')
          .find('.date')
              .hide()
              .each(function(){
                  var date = $(this).html().replace('.', '').split(' ');
                  $(this).html('<span class="d">' + date[0] + '</span><span class="m">' + date[1] + '</span>')
                })
                .end()
          .bind('mouseenter', function(e){
              $(this)
                  .find('span.date')
                      .stop()
                      .css({ opacity : 1 })
                      .fadeIn(150)
          })
          .bind('mouseleave', function(e){
              $(this)
                  .find('span.date')
                      .stop()
                      .fadeOut(200);
          })
          .find('img')
              .bind('click', function() {
                  window.location=$(this).parent().parent().find('h3 a').attr('href'); return false;
              });

      //wrap span around showlist images, add "Free" text into empty price fields in showlist, and remove undefined dates
      var freeText = isIS ? 'Frítt' : 'Free';
      $('.showlist')
          /*
          .find('div.btnbar li.buyticket')
              .each(function() {
                  if ( $(this).find('a').length == 0 ) {
                    $(this).addClass('free').append('<a>' + freeText + '</a>')
                  }
                })
          .end()
          */
          .find('h3 span.meta')
              .each(function() {
                  if ( $(this).find('.date .m').text() == 'undefined' ) {
                      $(this).remove();
                  }
                });

      //nasty ++ bizzare hack for empty events == evil! - plz remove asap
      var event = $('.event');
      if( event.find('.aboutevent h3.date').html() == 'Event' || !event.find('.aboutevent .dates ul').length ) {
        event.find('.aboutevent .dates, .aboutevent p.ebtns').remove();
        event.find('hr.split').remove();
      }


    // wrapper and title injection for exevents

    var exevents = $('div.exevents');
    if(exevents[0]) {
      var eventYear = exevents.find('.boxhead').html().split(' ');
      exevents.find('.boxbody')
          .find('.item:not(.firstitem)')
              .wrapAll('<div class="exeventwrap" />')
              .parent()
              .prepend('<h2 class="extratitle">Viðburðir ' + eventYear[eventYear.length-1] +'</h2>');
    
    }; //end if


    $('table.calendar td')
        .bind('mouseenter focusin',  function (e) {
            var _this = $(this);
            clearTimeout(_this.data('focustimeout'))
            _this.addClass('active')
          })
        .bind('mouseleave focusout', function (e) {
            var _this = $(this);
            _this.data('focustimeout', setTimeout(function(){
                _this.removeClass('active')
              }, 10) )
          });


    // mnav en current fix
    var thisURL = document.location.toString().split('/');
    if(thisURL[thisURL.length-1] == 'en')
    {
      $('.mnav li').eq(0).addClass('current');
    }

    //sitemap collapser
    $('div.sitemap').Req('treecollapse', function() { 
        $(this).treeCollapse({ 
            branch: 'li:has(ul)', 
            doTogglers: 1, 
            toggler: '> a.expand',
            startOpen: 'ul.level1 > li:has(ul)'
          }); 
        });


    // validate all forms
    $('form').autoValidate();
    $('.pagestyle').fontsizer();
        
    


  }
);
