$(document).ready(function() {

  /* IE fix for news image on homepage */
  $('.img-home').css('margin:0 6px');

  $('#stentor_basket-addressform .button-order').click(function() {
      $(this).parents('form').submit();
  });

  $('button[name=print]').click(function() {
      print();
      return false;
  });

  function support_group_click(a)
  {
      var current_item = $(a).parents('.support-group');

      var found_div = false;

      $('.support-group').each(function() {
          if(found_div == true) $(this).remove();
          if($(current_item).hasClass($(this).attr('class').split(' ').slice(-1))) found_div = true;
      });

      /* IE fix for the position of the round border when items are toggled */
      if($.browser.msie) {
          $('img.round-border', $(current_item).parents('.round-content')).css('bottom', 0+'px');
          $('img.round-border', $(current_item).parents('.round-content')).css('bottom', -2+'px');
      }

      $.ajax({
        url: $(a).attr('href')+'/json',
        type: 'POST',
        data: '',
        dataType: "json",
        timeout: 4000,
        error: function() { 

        },
        success: function(data)
        {
            $(a).addClass('active');
            $(current_item).after(data.html);

            /* IE fix for the position of the round border when items are toggled */
            if($.browser.msie) {
                $('img.round-border', $(current_item).parents('.round-content')).css('bottom', 0+'px');
                $('img.round-border', $(current_item).parents('.round-content')).css('bottom', -2+'px');
            }

            var added_content = $(current_item).next();
            $('li a', added_content).click(function() {
              if(!$(this).parents('.support-group').hasClass('treelevel-6')) return support_group_click(this);
            });
        }
      });
      return false;
  }

  $('.support-group li a').click(function() {

        return support_group_click(this);
  });


  $('.focus').focus();

  /* clear default value on focus */
  $('.def_value').focus(function() {
      if(($(this).attr('id') == 'stentor_form-q') && (($(this).attr('value') != 'Trefwoord(en)') && ($(this).attr('value') != 'trefwoord(en)'))) return;
      if ( $(this).val() == this.defaultValue) $(this).val('');
  });
  /* reset default value on focus lose */
  $('.def_value').blur(function() {
      if ( $(this).val() == "") $(this).val(this.defaultValue);
  });

  /* makes an href container clickable */
  $('.clickable-container').click(function() {
      if($('a', this).attr('target') == '_blank') {
          window.open($('a', this).attr('href'), "Lobeco");
      } else {
          window.location = $('a', this).attr('href');
      }
  });

  /* makes an href container's sister clickable */
  $('.clickable-sister').click(function() {
      if($('a', $(this).parent()).attr('target') == '_blank') {
          window.open($('a', $(this).parent()).attr('href'), "Lobeco");
      } else {
          window.location = $('a', $(this).parent()).attr('href');
      }
  });

  /* expands / collapses menus */
  var initialmenu = null;
  var initialsubmenu = null;
  $('#topmenu li.active').each(function() { initialmenu = this; });
  $('#topmenu li ul.active').each(function() { initialsubmenu = this; });
  $('#topmenu > ul > li').hover(function() {
      $('#topmenu li').removeClass('active');
      $('#topmenu li ul').removeClass('active');
      $('ul', this).addClass('active');
  }, function() { $('ul', this).removeClass('active'); $(initialmenu).addClass('active'); $(initialsubmenu).addClass('active'); });

   /* AJAX login */
  $('#stentor_loginform').submit(function() {
    var login_form = this;
    //$('input[type=submit]', this).before('<img class="ajax-loader" src="/style/ajax-loader.gif" alt="Loading..." title="Loading..." />').remove(); 
    $('.ajax-loader', login_form).show();
    $('input[type=submit]', login_form).hide();
    var data = {'stentor_user-login': true, name: $('input[name=name]', this).val(), password: $('input[name=password]', this).val(), current_url: $('input[name=current_url]', this).val()};
    $.ajax({
      url: $(login_form).attr('action'),
      type: 'POST',
      data: data,
      dataType: "json",
      error: function() { 
        //$('.ajax-loader', login_form).before('<input type="submit" class="button" value="Log in"/>').remove(); 
        $('.ajax-loader', login_form).hide();
        $('input[type=submit]', login_form).show();
      },
      success: function(data)
      {
        if (data && data['result']=='success') {
          window.location = data['redirect'];
        }
        if (data && data['result']=='failure') {
            if (data['msg']) { $('p.msg', login_form).html(data['msg']); }
            $('.ajax-loader', login_form).hide();
            $('input[type=submit]', login_form).show();
        }
      }
    });
    return false; 
  });

   /* AJAX call me */
  $('#callform').submit(function() {
    var callform = this;
    //$('input[type=submit]', this).before('<img class="ajax-loader" src="/style/ajax-loader.gif" alt="Loading..." title="Loading..." />').remove(); 
    $('.ajax-loader', callform).show();
    $('input[type=submit]', callform).hide();
    var data = {'stentor_contact-call': true, 
                current_url: $('input[name=current_url]', this).val(), 
                name: $('input[name=name]', this).val(), 
                phonenumber: $('input[name=phonenumber]', this).val(), 
                subject: $('input[name=subject]', this).val(), 
                date: $('select[name=date]', this).val(), 
                time: $('select[name=time]', this).val()};
    $.ajax({
      url: $(callform).attr('action'),
      type: 'POST',
      data: data,
      dataType: "json",
      error: function() { 
        $('.ajax-loader', callform).hide();
        $('input[type=submit]', callform).show();
      },
      success: function(data)
      {
        if (data && data['result']=='success') {
          window.location = data['redirect'];
        }
        if (data && data['result']=='failure') {
            if (data['msg']) { $('p.msg', callform).html(data['msg']); }
            $('.ajax-loader', callform).hide();
            $('input[type=submit]', callform).show();
        }
      }
    });
    return false; 
  });

  /* displays description of icons displayed in article tables */
  $('table.articles td.icons').hover(function() {
      $('.description', this).show();
  }, function() {
      $('.description', this).hide();
  });

  /* lightbox */
  var lightboxparams = {
      overlayBgColor: '#808080',
      overlayOpacity: 0.6,
      imageLoading: '/style/lightbox-ico-loading.gif',
      imageBlank: '/style/lightbox-blank.gif',
      imageBtnClose: '/style/lightbox-btn-close.gif',
      imageBtnPrev: '/style/lightbox-btn-prev.gif',
      imageBtnNext: '/style/lightbox-btn-next.gif'
  };

  $('a.lightbox').lightBox(lightboxparams);

  /* faq toggle answers */
  $('dt').click(function() {

      $('dt img').attr('src', '/style/collapse.png').attr('title', 'Collapsed');

      var activate = false;
      if(!$(this).hasClass('active')) {
          $('img', this).attr('src', '/style/expand.png').attr('title', 'Expanded');
          activate = true;
      } else {
          $('img', this).attr('src', '/style/collapse.png').attr('title', 'Collapsed');
      }
      

      $('dt').removeClass('active');
      $('dd').removeClass('active');

      if(activate == true) $(this).addClass('active').next().addClass('active');

      /* IE fix for the position of the round border when items are toggled */
      if($.browser.msie) {
          $('img.round-border', $(this).parents('.round-content')).css('bottom', 0+'px');
          $('img.round-border', $(this).parents('.round-content')).css('bottom', -2+'px');
      }
  });


  /* add to order */
  $('.add-to-basket .add-item-to-basket').click(function() {
        var baskettype = null;
        if($(this).hasClass('button-order')) baskettype = 'order';
        if($(this).hasClass('button-quotation')) baskettype = 'quotation';

        var theform = $(this).parent();
        var data = '';

        $('input[name=q]', theform).each(function() {
            var docid = $(this).next().val();
            var q = $(this).val();

            if(q > 0) {
                if(data == '') {
                    data+= '"'+docid+'":'+q
                } else {
                    data+= ',"'+docid+'":'+q
                }
            }
        });
        data = '{'+data+'}';

        if(baskettype == 'order') {
            $('#info-basket-order').html('<img class="ajax-loader" src="/style/ajax-loader.gif" alt="Loading..." title="Loading..." />');
            $('#info-basket-order-total').html('<img class="ajax-loader" src="/style/ajax-loader.gif" alt="Loading..." title="Loading..." />');
        } else {
            $('#info-basket-quotation').html('<img class="ajax-loader" src="/style/ajax-loader.gif" alt="Loading..." title="Loading..." />');
        }

        $.ajax({
          url: '/'+$('body').attr('class')+'/basket/'+baskettype+'/add/article/'+data,
          type: 'POST',
          data: data,
          dataType: "json",
          error: function() { 
              if(baskettype == 'order') {
                  $('#info-basket-order').html('??'); 
                  $('#info-basket-order-total').html('??'); 
              } else {
                  $('#info-basket-quotation').html('??'); 
              }
          },
          success: function(rdata)
          {
            if(baskettype == 'order') {
                $('#info-basket-order').html(rdata['amount']);
                $('#info-basket-order-total').html(rdata['total']);
            } else {
                $('#info-basket-quotation').html(rdata['amount']);
            }
            $('input[type=text]', theform).val('0');
          }
        });
  });

  /* add quantity to form action (order basket) onsubmit */
  $('form.update-basket-item-quantity').submit(function() {
      var parentrow = $(this).parents('tr');
      $(this).attr("action", $(this).attr("action")+"/"+$('input[name=q]',parentrow).attr("value"));
  });

  /* assigning different stylesheet for printpreview */
  $('a[href=#print]').click(function() {
    print_preview();
    return false;
  });


  $('a[href=#swe-start-edit]').click(function() {
    $('img.round-border').css('bottom', -2+'px');
  });

});

function setActiveStyleSheet(title)
{
  $('link').each(function() {
    if ($(this).attr('rel').indexOf('style') != -1 && $(this).attr('title')) {
      $(this).attr('disabled', true);
      if ($(this).attr('title') == title) {
        $(this).attr('disabled', false);
      }
    }
  });
}

function print_preview()
{
    setActiveStyleSheet('print-preview');
}

function cancel_print_preview()
{
    setActiveStyleSheet('default');
}
