// 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',
  'autovalidate',
  'labelizor',
  'imgpop',
  'mailtoenabler',
  'listscroller',
  'equalizeheights',
  'tabswitcher',
  'linkify',
  'curtain',
  'fickle',
  'x/bookmark',
  'http://codecentre.eplica.is/jquery/quickies/quicky-videoplayer-min.js',

  function(){
    var $ = jQuery,
        ie6 = $.browser.msie && parseInt($.browser.version) < 7,
        ie76 = $.browser.msie && parseInt($.browser.version) < 8,
        isIS = $('html').attr('lang') == 'is',
        body = $('body'),
        removeNoFlickerCSS = true;
    
    var months = isIS ? ['jan','feb','mar','apr','maí','jún','júl','ágú','sep','okt','nóv','des'] : ['jan','feb','mar','apr','may','jun','jul','aug','sep','okt','nov','dec'];

    if ( body.is('.clubhome') )
    {
      removeNoFlickerCSS = false;
      Req( Req.localPath+'js/club-home.js' );
    }

    if (!window.EPLICA_loggedin)
    {
      var articlelist = $('.articlelist');
      $('.articlelist img').wrap('<span class="imginner" />')
      articlelist.find('.item').filter(function() { return $(this).find('img').length == 0 }).addClass('noimg');

      $('.bnav').equalizeHeights();

      $('.boxrow-1').equalizeHeights();
      $('.boxrow-2').equalizeHeights();
      $('.boxrow-3').equalizeHeights();
      $('.boxrow-4').equalizeHeights();

      
      var subcatlist = $('.subcatlist .item');
      for (var i=0, l=subcatlist.length; i<l; i+=3)
      {
        subcatlist.slice(i,i+3).equalizeHeights();
      }
      subcatlist
          .bind('click', function (e) {
              window.location = $(this).find('a:first')[0].href;
            });


      $('.videoblog')
          .each(function(){
              $(this).find('.item').equalizeHeights();
            });

      // mnav decoration
      !ie6 && $('.mnav').each(function(){
          var mnavLine = $('<div class="mnav-line" />'),
              mnav = $(this).find('.boxbody'),
              mnavCurrent = mnav.find('.parent a, .current a'),

              mnavLineAni = function(hoverElm){
                mnavLine.stop()
                    .animate({
                        'width': hoverElm.outerWidth(),
                        'left': hoverElm.position().left
                    });
              };

              if ( !mnavCurrent[0]  &&  body.is('.home, .clubhome') )
              {
                mnavCurrent = mnav.find('.home a');
              }

          if ( mnavCurrent[0] )
          {
            mnavLine
                .prependTo(mnav)
                .css({
                  'width': mnavCurrent.outerWidth(),
                  'left':  mnavCurrent.position().left
                  });
          }

          mnav.find('li')
              .hover(
                  function (e) {  mnavLineAni( $(this).find('a') );  },
                  function (e) {  mnavLineAni( mnavCurrent );  }
                );
        }); // end mnav fancyness



      $('.article').each(function(){
          var article = $(this);

          article.find('blockquote')
              .prepend('<span class="icn" />');

          //content collapsing
          article.find('h3.collapse')
              .each(function(){
                  var head = $(this);
                  head.addClass('collapse-active collapse-closed').nextUntil('h2, h3, hr').wrapAll('<div class="collapseouter" />').wrapAll('<div class="collapsebox" />').parent().parent().hide();
                  head.wrapInner('<a href="#" />').find('a').bind('click', function (e) {
                      head
                          .toggleClass('collapse-closed')
                          .next().slideToggle('fast');
                      return false;
                    });
                })
              .filter(':first')
                  .addClass('collapse-first');


          //zebra tables
          article.find('table:not(.nozebra) tbody tr:nth-child(2n)').addClass('odd');


          //move imagebox after summary
          var summ = $('.summary', article),
              imgbox = $('.imagebox', article);
          if ( summ.length && imgbox.length && !article.is('.candidate-article') ) {
            imgbox.insertAfter(summ);
          }

          //listscroll imageboxes
          var zoomText = isIS ? 'Smelltu á myndina til að stækka' : 'Click on the image to zoom';
          !ie6 && imgbox
              .attr('title',zoomText)
              .filter(function(){ return $(this).find('li').length > 1; })
                  .listscroller({
                      item : 'li',
                      aspect     : 'horizontal',
                      paging     : true,
                      statusPager: true,
                      jumpPager  : false,
                      animation  : 'carousel',
                      windowSize : 1,
                      stepSize   : 1,
                      ofTotalSeparator: isIS ? ' af  ' : ' of  ',
                      labelNext  : isIS ? 'Næsta' : 'Next',
                      labelPrev  : isIS ? 'Fyrri' : 'Previous',
                      statusLabel: '',
                      titleNext  : isIS ? 'Næsta mynd' : 'Next image',
                      titlePrev  : isIS ? 'Fyrri mynd' : 'Previous image'
                    });

          //popup in articles
          $('a.img', imgbox)
              .each(function() {
                var imgsrc = $(this).find('img').attr('src').replace(/\/[^\/]+\/([^\/]+)$/, '/popup/$1');
                $(this).attr('href', imgsrc)
              })
              .imgPopper({
                  curtainColor : '#000000',
                  curtainOpacity : '0.7',
                  yOffset: 45,
                  fadeOutSpeed: 150
                });

        }); // end article


        //share / bookmark
        !ie6 && $('.buttons').each(function(){
            var btnbar = $(this),
                bookmarksOpen,
                shareText = isIS ? 'Segja frá' : 'Tell a friend',
                emailTextText = isIS ? 'Senda í pósti' : 'Send as e-mail',
                emailSubjectText = isIS ? 'Áhugaverð grein á vef Sjálfstæðisflokksins' : 'Interesting article on the Icelandic Independence Party website',
                emailBodyText = isIS ? 'Hugsa að þú hefðir áhuga á þessu:\n\n{t}\n{u}' : 'I thought you might find this page interesting:\n\n{t}\n{u}',
                shareHover = false,
                shareBtn = $('<span class="share"><a href="#">'+ shareText +'</a></span>'),
                bookmarks = $('<div class="share-menu" />').bookmark({
                                                        title:   $('h1:first').text(),
                                                        addEmail: true,
                                                        emailText: emailTextText,
                                                        emailSubject: emailSubjectText,
                                                        emailBody: emailBodyText,
                                                        sites:   ['facebook', 'twitter', 'google', 'yahoobm', 'stumbleupon', 'digg', 'reddit', 'delicious', 'spurl'],
                                                        compact: false, // defaults to `true`
                                                        icons:   '/skin/basic/design/i/icons.png'
                                                      }).hide();

            shareBtn
                .prependTo( btnbar )
                .append(bookmarks)
                .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 btnbar


      //videoblogg player generator
      var videoblog = $('.videoblog');
      if ( videoblog.length )
      {
        videoblog
            .makeTabbox()
                .tabSwitcher();

        videoblog
            .videoList({
                thumbnails: true,
                setfragment: true,
                autostart: 'all'
              })
            .find('.item')
                .addClass('yt-img');

        $('#videobox')
            .toggleClass( 'vb-hz', videoblog.is('.videoblog-hz') );
            /*.find('.videocontainer')
                .prepend('<a href="http://www.youtube.com/user/Sjalfstaedisflokkur" title="Sjálfstæðisflokkurinn á YouTube" class="overlaylink">Sjálfstæðisflokkurinn á YouTube</a>');*/

      }




      $('.articlelist-small .item')
          .bind('click', function (e) {
              window.location = $('a:first', this)[0].href;
            })
          .filter(':not(:first)').before('<span class="dashes" />').end()
          .add('.eventlist-small .item')
              .equalizeHeights();



      //eventlists
      $('.eventlist .item')
          .each(function(){
              var eventitem = $(this);

              var eventmeta =  eventitem.find('.date'),
                  datetime = $.trim ( eventmeta.text() ).split(/\s+/),
                  datesplit =  datetime[0].split('.'),
                  eventtime = datetime.slice(1).join(' ');

              eventmeta.parent().prepend( $(this).find('.venue'));
              eventitem.find('h3').before('<div class="js-date"><span class="d">'+ datesplit[0] +'</span><span class="m">'+ months[(datesplit[1]-1)] +'</span></div>');
            })
          .bind('click', function (e) {
              window.location = $('a:first', this)[0].href;
            })
          .filter(':not(:first)').before('<span class="dashes" />')


      // monthlist (remove empty dates)
      var mlhz = $('.monthlist-hz'),
          mlth = mlhz.find('th'),
          mltd = mlhz.find('td');
      mlhz.find('.calendar').wrap('<div class="calendarwrap" />')
      mltd
        .each(function(i) {
            if($(this).is('.o'))
            {
                $(this).remove();
                mlth.eq(i).remove();
            }
          });


      $('.event')
          .each(function(){
              var eventmeta = $(this).find('.meta')
              eventmeta.find('li:last').append(',&nbsp;').prependTo(eventmeta);
            });



      // candidates funk
      $('.candidates')
          .each(function(){
              $('.item', this)
                  .equalizeHeights()
                  //fara beint í frambjóðanda þegar smellt er á itemið ef tengill er til staðar
                  .filter(function() { return $(this).find('a').length > 0 })
                      .bind('click', function (e) {
                          
                          window.location = $('a:first', this)[0].href;
                        })
                  .end()
                  //annars búa til imagepopper tengil og poppa upp mynd
                  .filter(function() { return $(this).find('a').length == 0 })
                      .each(function(){
                          
                          $(this).find('img')
                              .each(function() {
                                  var imgsrc = $(this).attr('src').replace(/\/[^\/]+\/([^\/]+)$/, '/popup/$1');
                                  $(this).wrap('<a href="'+ imgsrc +'"></a>');
                                });
                        })
                      .find('a')
                          .imgPopper({
                              curtainColor : '#000000',
                              curtainOpacity : '0.7',
                              yOffset: 45,
                              fadeOutSpeed: 150
                            })
                      .end()
                      .bind('click', function (e) {
                          $(this).find('a').trigger('click');
                        });
            })
          .filter(':not(.primary-candidates)')
              .each(function(){
                  //split candidates up into 4 columns
                  var clItems = $('.item', this),
                      quadNum = Math.ceil(clItems.length / 4);

                  for (var i=0, l=clItems.length; i<l; i+=quadNum)
                  {
                    clItems.slice(i,i+quadNum).wrapAll('<div class="cl cl'+ i +'" />');
                  }

                  $('div.cl', this).equalizeHeights();
                });

        var candName = $.trim( $('h1').text() );
        $('.candidates-small .item')
            .each(function(){

                    var titleElm = $('h3 a',this),
                        title = $.trim( titleElm.text() );
                    if (candName.match(title) ) {
                      $(this).addClass('current');
                    }

                    titleElm.text( title.replace(/^(\S+\s+(\S+\s)?).+$/, '$1') );

                    $(this).bind('click', function (e) {
                        window.location = titleElm[0].href;
                      });
              })
            .filter(':not(.current)')
                .bind('mouseenter', function (e) {
                    $(this).find('img').animate({ 'width' : '55' }, 100);
                    $(this).find('.imginner').animate({ 'height' : 55 }, 100);
                    $(this).find('.img').animate({ 'margin-top' : -3 }, 100);
                  })
                .bind('mouseleave', function (e) {
                    $(this).find('img').animate({ 'width' : '49' }, 100);
                    $(this).find('.imginner').animate({ 'height' : 49 }, 100);
                    $(this).find('.img').animate({ 'margin-top' : 0 }, 100);
                  });


      
      !ie6 && $('.interview').each(function(){
          //imagemask on interview images
          $(this).find('img').each(function(){
                    var img = $(this),
                        imgsrc = img.attr('src').replace(/\/[^\/]+\/([^\/]+)$/, '/popup/$1');

                    $('<a href="'+ imgsrc +'" class="mask" />')
                        .insertAfter(img)
                        .imgPopper({
                            curtainColor : '#000000',
                            curtainOpacity : '0.7',
                            yOffset: 45,
                            fadeOutSpeed: 150
                          });
            });
        
          //ajax load full interviews
          var item =     $(this),
              moreLink =     item.find('.more a'),
              moreText = $.trim( moreLink.text() ),
              isOpen =   false;

          moreLink
              .bind('click', function (e) {
                  var articleText = moreLink.data('articleText');
                  if (articleText)
                  {
                    articleText.slideToggle(!isOpen);
                  }
                  else
                  {
                    isOpen || $.get(
                        moreLink.attr('href'),
                        { justPicPos: 'pgmain' },
                        function(data){
                            var articleText = $(data).find('.article .boxbody');
                            articleText
                                .addClass('articleText')
                                .removeClass('boxbody')
                                .find('h1, .subtitle, .summary, .meta, .imagebox').remove();
                            articleText.insertBefore( moreLink.parent() );
                            moreLink.data('articleText', articleText);
                          }
                      );
                  }

                  moreLink
                    .text( !isOpen ? 'Loka viðtali' : moreText )
                    .parent().toggleClass('open', !isOpen);
                  
                  isOpen = !isOpen;
                  return false;
                });

        }); // end interview


      // pngfix for IE6
      if ($.browser.msie && $.browser.version < 7) {
        $('img[src$=".png"]').Req('x/ifixpng', function(){
            $(this).ifixpng();
          });
      }

    //popup windows
      $.fn.popup = function ( cfg ) {
          var popupElm = this;
          if ( popupElm.length) {
            var curtainElm = $.curtain({
                        className: 'popup-curtain',
                        bg:        '#000000',
                        opacity:   .70,
                        fixed: true
                      }),
                remove = cfg && cfg.remove || false;
                closeText = isIS ? 'Loka' : 'Close';
            popupElm
                .hide()
                .appendTo('body')
                .addClass('popupblock')
                .before(curtainElm)
                .css({
                      top:        45 + $(window).scrollTop(),
                      marginLeft: - $.toInt( popupElm.outerWidth() ) / 2
                    })
                .fickle({
                    fadein: 350,
                    onOpen:   function (e) { $(this).prev().fadeIn(100);  },
                    onClose:  function (e) { popupElm.fadeOut(200, function() { $(this).prev().fadeOut(100); }); },
                    onClosed: function (e) { if (remove) { popupElm.prev().remove(); popupElm.remove(); } }
                  })
                .append('<a class="close" href="#">'+ closeText +'</a>')
                .find('a.close')
                    .bind('click', function (e) {
                        popupElm.fickle('close');
                        return false;
                      })
                .end()
                .fickle('open');
            popupElm.prev().bind('click', function (e) { popupElm.fickle('close'); });
          }
          return popupElm;
      };

    //ajax popups
    var svfelogPop = $('.svfelog a');
        
    !ie6 && svfelogPop
        .bind('click', function (e) {
            var link = $(this),
                popupForm = link.data('popupForm');
            if (popupForm)
            {
              popupForm.fickle('open');
            }
            else
            {
              $.get(
                  link.attr('href'),
                  { justPicPos: 'pgmain' },
                  function(data){
                      var popData = $(data).find('div.box:first'),
                          heading = popData.find('h1').text();
                      popData
                          .addClass('map-pop')
                          .removeClass('article')
                          .find('h1').remove().end()
                          .find('.boxhead').text(heading).end()
                          .find('h3')
                              .each(function(){
                                  var h3 = $(this);
                                  h3.add( h3.nextUntil('h3') ).wrapAll('<div class="tabpane" id="'+ h3.attr('id') +'" />');
                                  h3.removeAttr('id');
                                })
                          .end()
                          .popup();
                      !ie76 && popData
                          .find('.chapters ul')
                              .tabSwitcher({ setFragment: false })
                              .find('a')
                                  .append('<span class="hover" /><span class="hoverfix" />')
                                  .each(function(){
                                      var href = $(this).attr('href').replace('#', '');
                                      $(this).attr('title', $(this).text() ).parent().addClass(href);
                                    });
                      ie76 && popData.find('.chapters').removeClass('chapters').addClass('ie7chapters').find('ul').tabSwitcher({ setFragment: false });
                      link.data('popupForm', popData); // store for later
                    }
                );
            }
            return false;
          });


      //open svfelog if openlist=1
      var docLoc = document.location.toString().split('?');
      if (docLoc[1]) {
        var listTrigger = docLoc[1].match(/openlist=([^&]+)/);
        if (listTrigger && listTrigger[1]) {
          if (listTrigger[1] === '1' || listTrigger[1] === 'true') {
            svfelogPop.trigger('click');
          }
        }
      }
          

    } // end loggedin


/*
    $('div.twitterbox ul')
        .find('li')
            .each(function () {
                var li = $(this),
                    link = li.find('a')
                    text = link.text(),
                    permalink = link.attr('href');

                li.find('.meta').remove();
                link.text( text.split(':')[0] + ':' );
                $('<span class="tweet"/>')
                    .text( text.replace(/^.+?:/, '') )
                    .linkify()
                    .insertAfter( link )
                    .before( ' ' );
              });
*/
    $('div.twitterbox').each(function(){
        var permalink = $(this).find('a:first');
        if (permalink.length) {
          permalink = permalink.attr('href').replace(/[^\/]+$/, '').replace(/\/statuses\//, '');
          $(this)
              .find('.boxhead')
                  .wrapInner('<a href="'+ permalink +'" />')
              .end()
              .find('li')
                  .each(function () {
                      var li = $(this),
                          link = li.find('a')
                          text = link.text(),
                          meta = li.find('.date');

                      if ( $.trim( meta.text() ).length) {
                        var datetime = $.trim( meta.text() ).split(' :: '),
                            date = datetime[0].split('.');
                        meta.html('<span class="date">'+ date[0]+ '. ' + months[(date[1]-1)] + ' ' + date[2] +'</span><span class="time">, Kl '+ datetime[1] +'</span>');
                      }

                      link.remove();
                      $('<span class="tweet"/>')
                          .text( text.replace(/^.+?:/, '') )
                          .linkify()
                          .prependTo( li )
                    });
        } else {
          $(this).find('.boxbody').text( isIS ? '- Sambandsleysi við twitter' : '- Error connecting to twitter')
        }
      });


    //init flickr badge
    $('.flickrbox > .boxbody').Req( 
      Req.localPath+'js/jflickrfeed.js',
      function() {
        $(this).find('.placeholder').each(function(){
            var placeholder = $(this);

            $('<ul class="thumbs" />')
                .jflickrfeed({
                    limit: placeholder.attr('count'),
                    qstrings: { id: placeholder.attr('user') },
                    itemTemplate: '<li><a rel="colorbox" href="{{link}}" title="{{title}}"><img src="{{image_s}}" alt="{{title}}" /></a></li>'
                  }, function(data) {
                    var directlink = data.link;
                    $(this).closest('.box').find('.boxhead').wrapInner('<a href="'+ directlink +'" />')
                  }
                )
                .insertBefore(placeholder);
            
            placeholder.remove();
          });
      }
    );


    //sitemap collapser
    $('.sitemap').Req('treecollapse', function() {
        $(this).treeCollapse({
            branch: 'li:has(ul)',
            doTogglers: 1,
            toggler: '> a.expand',
            startOpen: 'ul.level1 > li:has(ul)'
          });
        });



    //remove CSS flicker trick
    if ( removeNoFlickerCSS )
    {
      $('#noflickerCSS').remove();
    }


    // labelize search input
    $('#qstr').labelizor()
        .bind('focus', function (e) {
            $('#pg-search').addClass('pgs-focus');
          })
        .bind('blur', function (e) {
            $('#pg-search').removeClass('pgs-focus');
          });

    // validate all forms
    $('form').autoValidate();

    if (!window.EPLICA_loggedin)
    {
      $('.netfang').mailtoEnabler();
    }

    //login hacks
    if (window.EPLICA_loggedin)
    {
      $('body.onecol .snav').prependTo( $('.pgfoot > .wrap') ).show();
    }

    /* some facebook testing
    var fbelm = document.getElementsByTagName('fb:like-box');
    window.fbAsyncInit = function() { FB.init({appId: '119099181450173', status: true, cookie: true, xfbml: true}); };
    $(fbelm).Req( document.location.protocol + '//connect.facebook.net/en_US/all.js' );
    */


  }
);
// **** /jqreq *****
