// encoding: utf-8
/*@cc_on/*@if(@_jscript_version<5.7)try{document.execCommand('BackgroundImageCache',0,1)}catch(e){}/*@end@*/
Req.localPath = /https?:/.test(document.location) ? '/skin/basic/' : './../';
// ***** jqreq *****
Req.localPath = Req.localPath || '/skin/basic/'
Req(
  'autovalidate',
  'anchortags',
  'curtain',
  'equalizeheights',
  'eutils',
  'fickle',
  'fontsizer',
  'imgpop',
  'labelizor',
  'listscroller',
  'mailtoenabler',
  'tabswitcher',
  'x/bookmark',
  'x/cufon',
  'x/ifixpng',
  Req.localPath+'js/Nilland-Black_900.font.js',
  function(){

    var $ = jQuery;
    
    $('body').addClass('js-active');

    // labelize search input
    $('#qstr').labelizor();

    $('.pgmain, .pgextra1').equalizeHeights();

    //set big background if screen is wide enough
    if ( $(window).width() > 968 ) { $('body').addClass('wide') };
    $(window).bind('resize', function() {
        if ( $(window).width() > 968 ) { $('body').addClass('wide') };
      });


    //frontpage bannerlist
    var bannerlistItems = $('.bannerlist .boxbody').find('.item, ul, li');
        // zap potential container elements.

    // check if bannerlist has just one item to hide the jump link
    var blHasOneItem = (bannerlistItems.length == 1) ? false : true;

    bannerlistItems
            .zap()
        .end()
        // remove/hide redundant content elements.
        .find('h3, .summary, .longdesc')
            .remove()
        .end()
        .listscroller({
            item          : 'a, span.img',
            windowSize    : 1,
            stepSize      : 1,
            paging        : blHasOneItem,
            aspect        : 'horizontal',
            speed         : 700,
            animation     : 'carousel',
            autoScrollDelay: 8000
          });


    if (!window.EPLICA_loggedin)
    {

      //cufonize fancyheadings
      $('.fancyhead .boxhead, a.dropbox-trigger').cufon().addClass('cufon-active');

      //articlelists fancination
      $('.articlelist').each(function() {
          var alist = $(this);

          //image fixes
          $('.item > img', alist)
                  .wrap('<span class="img" />')
                  .wrap('<span class="imginner" />');

          $(window).bind('load', function() {
              $('.item img', alist)
                  .each(function() {
                      $(this).css({ 'margin-top' : ( $(this).parent().height() / 2 ) - ( $(this).height() / 2 )  })
                    })
            });

          //trimSummaries function
          function trimSummaries (s, l)
          {
            if( $.trim(s.text()).length > l ) {
              var imgElm = $('img', s).clone(),
                  moreBtn = $('span.more', s).clone();
              imgElm.remove();
              moreBtn.remove();

              var summText = $.cropText(s.text(), l);

              s.text( summText ).prepend( imgElm ).append(moreBtn);
            }
          }


          alist.not('.widelist').filter('.box-1_3').find('.item')
              .add(
                  alist.filter('.focuslist').find('.item:not(.firstitem)')
                )
              .find('.summary')
                  .each(function(){
                      trimSummaries($(this), 85)
                    });
          
          alist.filter('.focuslist').each(function() {
              var flHead = $('<h2 class="boxhead">News Archive</h2>');
              flHead.insertBefore( $(this).find('ul') );
              
            })
        })
        .filter('.box-1_3, .box-1_2, .box-2_3').not('.news').find('.item').equalizeHeights();


        // home pgextra3 box-1_3
        $('.home .pgextra3 div.box-1_3')
            .slice(0, 3)
                .equalizeHeights();




        // subscr
        var subscr = $('.home div.subscr'),
            openBtn = $('<div class="act"><a href="url">Sign up</a></div>')
                          .bind('click', function(e){
                              popup.fickle('open');
                              popupbox.parents('.subscr-popup').css('top', $(window).scrollTop());
                              return false;
                            }),
            popup = $('<div style="_height:1px;min-height:1px;" />') // fix for IE .. damn
                        .append( '<div class="curtain" />', subscr.clone().addClass('subscr-popup') )
                        .fickle({
                            focusTarget: '',
                            fadein: 300,
                            fadeout: 300,
                            opener: openBtn
                          })
                        .bind('click', function(e){ popup.fickle('close'); })
                        .appendTo('body'),
            popupbox = popup.find('> .subscr')
                        .bind('click', function(e){ e.stopPropagation(); })
                        .find('.boxbody')
                            .append('<div class="act"><a href="url" class="close">close</a></div>')
                                .find('a.close')
                                  .bind('click', function(e){
                                      popup.fickle('close');
                                      return false;
                                  });

        subscr
            .addClass('subscr-intro')
            .find('.boxbody')
                .find('*:not(p.desc)')
                  .remove()
                .end()
                .append(openBtn);



      /* *** postlisti ajax forms *** */
      $('div.subscr-popup form')
          .submit(function() {

              var theForm = $(this);

              if (theForm.isValid()) {
                  $.get(theForm.attr('action'), theForm.serialize(), function(response){
                      var pgmain = $(response).find('.pgmain .wrap .article .boxbody');

                      theForm.html(pgmain.html());

                  });

              }
              return false;

          });


      // event

      $('div.event').each(function(){
        var eventBox = $(this),
            detailsHTML = $('<div class="fancyhead bluehead infobox box">'+
                              '<h2 class="boxhead">Event details</h2>'+
                              '<div class="boxbody" />'+
                            '</div>'),
            detailsBody = detailsHTML.find('.boxbody');

        eventBox.find('.details').appendTo(detailsBody);
        eventBox
            .find('.imagebox')
                .find('img')
                    .appendTo(detailsHTML) // appendTo creates a new collection
                .end()
                .remove()

        $('.pgextra1 .wrap').prepend(detailsHTML);

        eventBox.find('ul.profilelinks').each(function(){
            var plinkUL = $(this);
            plinkUL.prev('h2').addClass('profilelinkHead');

            plinkUL.find('a').each(function(){
                  var link = $(this),
                      match = link.attr('href').match(/\.(facebook|myspace|twitter|youtube|soundcloud)\./),
                      liElm = link.closest('li');
                  match ?
                      liElm.addClass( 'icn icn-' + match[1] ):
                      liElm.appendTo( plinkUL );
              });

          });
      });



      //create tabs
      $('div.article:has(h2.tab)')
          .each(function(i, article){
              article = $(article)
              article.find('h2.tab').each(function(i, h2){
                  h2 = $(h2);
                  h2.add( h2.nextUntil('h2') ).wrapAll('<div class="tabpane" />');
                });
              article.find('.tabpane').makeTabbox().tabSwitcher();
            });

      $('div.tabs ul').tabSwitcher();



      // pngfix for IE6
      if ($.browser.msie && $.browser.version < 7) {
        $('img[src$=".png"]').ifixpng();
      }



      //popup in articles
      $('div.article div.imagebox')
          .find('a.img')
              .each(function() {
                var imgsrc = $(this).find('img').attr('src').replace(/\/[^\/]+\/([^\/]+)$/, '/large/$1');
                $(this).attr('href', imgsrc)
              })
          .end()
          .prependTo('.pgextra1 .wrap');



      //iconify links
      $('.article p a, .article li a, .media p a, .media li a').anchorTags({ usePatterns: ['pdf', 'doc', 'xls', 'audio', 'video'] });




      //collapse collapselist boxes if more than 3 links
      $('.collapselist .boxbody ul')
          .each(function() {
              if( $('li', this).length > 3 ) {
                var block = $(this),
                    open = false,
                    h1 = $(this).height(),
                    h2 = $('li:eq(0)', this).outerHeight() + $('li:eq(1)', this).outerHeight() + $('li:eq(2)', this).outerHeight();

                block
                    .css({
                        height : h2,
                        overflow: 'hidden'
                      })
                    .after('<p class="more"><a href="#">See more</a></p>')
                    .parent()
                        .find('.more a')
                            .bind('click', function() {
                                $(this).html( open == false ? 'Show less' : 'Show more' ).blur();

                                var animHeight = open == false ? h1 : h2;
                                block.animate({ height : animHeight}, 300);

                                open == false ? open = true : open = false;
                                return false;
                              })
              }
            });



      $('.actbuttons').each(function(){
          var actButtons = $(this),
              actUl = actButtons.find('ul')
              calBtn = actUl.find('li.calendar').detach(),
              shareBtn = actUl.find('li.share'),
              sendBtn = actUl.find('li.send');

          if (!calBtn.length)
          {
            calBtn = $('<li class="calendar"><a href="#">Add Event to my Calendar</a></li>');
            calBtn.prependTo(actUl);
          }
          calBtn.detach(); // disable until we've finished the script!

          if (!shareBtn.length)
          {
            shareBtn = $('<li class="share"><a href="#">Share / Add Bookmark</a></li>');
            shareBtn.appendTo(actUl);
          }
          var bookmarks,
              bookmarksOpen;
          shareBtn.find('a').bind('click', function (e) {
              bookmarks = bookmarks || $('<div class="share-menu">').appendTo(shareBtn).hide().bookmark({
                                              title:   $('h1:first').text(),
                                              sites:   ['facebook', 'twitter', 'google', 'yahoobm', 'stumbleupon', 'digg', 'reddit', 'delicious', 'spurl'],
                                              compact: false, // defaults to `true`
                                              icons:   null
                                            });
              bookmarksOpen ?
                  bookmarks.slideUp(150):
                  bookmarks.slideDown(300);
              bookmarksOpen = !bookmarksOpen;
              shareBtn.toggleClass('share-open', bookmarksOpen)
              return false;
            });



          if (!sendBtn.length)
          {
            sendBtn = $('<li class="send"><a href="#">Send page to Friend</a></li>');
            sendBtn.appendTo(actUl);
          }
          sendBtn.find('a').attr(
                'href',
                'mailto:your.friend@email.address?'+$.param({
                        subject: 'Interesting item on Iceland Naturally',
                        body: $('h1:first').text() + ':\n' + location.href
                      }).replace(/\+/g, '%20')
              )


        });

      // cuz of body background
      if($('.pgwrap').height() < 900) {
        var sumheights = $('.pghead').outerHeight() + $('.pgextra3').outerHeight() + $('.pgfoot').outerHeight();
        $('.pgmain .wrap').css({ height : 900 - sumheights });
      }

    } // end logged in



    //remove flicker trick
    $('#noflickerCSS').remove();


    //init popups and image centering
    $('ul.imagelist')
        .each(function() {
          $('li a', this)
              .imgPopper({
                  curtainColor : '#000000',
                  curtainOpacity : '0.8'
                })
              .find('img')
                  .each(function() {
                      $(this).css({ 'margin-top' : ( $(this).parent().height() / 2 ) - ( $(this).height() / 2 )  })
                    });
          })
        .parent()
        .find('.more')
            .append('<span>Click on the image to enlarge.</span>');

    $('div.imagelist ul li')
        .equalizeHeights()
        .find('a')
            .each(function() {
                $(this).css({ 'margin-top' : ( $(this).parent().height() / 2 ) - ( $(this).height() / 2 )  })
              });




    // news
    $('.addrss .moreolder').each(function() {
        var morelink = $(this).find('a').attr('href');
        $(this).prepend('<a class="rss" href="'+ morelink +'/rss.xml">Subscribe</a>');
      });




    if (!window.EPLICA_loggedin)
    {

      // imgswitcher
      var articleimages = $('.imagescroller .boxbody');
          articleimageList = $('li a', articleimages);
      if(articleimageList.length > 1 && !window.EPLICA_loggedin)
      {

        articleimages.append('<div class="medimg"><a href="#"><img src="" alt="" /></a></div>');

        // imgswitcher - helper function
        $.fn.setImg = function( ) {
          activeImg.parent().removeClass('active');
          activeImg = $(this);

          var medImg = activeImg.attr('href').replace(/large/i, 'medium'),
              bigImg = activeImg.attr('href');

          $('.medimg a', articleimages)
              .stop()
              .fadeOut(150, function() {
                  $(this)
                      .attr('href', bigImg)
                      .find('img')
                          .attr('src', medImg)
                      .end()
                      .fadeIn(200, function() { $(this).stop().css({ opacity : 1 }) })
                });

          activeImg.parent().addClass('active');
        }

        //imgswitcher - init switcher
        var activeImg = $('li a:first', articleimages);
        activeImg.setImg();


        //imgswitcher - hovering
        var trigger = false;
        $('li a', articleimages)
            .hover(
                  function(){ // in
                    trigger = false;
                    var elm = $(this)
                    setTimeout(function(){
                      if(!trigger) {
                        elm.setImg();
                      }
                    }, 200);
                  },
                  function(){ // out
                    trigger = true;
                  }
              )
            .bind('click', function() {
                return false;
              });


        //imgswitcher - listscroller
        $('ul', articleimages)
            .listscroller({
                item: 'li',
                aspect: 'horizontal',
                windowSize: 4,
                stepSize: 4,
                animation: 'carousel',
                controls: 'above',
                paging: true,
                jumpPager: false,
                statusPager: true,
                itemStatusPager: true,
                titleNext: 'Scroll forward',
                titlePrev: 'Scroll back',
                statusLabel: 'Displaying: ',
                ofTotalSeparator: ' of ',
                statusLabelAfter: ' images'
              });

        //imgswitcher - popup on medimg click
        $('.medimg a')
            .bind('click', function() {
                activeImg.trigger('click');
                return false;
              });

      }  // end imgswitcher
      if ( articleimageList.length == 1) {
        articleimageList.prependTo( articleimages ).wrap('<div class="medimg" />');
        articleimages
            .find('ul')
                .remove()
            .end()
            .find('img')
                .each(function(){
                    $(this).removeAttr('style');
                    var imgsize = $(this).attr('src').replace(/small/i, 'medium')
                    $(this).attr('src', imgsize);
                  });
      }       


      // news
      var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
      var weekdays = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];

      var eitems = $('.eventlist .item');
      var eitemsBoxbody = eitems.eq(0).parent();

      eitemsBoxbody.append('<div class="items" />');

      eitems
          .each(function(i){

              var eitemsDate = eitems.find('.date').eq(i).html();
              if ( eitemsDate ) {
                var eitemsDateNext = eitems.find('.date').eq(i+1).html();

                var d = new Date(eitemsDate);

                eitemsBoxbody.find('.items:last').append($(this));

                if(eitemsDate != eitemsDateNext && i != eitems.length-1) {
                  eitemsBoxbody.append('<div class="items" />');
                }

                // change the date
                var dt = $(this).find('.date').html().split('.');

                var dn = new Date(eitemsDate);
                dn.setFullYear(dt[2],dt[1]-1,dt[0]);

                $(this)
                    .find('.date')
                    .html('<b class="d">' + dt[0] + '</b> <b class="m">'
                            + months[dt[1]-1] + '</b> <b class="y">'
                            + dt[2] + '</b> <b class="dn">'
                            + weekdays[dn.getDay()] + '</b>');
              }
            });

      eitemsBoxbody.find('.items').each(function(){

          $(this).find('.meta:first').prependTo($(this));

          $(this).find('.meta:not(:first)').remove();

      });
      
    }
    
    
    // dropbox
    var dropbox = $('div.dropbox'),
        dropboxtrigger = $('a.dropbox-trigger');
    
    if(dropbox.length && dropboxtrigger) {
      dropboxtrigger.after(dropbox);
    }
    
    dropbox
        .hide()
        .find('.boxbody')
            .append('<a href="#" class="close">Close</a>')
            .find('a.close')
              .bind('click', function(){
                  dropbox.slideUp(500, function() {
                      dropboxtrigger.css('visibility', 'visible');
                      return false;
                  });
              })
            .end()
            .find('.fi_txt input')
                .labelizor();
        
    dropboxtrigger
        .bind('click', function(){
            dropboxtrigger.css('visibility', 'hidden');
            dropbox.slideDown(500);
            return false;
        });

    $('form', dropbox)
        .submit(function() {
            var theForm = $(this);
            if (theForm.isValid()) {
              var action = theForm.attr('action') || document.location.toString().replace(/([?#].*)?$/, '');
              $.get(action, theForm.serialize(), function(response) {
                  var newDoc = $(response).find('.pgmain .boxbody').text();
                  theForm.before('<div class="responce">' + newDoc + '</div>');
                  theForm.remove();
              });
            }
            return false;
        });


    $('td.netfang').mailtoEnabler()


    // fontsizer
    $('.pagestyle').fontsizer();

    // validate all forms
    $('form').autoValidate();


  }
);
// **** /jqreq *****
