// 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', 
  function(){
    var $ = jQuery;
    
    //labelize
    $('#qstr, div.pgextra4 div.fi_txt input').labelizor();
    
    $('#noflickerCSS').remove();
    $('body').addClass('js-active'); //IE kick
    
    if (!window.EPLICA_loggedin)
    {
      
      //create tabs
      var tabarticle = $('div.article div.tab:first').parent(),
          tabsBoxes = tabarticle.find('div.tab'),
          nextTabText = ($('html').attr('lang') == 'is') ? 'Næsti flipi' : 'Next tab';
      tabarticle
          .addClass('tabsactive')
          .find('div.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>');
        });
        
      
      //english event date fix
      var enEventDate = $('body.en div.pgmain div.event div.aboutevent h3:first'),
          enEventDateText = enEventDate.text().replace('.','');
      enEventDate.addClass('date').html( enEventDateText );
        
      //Tab switcher
      $('ul.tabs').tabSwitcher();
      
      //zebra
      $('div.article table tr:even').addClass('alt');
      
      // Add "send to facebook" link to articles
      var fbBtnTxt = $('body').hasClass('en') ? 'Send to Facebook' : 'Senda á 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();
      }


     //init newsticker
     $('div.home div.newsticker div.boxbody ul')
        .innerfade({
            animationtype: 'fade',
            speed: 1000,
            timeout: 4000,
            type: 'random',
            containerheight: '25px'
          })
          
      
      //insert quotes into blockquote
      $('div.article blockquote.quotes')
        .prepend('<span class="quotes-top"></span>')
        .append('<span class="quotes-bottom"></span>');
      
      //heightfixes
      $('body.twocol div.pgextra2 div.wrap, body.twocol div.pgmain div.wrap, body.threecol div.pgextra2 div.wrap, body.threecol div.pgmain div.wrap').equalizeHeights();
      $('div.pgextra3 div.box div.boxbody').equalizeHeights();
      $('div.pastevents div.item').equalizeHeights();
      $('div.sl-2d div.item').equalizeHeights();
      $('div.sl-3d div.item').equalizeHeights();
      $('div.sl-4d div.item').equalizeHeights();
      $('div.exevents div.item:not(.firstitem)').equalizeHeights();
      $('body.home div.pgextra4 div.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'
                });
      
      
      
    }; //end isloggedin
    
    //crossfader for frontpage articles
    var fpShowitem = $('body.home div.showitem');
     if (fpShowitem.length)
     {
       $('div.boxbody', fpShowitem)
          .innerfade({
              animationtype: 'fade',
              speed: 1000,
              timeout: 8000,
              type: 'random',
              containerheight: '241px'
            })
            .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) + '... ');
                    };

                  });
    }
  
   //frontpage imagelist crossfader
   $('body.home div.imglist div.item')
      .each(function() {
          $(this).find('> *:not(.img)').wrapAll('<div class="imgcontent" />');
        })
      .parent()
      .innerfade({
          animationtype: 'fade',
          speed: 1000,
          timeout: 4000,
          type: 'random',
          containerheight: '241px'
        })


    //hover and click effect on pastevents and showlists
    $('div.pastevents div.item, div.showlist div.item')
        .bind('mouseenter', function(e){
          $(this)
              .addClass('hover')
              .stop()
              .animate({
                    borderLeftColor    : '#FF9900', 
                    borderRightColor   : '#FF9900',
                    borderTopColor     : '#FF9900',
                    borderBottomColor  : '#FF9900'
                }, 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
      $('div.pastevents div.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;
          });
          
      $('div.sl-3d div.item, div.sl-4d div.item')
          .find('span.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 = ( $('html').attr('lang') == 'en' || $('body.en').length ) ? 'Free' : 'Frítt';
      $('div.showlist')
          .find('div.item img')
              .filter(function(){ return !$(this.parntNode).is('.img'); })
                  .wrap('<span class="img"></span>')
              .end()
          .end()
          /*
          .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('span.date span.m').text() == 'undefined' ) {
                      $(this).remove();
                  }
                });
      
      //nasty ++ bizzare hack for empty events == evil! - plz remove asap
      if( $('div.event div.aboutevent h3.date').html() == 'Event' || !$('div.event div.aboutevent div.dates ul').length ) {
        $('div.event div.aboutevent div.dates').remove();
        $('div.event div.aboutevent p.ebtns').remove();
        $('div.event hr.split').remove();
      }
          
    
    // wrapper and title injection for exevents
    if($('div.exevents')[0]) {
      var eventYear = $('div.exevents h2.boxhead').html().split(' ');
      $('div.exevents div.boxbody')
          .find('div.item:not(.firstitem)')
              .wrapAll('<div class="exeventwrap" />')
              .parent()
              .prepend('<h2 class="extratitle">Viðburðir ' + eventYear[eventYear.length-1] +'</h2>');
    
    }; //end if
    
    
    // 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 ) || "";
    };


    if ($('body.home').length)
    {

      
      $('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) )
            });

      /* *** postlisti ajax forms *** */
      $('div.subscr form').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
      $('body.home .imgbanner .imgcontent').show(700, 'easeOut');

    }

    
    // mnav en current fix
    var thisURL = document.location.toString().split('/');
    
    if(thisURL[thisURL.length-1] == 'en')
    {
      $('.mnav li').eq(0).addClass('current');
    }


    // validate all forms
    $('form').autoValidate();
    $('div.pagestyle').fontsizer();
    

  }
);