// encoding: utf-8
/*@cc_on/*@if(@_jscript_version<5.7)try{document.execCommand('BackgroundImageCache',0,1)}catch(e){}/*@end@*/

Req.localPath = Req.localPath || '/skin/basic/';

Req(
  'autovalidate',
  'curtain',
  'eutils',
  'equalizeheights',
  'fickle',
  'fontsizer',
  'imgpop',
  'listscroller',
  'mailtoenabler',
  'ontime',
  'simplecarousel',
  'tabswitcher',
  'twitterize',
  //'x/resize',
  Req.localPath+'js/jquery.popupdiv.js',
  
  function(){
    var $ = jQuery,
        body = $('body').addClass('js-active');


    var texts = {
        is: {
            moreText  : 'Meira',
            lessText  : 'Minna',

            contactus : 'Hafðu samband',
          
            closeText : 'Loka glugga',

            totopText : 'Aftur upp',

            nextText  : 'Fletta áfram',
            prevText  : 'Fletta til baka',
            nextTitle : 'Næsta verkefnasíða',
            prevTitle : 'Fyrri verkefnasíða',
            ofText    : ' af '
          },
        en: {
            moreText  : 'More',
            lessText  : 'Less',

            contactus : 'Contact us',
          
            closeText : 'Close popup',

            totopText : 'Back to top',

            nextText  : 'Next page',
            prevText  : 'Previous page',
            nextTitle : 'Next page',
            prevTitle : 'Previous page',
            ofText    : ' of '
          }
      };
    texts = texts[ $.lang() ]  ||  texts.en;


    // *** subscr popupdiv
    var subscr = $('.subscr'),
        spop = subscr.find('> form.boxbody')
                          .popupdiv()
                              .parent()
                                  .addClass('subscr-popup')
                                  .hide();

    subscr
        .after( spop )
        // fix the subscr box on the frontpage after the popupdiv has been built
        .append('<div class="boxbody">'+
                  '<p class="more moreolder">'+
                    '<a href="#subscr_popup">' + spop.find('p.desc').text() + '</a>'+
                  '</p>'+
                '</div>')
        .find('.moreolder a')
            .click(function(e){
                spop.pop();
                return false;
              });


    // extras link/links that can open the popup
    $('.quicknav .cat3 a')
        .attr('href', '#')
        .click(function(){
            spop.pop();
            return false;
          });



    if( $('html').attr('lang') == 'is' )
    {
      // *** contact popup (with the tabswitch)
      $('.pgfoot .subscr').remove(); // throw the box away as we use a different link as trigger

      var contactbox = $('#cp_tel, #cp_email, #cp_call')
                            .wrapAll('<div class="contactbox" />')
                            .parent()
                                .popupdiv(),
          contactpop = contactbox
                          .parent()
                              .addClass('contact-popup')
                              .hide();

      $('.footer .boxbody')
          .append(
            $('<div class="act"><a href="#" class="contact">'+ texts.contactus +'</a></div>')
              .click(function(){
                contactpop.pop();
                return false;
              })
          );
      contactbox.prepend( $('.contactnav') );
      
      var fform = $('.fform')
                      .wrap('<div class="contactbox" />')
                            .parent()
                                .popupdiv(),
          feedbackpop = fform
                          .parent()
                              .addClass('contact-popup feedback-popup')
                              .hide();
              
      $('.feedback a').bind('click', function (e) {
          feedbackpop.pop();
          return false;
        });
    }




    // *** companyinfo browser - New articlelist version
    
    // *** logolisti (middle images on y-axis)
    $('.companylogolist .item img, .companyarticle .imagebox img')
        .each(function(){
            $(this)
              .css('backgroundImage', 'url(' + this.src + ')')
              .attr('src', '/skin/basic/design/i/blank.gif'); // inn á servernum á að vera '/skin/basic/design/i/blank.gif'
          });



    // *** logolisti (carousel wrappers)
    var cl = $('.companylogolist .boxbody').not('.portfolio .companylogolist .boxbody'),
        clItm = cl.find('.item');

    if (clItm.length > 8) 
    {

      var cul = $('<div class="itmwrap" />');
      clItm.each(function(i){

          if (i % 8 == 0) {
            cul = $('<div class="itmwrap" />');
            $( this ).parent().append( cul );
          }
          cul.append( this );

        });

      cl.find('.itmwrap:not(:has(.item))').remove();

      cl.listscroller({
            item       : '.itmwrap',
            aspect     : 'horizontal',
            paging     : true,
            statusPager: false,
            jumpPager  : true,
            animation  : 'carousel',
            windowSize : 1,
            stepSize   : 1,
            speed      : 600,
            easing     : 'swing',
            ofTotalSeparator  : texts.ofText,
            labelNext  : texts.nextText,
            labelPrev  : texts.prevText,
            statusLabel: texts.pageText,
            titleNext  : texts.nextTitle,
            titlePrev  : texts.prevTitle
        });

    }



    
    $('.companyarticle .boxbody').each(function(){
        var ca = $(this),
            thumblist =  ca.find('.imagelist'),
            firstImgSrc = thumblist.find('a:first').attr('href');
        
        ca.find('h1').after('<div class="fullsizeimg"><div class="image"><img src="'+ firstImgSrc +'"></div></div>');
        thumblist.find('li:first').addClass('current');

        var setImg = function ( thumbitem, ldesc )
                      {
                        thumbitem.parents('.imagebox').find('.current').removeClass('current');
                        thumbitem.parents('li').eq(0).addClass('current');
                        
                        // make new fullimage
                        var alt   = thumbitem.find('img').attr('alt'),
                            title = thumbitem.find('img').attr('title'),
                            desc  = '',
                            src   = thumbitem.attr('href'),
                            newImg = $( '<div class="image"><span class="img"><img alt="' + alt + '" src="' + src + '"/></span></div>' );
                        
                        if ( title || desc ) {
                          var longdesc = $('<div class="longdesc"></div>');
                          newImg.append( longdesc );
                          if ( title ) {
                            longdesc.append( '<strong class="title">'+title+'</strong>' );
                          }
                          if ( desc ) {
                            longdesc.append( '<div class="desc">'+desc+'</div>' );
                          }
                        }
                        
                        newImg.hide();
                        ca.find( '.fullsizeimg .image:first') .before( newImg );
                        
                        var img = newImg.find('img');
                        var runner = function () {
                          ca.find( '.fullsizeimg .image:not(:first)' ).slideUp( 400, function () { $( this ).remove(); });
                          newImg.slideDown( 400 );
                        };
                        
                        $(img).load( runner );
                        return newImg;
                      },
            fullimage  = ca.find('.fullsizeimg .image'),
            // get thumbnails
            thumbs = thumblist.find('li'),
            // animate in
            delay = 0;
          
        thumbs.each(function (i) {
          var item = $(this);
          item.hide();
          
          setTimeout(function () {
            thumbs.eq(i).fadeIn();
          }, (70 * i));
          
          item.find('a').click(function () {
            if (!$(this).parent().is('.current')) {
              var thumb = $(this),
                  // has longdesc
                  desc = $('img', this).attr('longdesc');
              if (desc) {
                $.ajax({
                  type : 'GET',
                  url : desc,
                  dataType : 'text',
                  cache : true,
                  success : function ( ret ) { fullimage = setImg( thumb, '' ); }
                })
              }
              else {
                 fullimage = setImg( thumb, '' );
              }
            }
            return false;
          });
        });
        
        ca.find('p.more').clone().appendTo(thumblist);

        ca.find('> :last-child').filter(function() { return $(this).is('br') }).remove();

      });
      
      //Portfolio additions(extends logolist)
      if ( body.is('.portfolio') )
      {
        $('.companyinfo').append('<span class="backbtn"><a href="/portfolio">Til baka í yfirlit verkefna</a></span>');
      }




    //companyinfo tabswitcher
    $('.companyinfo-tabpane').makeTabbox().tabSwitcher({ showFirst: true, setFragment: false });

    // *** some other tabswitchers
    $('ul.tabs').tabSwitcher({ setFragment: false });


    /* *** article imagelist & galleries (carousel & lightbox) *** */
    $('.article .imagelist')
        .removeClass('imagelist')
        .wrap('<div class="imagelist" />')
        .find('a')
            .each(function(){
                var img = $('img', this)[0],
                    longDesc = $(this).parent().find('div.longdesc');
                img.title = longDesc.find('.title').text();
                img.alt   = longDesc.find('.descr').text();
              })
            .imgPopper()
        .end()
        .filter(function() { return $(this).find('li').length>1 })
            .simpleCarousel({
                // labelNext: '>>',
                // labelPrev: '<<',
                // wrap: true,
                item : 'li'
              });



    if (!window.EPLICA_loggedin)
    {
      body.filter('.home').find('.sbox-mappa').each(function(){
          var imgCont = $(this).find('.boxbody > div:first'),
              imgs = imgCont.find('a:has(img), img:not(:descof(a))').detach().get().sort(function(){ return Math.random()>.5 }),
              i = imgs.length;

          imgCont
              .addClass('crossfader-active')
              .empty()
              .append( imgs[0] )
              .ontime({
                  interval: 5000,
                  bubble:   false,
                  fn:       function (e) {
                                var lastimg = $(imgs[0]).fadeOut(500, function(){ $(this).detach(); });
                                imgs.push( imgs.shift() );
                                $(imgs[0])
                                    .hide()
                                    .appendTo( this )
                                    .fadeIn(500);
                              }
                });
        });

      $('.netfang').mailtoEnabler();
    }


    /* BEGIN: e2focus */
    body.filter('.home')
            //.Req(Req.localPath+'js/jquery.displaybox.js') - disabled, not in use
            .find('.e2focusbox').each(function(){
                var box = $(this),
                    ulElm = box.find('ul').fin(),
                    items = box.find('li').fin(),
                    realClick,
                    i = items.length-1;
                items
                    .each(function(){
                          $(this).find('a').append( $(this).find('i,em') )
                        })
                    .append('<span class="timer" />')
                    .find('i,em')
                        .hide()
                        .bind('mouseenter', function (e) { ulElm.ontime('pause', 'ticker'); })
                        .bind('mouseleave',  function (e) { ulElm.ontime('resume', 'ticker'); })
                        .bind('click', function (e) { e.stopPropagation(); })
                    .end()
                    .bind('click', function (e) { realClick = true;})
                    .bind('mouseover', function (e) {
                        var hoverElm = $(this);
                                hoverTimeout = setTimeout(function(){
                              hoverElm.trigger('click');
                            }, 500);
                    })
                    .bind('mouseout', function (e) {
                          clearTimeout(hoverTimeout);
                    })
                    .bind('click.switcher', function (e) {
                        var thisIdx = items.index(this);
                        if (thisIdx != i)
                        {
                          realClick  &&  ulElm.ontime('end', 'ticker');
                          i = thisIdx;
                          ulElm
                              .ontime({
                                  label:    'ticker',
                                  start:    0,
                                  interval: 1000,
                                  reps:     7,
                                  bubble:   false,
                                  fn:       function(e, count, cfg){
                                                (count===0)  &&  items.eq(i).addClass('current').find('i,em').fadeIn(900);
                                                ulElm.removeClass('tick-'+(count-1));
                                                (count < cfg.reps-1)  &&  ulElm.addClass('tick-'+count);
                                                (count == cfg.reps-2) && items.eq(i).find('i,em').fadeOut(900);
                                              },
                                  end:      function(e, cfg){
                                                items.eq(i).removeClass('current').find('i,em').hide();
                                                if (!realClick)
                                                {
                                                  var next = (i+1) % items.length;
                                                  setTimeout(function(){
                                                      items.eq(next).trigger('click.switcher');
                                                    }, 0);
                                                }
                                              }
                                });
                        }
                        realClick = false;
                        return false;
                      })
                    .eq(0)
                        .trigger('click.switcher')
                    .end()
                        .find('a')
                          .bind('click', function (e) { 
                                e.stopPropagation();
                            });

              });
    /* END: e2focus */




    // *** removeflicker
    $('#noflickerCSS').remove();



    // helper function that trims a html doc for use as jquery object
    jQuery.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 jQuery.trim( r ) || "";
    };


    $('.contactpane form, .fform form')
	       .bind('submit', function(e) {
	           var theForm = $(this);
	           if (theForm.isValid()) {
	             var action = theForm.attr('action') || document.location.toString().replace(/([?#].*)?$/, '');
	             $.post(action, theForm.serialize(), function(data) {
									var response = $( $.cleanDoc(data) ).find( '.pgmain .box:first .boxbody' );
									if ( /ekki svarað rétt/.test( response.text() ) ) {
										var ctrl = theForm.find( 'input[name=spm_answer]' ),
												msg = response.text(),
												lbl = ctrl.parent().find( 'label' ).text().replace( /(^[:*]|[:]$)/g, '' ),
                        cfId = theForm.closest('.contactpane').attr('id');
										//þurfum að uppfært spam field frá servernum... önnur form á síðu verða samt óvirk við þetta :S
										$.get(
													document.location,
													function(data) {
                            data = $.cleanDoc(data);
														var spm = $(data).find('#'+cfId+' .spm');
														spm.find('.fi_txt').addClass( 'typeerror' );
														theForm.find('.spm').after(spm).remove();
													}
												);
										alert( lbl + "\n\n" + $.trim( msg ) );
									 }
									 else {
										 var newDoc = response.html();
										 theForm.before('<div class="boxbody" id="response"><p>' + newDoc + '</p></div>');
										 theForm.remove();
									 }
								 });	
	           }
	           return false;
	         });


    /* *** postlisti ajax forms *** */
    $('.subscr-popup form')
        .bind('submit', function(e) {
            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('.subscr:first .boxbody').html();
                  window.newDoc = newDoc;
                  window.response = response;
                  theForm.before('<div class="boxbody" id="response"><p>' + newDoc + '</p></div>');
                  theForm.remove();
                }
                else
                {
                  var ctrl = theForm.find( 'input[name=VIS_Email]' ).closest( '.fi_txt' ),
                      lbl = ctrl.find( 'label:first' ).text().replace( /(^[:*]|[:]$)/g, '' );
                  ctrl.addClass( 'typeerror' );
                  alert( 'Þessir liðir eru rangt útfylltir:\n\n' + lbl );
                }

              });
            }
            return false;
          });




    // fix look for contactform in popup
    $('#cp_call, #cp_email').each(function(){
        $('.fi_txt', this).not('.fi_qty').wrapAll('<fieldset />');
      });


    // Listscroller
    $('.fbox > .boxbody')
        .filter(':has(.item)')
            .find('h3')
                .append('<a class="focustarget" href="#">.</a>')  // For accessibility
            .end()
        .end()
        .listscroller({
            item: '.item, li',
            paging: true,
            windowSize: 1,
            stepSize: 1,
            autoScrollDelay: 5000,
            animation: 'crossfade'
          });



    // Append More link, wrap detail info, hide detail info, set toggle function, etc. 
    var coreInfo =  $('.core-info');
    coreInfo.each(function() {
        if ($(this).children().not('.summary, .toggler, h2').length)
        {
          $(this)
              .append('<div class="toggler"><a href="#">'+ texts.moreText + '</a></div>')
              .children()
                  .not('.summary, .toggler, h2')
                      .wrapAll('<div class="details-toggle" />'); 
        } 
        else
        {
          $(this)
              .append('<div class="toggler"></div>');
        }

      });

    var details = coreInfo.find('.details-toggle');

    details.hide();
    coreInfo
        .find('.toggler a')
            .each(function(){
                var isOpen = false;
                $(this).bind('click', function (e) {
                    $(this)
                        .html(isOpen ?  texts.moreText : texts.lessText )
                        .parent()
                            .toggleClass('active')
                            .prev(details)
                                .toggle();
                    isOpen = !isOpen;
                    return false;
                  });
                
              });


    //focusnav triggers click on coreinfo toggler if it's not open already
    $('#focusnav li a').bind('click', function (e) {
        $( $(this).attr('href') )
            .filter(function() { return $(this).find('.details-toggle:visible').length == 0 })
                .find('.toggler a')
                    .trigger('click');
      });



    // Carousel - About
    var mq = $('.marquee');
    mq.filter('.about')
          .find('img')
              .each(function(){
                  $(this)
                    .css('backgroundImage', 'url(' + this.src + ')')
                    .attr('src', '/skin/basic/design/i/blank.gif'); // inn á servernum á að vera '/skin/basic/design/i/blank.gif'
                })
          .end()
          // Carousel init
          .find('li:nth-child(3n+3)')
              .css('margin-right','0')  //nth-child selector for IE which can't handle CSS3 for this.
          .end()
          .find('li:nth-child(3n+1) span')
              .css('display','block')  //nth-child selector for IE...
          .end()
          .find('.boxbody')
              .simpleCarousel({
                  item            : 'ul',
                  nextBtnTemplate : '<a href="#" class="next">'+ texts.nextText +'</a>',
                  prevBtnTemplate : '<a href="#" class="prev">'+ texts.prevText +'</a>',
                  wrap            : true
                });

  
    /* *** Lightbox from carousel *** */
    mq.find('ul')
          .wrap('<div class="imagelist" />')
          .find('a')
              .each(function(){
                  var img = $(this).find('img');
                })
              .imgPopper({
                  curtainColor : '#ffffff',
                  curtainOpacity : '0.75'
                });



    //popup windows
    $.fn.ajaxpop = function ( cfg ) {
        var popupElm = this;
        if ( popupElm.length) { 
          var curtainElm = $.curtain({
                      className: 'popup-curtain',
                      bg:        '#ffffff',
                      opacity:   .70
                    });
          popupElm
              .hide()
              .appendTo('body')
              .addClass('popupbox')
              .prepend('<a class="focustarget" href="#">#</a>')
              .before(curtainElm)
              .css({
                    top:        100 + $(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) {  }
                })
              .append('<a class="close" href="#">'+ texts.closeText +' <span>x</span></a>')
              .find('a.close')
                  .bind('click', function (e) {
                      popupElm.fickle('close');
                      return false;
                    })
              .end()
              .fickle('open');
        }
        return popupElm;
    };


    //Ajax - Any link with class "popup" will trigger the Ajax get event.
    $('a.popup')
        .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('.box:first');  // Gets the very first .box on the linked page.
                      popData.ajaxpop();
                      link.data('popupForm', popData); // store for later
                    }
                );
            }
            return false;
          });


    //Appends 'Back to Top' button to all English twocol subpages and sets the click event
    var scrollLink = $('<a style="display:none;" class="upward" href="#">'+ texts.totopText +'</a>');
    scrollLink
        .appendTo('.english.twocol .pgmain')
        .bind('click', function (e) {
            //$(window).scrollTop() = 0; This kept throwing errors.  Changed syntax.  See next line.
            $(window).scrollTop(0);
            e.preventDefault();
          });

    $(window)
        .bind('scroll', function (e) {
            if ($(window).scrollTop() != 0) {
              scrollLink.fadeIn(250);
            } else {
              scrollLink.fadeOut(250);
            }
          })
        .trigger('scroll');

    //Next prev buttons for "helstu lausnir"
    var sarr = $('.solnav li').hide();
      if ( $('.solnav').length )
      {
        sarr.each(function(){
          if ( $(this).find('a').attr('href') == window.location.pathname )
          { 
            $(this).next().show().addClass('next');
            $(this).prev().show().addClass('prev');
          }
        });
      }



    //init twitter widget
    $('.twitterbox .boxbody')
        .twitterize({  userName: 'eplica',  numTweets: 1  });


    // *** autoValidator
    if ($.av)
    {
      var excludes = $('#cp_email form, #cp_call form, .popup form, .qsearch form').get();
      $( 'form' ).not( excludes ).autoValidate();
    }

    //sitemap collapser
    $('.sitemap').Req('treecollapse', function() { 
        $(this).treeCollapse({ 
            branch: 'li:has(ul)', 
            doTogglers: 1, 
            toggler: '> a.expand',
            startOpen: 'ul.level1 > li:has(ul)'
          }); 
        });

    // *** fontsizer
    $('.pagestyle').fontsizer();
  }
);




