// 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(
  'autovalidate',
  'eutils',
  'fickle',
  'curtain',
  'easing-mini',
  'equalizeheights',
  'fontsizer',
  'imgpop',
  'labelizor',
  'mailtoenabler',
  'x/ifixpng',

  function(){
    var $ = jQuery;

    // labelize search input
    $('#qstr').labelizor();

    $('#noflickerCSS').remove();

    if (!window.EPLICA_loggedin)
    {
      $('.box .boxhead').wrapInner('<span />');
      
      $('body.home').each(function(){
          $('div.box-1_4 > .boxbody', this).equalizeHeights();
        });

      //nasty articlelist/article module hack
      $('body.namskeid:not(.milli)').each(function() {
        
          var titleText = $.trim( $('div.titlebox').text() );
          var selector = $('.namskeidlist', this).length ? 'div.titlebox, div.breadcrumbs' : '';
        
          $(selector).remove();
        
          $('div.catlist li').each(function(){
              if ( $(this).text().indexOf(titleText) >= 0 ) 
              {
                $(this).addClass('active');
              }
            });
        });

      $('.catlist li')
          .bind('mouseenter', function (e) {  $(this).addClass('hover');  })
          .bind('mouseleave', function (e) {  $(this).removeClass('hover');  })
          .bind('click',      function (e) {  window.location = $(this).find('a').attr('href');  return false;  });


      $('div.article').each(function(){
          var article = $(this);

          //popup in articles
          $('div.imagebox a.img', article)
              .each(function() {
                  var link = $(this);
                      imgSrc = link.find('img').attr('src').replace(/\/[^\/]+\/([^\/]+)$/, '/large/$1');
                  link.attr('href', imgSrc)
                })
              .imgPopper({
                  curtainColor : '#000000',
                  curtainOpacity : '0.75'
                });
                
          $('.summary', article).each(function(){
              var summary = $(this);
              if (/^\s+$/.test( summary.text() ) || summary.text() === '' )
              {
                summary.remove();
              }
            });


          $('img.banner', article)
              .insertBefore(article)
              .wrap('<div class="imgbanner" />')
              .after('<span class="frame" />');
          
          var ktHeads = $('h4.kennslutimar', article);
          if ( ktHeads.length ) {
            ktHeads.eq(0).nextUntil('div, h2, h3, p.buttons').andSelf().wrapAll('<div class="kt-box" />').parent().prepend('<h2>Kennslutímar</h2>');
            ktHeads.each(function(){
                        $(this).nextUntil('h4.kennslutimar, div, h2, h3, p.buttons').andSelf().wrapAll('<div class="kt-inner" />');
                        var h5 = $(this).parent().find('h5');
                        h5.before('<img src="/media/starfsmenn/tiny/'+ h5.text() +'.jpg" alt="" />').remove();
                      })
                    .filter(':last').parent().addClass('last');
          }
          
        });



      //stafflist funk
      $('div.people td:not(.netfang) a').click(function() { return false; })
      $('#filter').prependTo('div.people > .boxbody');

      //init calendars
      $('.monthlist').Req('/bitar/common/calendar/calendarPager.js', function(){
          var initCalendars = function ( e ) {
              $(this).find('.dateinfo')
                  .hide()
                  .parent()
                  .bind('mouseenter focusin', function(e){
                      $(this).find('div.dateinfo')
                          .stop()
                          .css({ opacity : 1 })
                          .css({ height : 'auto' })
                          .css({ width : 'auto' })
                          .show(200, 'easeOut');
                    })
                  .bind('mouseleave focusout', function(e){
                      $(this).find('div.dateinfo')
                          .stop()
                          .css({ opacity : 1 })
                          .css({ height : 'auto' })
                          .css({ width : 'auto' })
                          .hide(200, 'easeIn');
                    });
            };

          this
              .eplicaCalendarLoader()
              .bind('reload', initCalendars);

          initCalendars.call(this);
        });



      // autofill and hide "ruslpóstur" traps
      $.fn.spm_answer = function () {
          this.find("input#spm_answer")
              .each(function(){
                  try { // try because eval() below may throw an error
                    var input = $(this),
                        sum = eval(
                                  input.prev('label').text()
                                    .replace(/^\D*(\d+)(\D+?)(\d+)\D*$/,'$1+$3')
                                );
                    input.val(sum);
                    if ( typeof sum == 'number' )
                    {
                      input.parent().hide()
                    }
                  } catch (e) { }
                });
          return this;
        };

      //popup windows
      $.fn.popup = function () {
          var popupElm = this;
          if ( popupElm.length) { 
            var curtainElm = $.curtain({
                        className: 'popup-curtain',
                        bg:        '#404040',
                        opacity:   .90,
                        fixed:     true
                      });
            popupElm
                .hide()
                .appendTo('body')
                .addClass('popupblock')
                .prepend('<a class="focustarget" href="#">#</a>')
                .append('<a class="close" href="#">Loka</a>')
                .before(curtainElm)
                .css({ marginLeft: - $.toInt( popupElm.outerWidth() ) / 2 })
                .fickle({
                    fadein: 350,
                    onOpen:   function (e) { $(this).css({ top: 30 + $(window).scrollTop() }).prev().fadeIn(100)  },
                    onClose:  function (e) { popupElm.fadeOut(200, function() { $(this).prev().fadeOut(100); }) },
                    onClosed: function (e) {  }
                  })
                .find('a.close')
                    .bind('click', function (e) {
                        popupElm.fickle('close');
                        return false;
                      })
                .end()
                .fickle('open');
          }
          return popupElm;
        };


      //popup notify boxes
      $('div.notify').popup();

      //contactform ajax
      $('li.senda a, li.uppl a, a.senda, a.ajaxpop')
          .bind('click', function (e) {
              var link = $(this),
                  popupForm = link.data('popupForm'),
                  wideClass = link.is('.ajaxpop') ? 'widepop' : '';
              if (popupForm)
              {
                popupForm.fickle('open');
              }
              else
              {
                $.get(
                    link.attr('href'),
                    { justPicPos: 'pgmain' },
                    function(data){
                        var popData = $(data).find('div.box:first');
                        popData
                          .addClass(wideClass)
                          .removeClass('article')
                          .find('p.buttons').remove().end()
                          .popup()
                          .find('form')
                              .autoValidate()
                              .spm_answer();
                        link.data('popupForm', popData); // store for later
                      }
                  );
              }
              return false;
            });


      //Námskeiða filter
      $('.umsokn').Req('http://codecentre.eplica.is/concat/?utils_1.1.js;fieldsetcloner_1.0.js', function(){
          var namskeid = $(this).find('.namskeid'),
              checkboxes = namskeid.find('td.fi_chk input'),
              selectboxes = namskeid.find('select'),
              filtered,
              cartstatus = $('#cartstatus');

          //filter tabs
          $('h2', namskeid).after('<ul class="filtertabs"><li><a id="showall" href="#">Sjá öll námskeið</a></li><li><a id="showfiltered" href="#">Sjá valin námskeið</a></li></ul>');

          //hide not selected
          $('#showfiltered')
              .bind('click', function() {
                  checkboxes.closest('tr')
                      .hide()
                      .filter(':has(input:checked)')
                          .show();

                  namskeid.find('.group')
                      .not(':has(input:checked)')
                          .hide()
                      .end()
                      .removeClass('box-left')
                      .filter(':visible:even')
                          .addClass('box-left');

                  $('#showall').removeClass('active');
                  $(this).addClass('active');
                  namskeid.find('.info').text('Hér má sjá öll námskeið sem hafa verið valin');
                  filtered = true;
                  return false;
                });

          //show all selectable
          $('#showall')
              .bind('click', function() {
                  namskeid.find('.group')
                      .show()
                      .removeClass('box-left')
                      .filter(':even')
                          .addClass('box-left')
                      .end()
                      .find('tr')
                          .show();
                  $(this).addClass('active');
                  $('#showfiltered').removeClass('active');
                  $('.info', namskeid).text('Hér má sjá öll námskeið sem eru í boði');
                  filtered = false;
                  return false;
                });

          //show everything if nothing has been selected
          checkboxes.filter('input:checked').length ?
              $('#showfiltered').trigger('click'):
              $('#showall').trigger('click');


          //select change handler
          selectboxes
              .bind('change', function() {
                  $(this).val() ? 
                      $(this).closest('tr').find('input:checkbox').attr('checked', true).trigger('change') : 
                      $(this).closest('tr').find('input:checkbox').attr('checked', false).trigger('change');
                });


          //checkbox handler
          checkboxes
              .bind('change', function() {
                  var checkBox = $(this),
                      trow = checkBox.closest('tr'),
                      group = checkBox.closest('.group');

                  if (!this.checked  &&  filtered)
                  {
                    $('#showfiltered').trigger('click');
                  }
                  trow.find('td.fi_sel').toggleClass('req');
                  trow.find('option:first').html( this.checked ? 'Veldu röð' : '' ).filter(function(){ return checkBox.attr('checked') == false }).attr('selected', 'selected');

                  //skila villu ef fleiri en 3 námskeið eru valin
                  checkboxes.filter(':checked').length < 4  ?
                      $('#error').remove() :
                      !$('#error').length ? //if more than 3 are selected and no error message present do...
                          $('.group:first', namskeid).before('<div id="error" class="errorbox"><strong>ATH:</strong> Eingöngu er hægt að velja 3 námskeið.</div>') :
                          undefined;
                    
                  //Skila villu ef sama priority er valið 2x eða oftar
                  var prioritySelected = [],
                      selectwithvalue = selectboxes.filter(function() { return $(this).val() });
                  selectwithvalue.each(function() { prioritySelected.push( $(this).val() ) });
                  prioritySelected.sort();

                  $('#error2').remove();
                  for (var i=0; i<prioritySelected.length; i++) 
                  {
                    if( prioritySelected[i] == prioritySelected[i-1] && !$('#error2').length ) 
                    {
                      $('.group:first', namskeid).before('<div id="error2" class="errorbox"><strong>ATH:</strong> Eingöngu er hægt að velja sama forgang einu sinni.</div>');
                    }
                  }
                  
                  
                  //cartstatus sillyness
                  if ( cartstatus.length ) 
                  {
                    if ( checkBox[0].checked ) 
                    {
                      cartstatus.show().find('ul').append('<li class="'+ checkBox.attr('id') +'"><a>'+ checkBox.next().text() +'</a></li>');
                    } 
                    else 
                    {
                      cartstatus.find('.' + checkBox.attr('id') ).remove();
                      if( !cartstatus.find('li').length ) 
                      {
                        cartstatus.hide();
                      }
                    }
                  }
                  
                  
                })
              .each(function() {
                  var trow = $(this).closest('tr');
                  this.checked ?
                      trow.find('td.fi_sel').addClass('req'):
                      trow.find('option:first').html('');
                });


          //clone time fields
          fieldsetCloner.config['fieldset.cloneable'] = {
            addBtnTemplate : '<div class="addDate"><a id="addDate" href="#" title="Bæta við auka kennsludegi">Bæta við kennsludegi</a></div>',
            rowName : 'kennslutimi'
          }
          fieldsetCloner.init();

          $('#addDate')
              .bind('click', function() {
                  var link = $(this);
                  setTimeout(function(){ // Delay because when mixing utils_1.1 and jQuery event handlers we can't ensure that handlers run in the correct order.
                      if ( !link.parent().prev().find('a.remove').length ) {
                        link.parent().prev().append('<a class="remove" href="#">Fjarlægja dag</a>');
                      }
                    }, 200);
                })
              .parent().parent()
                  .bind('click', function (e) {
                      var link = $(e.target);
                      if (link.is('a.remove')) // delegated event handling
                      {
                        link.closest('fieldset').remove();
                        return false;
                      }
                    });


          //custom req check
          $(checkboxes[0]).closest('form')
              .bind('submit', function (e) {
                  if ( !e.isDefaultPrevented() )
                  {
                    if (!checkboxes.filter(':checked').length)
                    {
                      namskeid.find('.group:first').before('<div id="error" class="errorbox"><strong>ATH:</strong> Vinsamlega veldu <acronym title="að minnsta kosti">a.m.k.</acronym> eitt námskeið.</div>');
                    }
                    var errorMsg = $('#error');
                    if (errorMsg.length)
                    {
                      alert( errorMsg.text() );
                      errorMsg.setFocus();
                      return false;
                    }
                    var errorMsg2 = $('#error2');
                    if (errorMsg2.length)
                    {
                      alert( errorMsg2.text() );
                      errorMsg2.setFocus();
                      return false;
                    }
                  }
                });

        }); // End námskeið


      // pngfix for IE6
      if ($.browser.msie && $.browser.version < 7) {
        $('img[src$=".png"]').ifixpng();
      }
      //enable mailto links
      $('.netfang').mailtoEnabler();

      $('.pagestyle').fontsizer();
      $('form')
          .autoValidate()
          .spm_answer();
    }

  }
);
// **** /jqreq *****

