// encoding: utf-8

/* blackberry check / arbys promo / png24 */
var isblackberry = /BlackBerry/i.exec(navigator.userAgent);
if(isblackberry) {
  var bdy = document.getElementsByTagName('body')[0];
  bdy.className = bdy.className += ' blackberry';
}

/*@cc_on/*@if(@_jscript_version<5.7)try{document.execCommand('BackgroundImageCache',0,1)}catch(e){}/*@end@*/
Req.localPath = /https?:/.test(document.location) ? '/skin/basic/' : Req.localPath;
// ***** jqreq *****
Req.localPath = Req.localPath || '/skin/basic/'
Req(
  'autovalidate',
  'anchortags',
  'curtain',
  'equalizeheights',
  'eutils',
  'fickle',
  'fontsizer',
  'imgpop',
  'labelizor',
  'listscroller',
  'mailtoenabler',
  'tabswitcher',
  'virtualbrowser',
  'x/bookmark',
  'x/cufon',
  'x/ifixpng',
  Req.localPath+'js/Nilland-Black_900.font.js',
  function(){

    var $ = jQuery,
        oldMSIE = $.browser.msie && parseFloat($.browser.version)<9,
        body = $('body').addClass('js-active'),
        article = body.find('.article'),
        articlelist = body.find('.articlelist');


    if ( $('.mnav .level2').length == 0 ) {
      body.addClass('onelevel');
    }

    // labelize search input
    $('#qstr').labelizor();

    //$('.pgmain, .pgextra1').equalizeHeights(); //this is commented out due to i can't see a reason for this being used, aslo this caused some problems with tabs in IE7 and Chrome(not browser tabs)

    //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 bannerlist = $('.bannerlist .boxbody');
    if (bannerlist.length) {
      var bannerlistItems = bannerlist.find('.item, li'),
          blHasOneItem = (bannerlistItems.length == 1) ? false : true;

      bannerlistItems
              // zap potential container elements.
              .zap()
          .end()
          // remove/hide redundant content elements.
          .find('h3, .summary, .longdesc')
              .remove()
          .end()
          .filter(function() { return bannerlistItems.length > 1 })
              .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').cufon().addClass('cufon-active');

      //articlelists fancination
      articlelist.each(function() {
          var alist = $(this);

          //image fixes
          $('.img img', alist).wrap('<span class="imginner" />');
          $('.item > img', alist).wrap('<span class="img" />').wrap('<span class="imginner" />');
          

          $(window).bind('load', function() {
              alist.not('.noimgcenter').find('.item img')
                  .each(function() {
                      $(this).css({ 'margin-top' : ( $(this).parent().height() / 2 ) - ( $(this).height() / 2 )  })
                    })
            });
 
          /* trimSummaries function - use text-overflow css rules instead? */
          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.filter('.box-1_3:not(.widelist)').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();


      //equalize box-1_4 in rows
      var quartbox = articlelist.filter('.box-1_4');
      if (quartbox.length) {
        quartbox.filter('.box-left')
          .find('.item').each(function(i){
              $(this).add( quartbox.find('.item').filter(function() { return $(this).index() == i }) ).equalizeHeights();
            });
        quartbox.find('.item:has(img)').addClass('hasimg');
      }



      if (body.is('.home')) {

        // home pgextra3 box-1_3
        $('.pgextra3 .box-1_3')
            .slice(0, 3)
                .equalizeHeights();

        $('.pgextra3 .widelist .item').equalizeHeights();


        
        $('.cotm .boxbody').each(function(){
            var cotmHovered = false,
                cotm = $(this),
                cotmSummary = cotm.find('.summary');
            cotm
              .bind('click', function (e) {
                  cotm.trigger('mouseenter');
                })
              .bind('close', function (e) {
                  cotmSummary.slideUp(200, function() { cotm.removeClass('cotm-open'); });
                })
              .bind('mouseenter', function (e) {
                  if (!cotmHovered) {
                    cotm.addClass('cotm-open');
                    cotmSummary.slideDown(200);
                  }
                  cotmHovered = true;
                })
              .bind('mouseleave', function (e) {
                  cotmHovered = false;
                  setTimeout(function() {
                    if (!cotmHovered) {
                      cotm.trigger('close');
                    }
                  }, 250);
                });

            cotmSummary.append(
                $('<a class="close" href="#">Close</a>').bind('click', function (e) {
                    cotm.trigger('close');
                    return false;
                  })
                )
          });


        // subscr
        var subscr = $('.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 *** */
        $('.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;

            });
        
        // dropbox
        var dropbox = $('.dropbox');
        if (dropbox.length) {

          var dropboxtrigger = $('a.dropbox-trigger');

          dropboxtrigger.cufon().addClass('cufon-active');
          
          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;
              });
        }
            
      }

      // event
      var eventBox = article.filter('.event');
      if (eventBox.length) {
        var detailsHTML = '',
            relmediaHTML = '',
            mediaTypes = {
              'mp3' : 'audio',
              'youtube' : 'video',
              'vimeo' : 'video'
            };

        if ( eventBox.find('.details').length ) {
          detailsHTML = $('<div class="fancyhead bluehead infobox box">'+
                                '<h2 class="boxhead">Event details</h2>'+
                                '<div class="boxbody" />'+
                              '</div>');
          eventBox.find('.details').appendTo( detailsHTML.find('.boxbody') );

          eventBox
              .find('.imagebox')
                  .find('img')
                      .appendTo(detailsHTML) // appendTo creates a new collection
                  .end()
                  .remove();
        }

        if ( eventBox.find('.relmedia').length ) {
          relmediaHTML = $('<div class="fancyhead media box">'+
                                '<h2 class="boxhead">Related media</h2>'+
                                '<div class="boxbody" />'+
                              '</div>');
          eventBox.find('.relmedia').appendTo( relmediaHTML.find('.boxbody') );

          relmediaHTML.find('li a').each(function(){
              var link = $(this),
                  match = link.attr('href').match(/(youtube|vimeo|mp3)\./);
              if (match) {
                link.addClass( 'file_' + mediaTypes[ match[1] ] )
              }
            });
        }

        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 );
              });

          });

        $('.pgextra1 .wrap').append(relmediaHTML).prepend(detailsHTML).find('.yearindex').remove();
      }


      if (article.length) {

        //create tabs
        article.has('h2.tab')
            .each(function(i){
                var tabarticle = $(this)
                tabarticle.find('h2.tab').each(function(i, h2){
                    h2 = $(h2);
                    h2.add( h2.nextUntil('h2, .buttons, .fb-like') ).wrapAll('<div class="tabpane" />');
                  });
                tabarticle.find('.tabpane').makeTabbox().tabSwitcher({ setFragment: false });
              });

        $('.tabs ul').tabSwitcher();


        //popup in articles
        article.find('.imagebox')
            .find('a.img')
                .each(function() {
                  var imgsrc = $(this).find('img').attr('src').replace(/\/[^\/]+\/([^\/]+)$/, '/large/$1');
                  $(this).attr('href', imgsrc)
                })
            .end()
            .prependTo('.pgextra1 .wrap');

        //zebra tables
        article.find('tbody tr:nth-child(2n-1)').addClass('odd');

        article.find('p a, li a').anchorTags({ usePatterns: ['pdf', 'doc', 'xls', 'audio', 'video'] });
        
        article.find('a.videolink').Req(
            'q-videolinks',
            function() {
              $(this).videoLinks(); //{ vidWidth:'auto',vidHeight:'auto',aspect4x3:false }  Set width and height (default auto) and aspect 4x3 autocalc (default 16x9)
            }
          );
/*
        //share / bookmark
        var buttons = article.find('.buttons')
        if (buttons.length) {
          var bookmarksOpen,
              shareHover = false,
              shareBtn = $('<span class="share"><a href="#">Share article</a></span>'),
              bookmarks = $('<div class="share-menu" />').bookmark({
                                                      title:   $('h1:first').text(),
                                                      addEmail: true,
                                                      emailText: 'Send as e-mail',
                                                      emailSubject: 'Interesting article on IcelandNaturally.com',
                                                      emailBody: 'I thought you might find this page interesting:\n\n{t}\n{u}',
                                                      sites:   ['facebook', 'twitter', 'google', 'yahoobm', 'stumbleupon', 'digg', 'reddit', 'delicious', 'spurl'],
                                                      compact: false, // defaults to `true`
                                                      icons:   '/skin/basic/design/i/icons.png'
                                                    });

          shareBtn.prependTo(buttons);
          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;
                });
        } // end share buttons
*/
      } // end article
     

      //iconify links
      $('.media').find('p a, li a').anchorTags({ usePatterns: ['pdf', 'doc', 'xls', 'audio', 'video'] });




      //collapse collapselist boxes if more than 3 links
      var collapselist = $('.collapselist');
      if (collapselist.length) {
        collapselist.find('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;
                            })
            }
          });
      }


      //action buttons
      var actButtons = $('.actbuttons');
      if (actButtons.length) {
            var 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
      setTimeout(function(){
          if(body.find('>.pgwrap').height() < 900) {
            var sumheights = $('.pghead').outerHeight() + $('.pgextra3').outerHeight() + $('.pgfoot').outerHeight();
            $('.pgmain .wrap').css({ 'min-height' : 900 - sumheights });
          }
        }, 150);


    } // end logged in



    //remove flicker trick
    $('#noflickerCSS').remove();


    //init popups and image centering
    var imagelist = $('ul.imagelist');
    if (imagelist.length) {

      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>');

      imagelist.find('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');
      if(articleimages.length && !window.EPLICA_loggedin)
      {
        var articleimageList = articleimages.find('li a');

        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);
                    });
        }
        else
        {
          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;
                });
        }
        //articleimages.parent().prependTo( $('.pgextra1 .wrap') );
      }  // end imgswitcher



      // news
      var eventlist = $('.eventlist');
      if (eventlist.length) {
        var eitems = eventlist.find('.item');
        if (!eitems.length) {
          eventlist.find('.boxbody').addClass('noneahead').html('<p>There are no events registered for this month. You can use the calendar on the right to browse events.</p>');
        }
        else
        {
          var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
              weekdays = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],
              eitemsBoxbody = eitems.eq(0).parent();

          eitemsBoxbody.append('<div class="items" />');

          eitems
              .each(function(i){

                  var eitemsDate = $(this).find('.date').html();
                  if ( eitemsDate ) {
                    if (eitemsDate.split(' - ')[1]) {
                      var daterange = $.trim(eitemsDate.replace(/\s+-\s+/, '.')).split('.');
                      $(this)
                          .addClass('daterange')
                          .find('.date')
                          .html( months[daterange[1]-1] + ' ' +  daterange[0] + ', ' + daterange[2] + ' - ' + months[daterange[4]-1] + ' ' +  daterange[3] + ', ' + daterange[5] );
                    }
                    else 
                    {
                      var eitemsDateNext = eitems.find('.date').eq(i+1).html(),
                          d = new Date(eitemsDate),
                          dt = $(this).find('.date').html().split('.'),
                          dn = new Date(eitemsDate);

                      eitemsBoxbody.find('.items:last').append($(this));

                      if(eitemsDate != eitemsDateNext && i != eitems.length-1) {
                        eitemsBoxbody.append('<div class="items" />');
                      }

                      // change the date
                      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();
            });
        }
      }

    }


    //category specific stuff
    if (!window.EPLICA_loggedin)
    {

      //require sharing
      var reqsharelnk = $('a.reqshare');
      if (reqsharelnk.length) {
        var title = $.trim( article.find('h1').text() );
        reqsharelnk.bind('click', function (e) {
            if ( $.cookie('page-shared') != title ) {
              e.preventDefault();
              alert('Please share this article before entering.');
              if (actButtons.length)
              {
                actButtons.find('.share a').trigger('click').focus();
              }
              else
              {
                article.find('.buttons .share a').trigger('click').focus();
              }
            }
          });

        actButtons.find('a').add( article.find('.buttons .share li a') ).bind('click', function (e) {
            $.cookie('page-shared', title, { expires: 7 });
          });
      }

      //special twitter sharing text for http://www.icelandnaturally.com/olafur-arnalds-usa-tour/
      if (body.is('.page-olafur')) {
        var special = encodeURI('A Chance to win a trip to Iceland for Iceland Airwaves with @olafurarnalds and @icelandnatural http://bit.ly/oa-usa');
        actButtons.find('.share > a').bind('click', function (e) {
            $('.bookmark_list li a').eq(1).attr('href', 'http://twitter.com/?status='+special);
          });
      }

      //special twitter sharing text for http://www.icelandnaturally.com/taste-of-iceland---boston
      if (body.is('.page-boston')) {
        var special = encodeURI('Boston to Host 2nd Annual Festival of Icelandic Culture And Entertainment This Spring: http://ow.ly/478SU');
        actButtons.find('.share > a').bind('click', function (e) {
            $('.bookmark_list li a').eq(1).attr('href', 'http://twitter.com/?status='+special);
          });
      }

      //airwaves on campus :: http://www.icelandnaturally.com/campus2010
      $('.campusform').each(function(){
          var cpf = $(this);
          cpf
              .wrapInner('<div class="toggle" />')
              .children()
                  .hide()
              .end()
              .prepend('<h2 class="formhead"><a href="#">Click here for a chance to win a trip to Reykjavik, Iceland!</a></h2>')
              .insertAfter('.awcampus .subtitle')
              .delegate('.formhead a', 'click', function (e) {
                  cpf.find('> .toggle').slideToggle('fast');
                  return false;
                });
        });

      //airwaves on campus menu :: http://www.icelandnaturally.com/campus2010/the-menu
      $('.airwavesmenu').run(function(){
          if (this.length) {
            $(this).find('.menucarousel')
                .wrap('<div class="imgwrap" />')
                .listscroller({
                    item          : 'li',
                    windowSize    : 3,
                    stepSize      : 1,
                    jumpPager     : false,
                    aspect        : 'horizontal',
                    speed         : 700,
                    animation     : 'carousel',
                    wrap          : 'loop'
                  })
                .find('img')
                    .each(function(){
                        var src = $(this).attr('src').replace(/\/[^\/]+\/([^\/]+)$/, '/large/$1');
                        $(this).wrap('<a href="'+ src +'" />')
                      })
                .end()
                .find('li a')
                    .imgPopper({
                        curtainColor : '#000000',
                        curtainOpacity : '0.8'
                      });
          }
        });



      //Bachelorette image popup (ali's photos on /bachelorette) :: ?
      $('.bachelorette .thumbsview li a:has(img)')
          .each(function() {
            var imgsrc = $(this).find('img').attr('src').replace(/\/[^\/]+\/([^\/]+)$/, '/large/$1');
            $(this).attr('href', imgsrc)
          }) 
          .imgPopper({
              curtainColor : '#000000',
              curtainOpacity : '0.8'
            });


      //Virtualbrowser :: ?
      var trivialinks = article.filter('.event').find('a.trivia');
      if (trivialinks.length) {

        var popupCont,
            f = oldMSIE ? 0 : 1,
            nothingfoundMsg,
            cacheBust = 0, // cache busting (needed for IE6)
            getPopup = function () {
                if (!popupCont)
                {
                  popupCont = $('<div class="virtualiframe-container" />')
                                    .curtain({ className: '' })
                                    .fickle({
                                        fadein: 500*f,
                                        fadeout: 500*f,
                                        closeOnEsc: false, //also have to make sure box does not close on focus out
                                        onOpen: function(){
                                            popupCont.appendTo('body');
                                            elm.css( 'top', $(window).scrollTop() );
                                          },
                                        onClosed: function(){
                                            popupCont.detach();
                                            var elms = popupCont.data('elms')
                                            elms.head.empty();
                                            elms.body.empty();
                                          },
                                        focusTarget: ''
                                      })
                                    .bind('click', function (e) { $(this).fickle('close'); });


                  var elm =  $('<div class="virtualiframe">' +
                                  '<a href="#" class="focustarget">.</a>' +
                                  '<div class="wrap" />' +
                                '</div>')
                                  .bind('click', function (e) { e.stopPropagation(); })
                                  .appendTo(popupCont),

                      body =  elm.find('.wrap')
                                  .virtualBrowser({
                                      params:       'justPicPos=pgmain',
                                      loadmsgMode:  'replace',
                                      onBeforeload: function (e, request) {
                                                        var url = request.url;
                                                        // Open .xml links in a new window
                                                        if (/\.xml$/.test(url))
                                                        {
                                                          request.elm.target = request.elm.target || 'feedwindow';
                                                          e.passThrough = true;
                                                        }
                                                      },
                                      onLoad:       function (e, request) {
                                                        var linkId = $(this).data('virtualBrowser').cfg.linkId,
                                                            box =  $.getResultBody(request.result)
                                                                       .find( (linkId  &&  ajaxSelectors[linkId]) || ajaxSelectors._default );
                                                        if (box.length)
                                                        {
                                                          box.wrap('<div />').find('form').autoValidate();
                                                          request.resultDOM = box;
                                                        }
                                                        else
                                                        {
                                                          request.resultDOM = nothingfoundMsg || (nothingfoundMsg = $('<div class="nothingfound">Nothing found...</div>'));
                                                          setTimeout(function(){ popupCont.fickle('close'); }, 1000);
                                                        }
                                                      }
                                    }),

                      closeBtn = $('<a href="#" class="closebtn" title="Close">Close</a>')
                                    .bind('click', function (e) {
                                        popupCont.fickle('close');
                                        return false;
                                      })
                                    .appendTo(elm);

                  popupCont.data('elms', {
                        head:     elm.find('.title'),
                        body:     body,
                        closeBtn: closeBtn
                      }
                    );
                }
                return popupCont;
            },

            ajaxSelectors = {
                'rsslinks-window': '.rsslinks',
                _default:          '.pgmain .wrap > *'
                //_default: '.pgmain *:has(>.boxhead):first'
              };

        //trivia :: ?
        trivialinks.each(function(i, link){
            var linkId = $(link).attr('class') +'-window';
              //;;;alert( linkId );
                $(this).bind('click', function (e, obj) {
                    getPopup() // <-- returns popupCont
                             .addClass(linkId)
                             .addClass('hastitle')
                             .one('fickleclosed', function(){ $(this).removeClass(linkId); }) 
                        .fickle('open', { opener: (obj&&obj.opener)||this });
                    var elms = popupCont.data('elms'); 
                    
                    //elms.head.append( link.title );
                    elms.body
                        .one('VBbeforeload', function (e) {
                            $(this).data('virtualBrowser').cfg.linkId = linkId; 
                          })
                        .virtualBrowser('load', this);
                    return false;
                  });
          });

      } // end trivialinks

      // pngfix for IE6
      if ($.browser.msie && $.browser.version < 7) {
        $('img[src$=".png"]').ifixpng();
      }

    }// end !loggedin



    //for "fall in love" voting. :: http://www.icelandnaturally.com/fall-in-love/vote
    var votelist = $('.voteform li');
    if (votelist.length)
    {
      var lastSelected = votelist
                              .bind('click', function (e) {
                                  var item = $(this);
                                  lastSelected.removeClass('selected');
                                  lastSelected = item;
                                  item
                                      .addClass('selected')
                                      .find('input:radio')
                                          .prop('checked', true);
                                })
                              .filter(':has(input:checked)')
                                  .addClass('selected');
    } //end votelist



    $('td.netfang').mailtoEnabler()
    $('.pagestyle').fontsizer();
    $('form').autoValidate();

    //loading body class scripts 
    Req.loadPageScripts();

  }
);
// **** /jqreq *****
