$(document).ready(function() {

  $('.focus').focus();

  $('.add_to_order .button').click(function() {
    var submitbutton = this;
    var self = $(this).parents('form');
    var add_to_order_snippet = self;
    var quantity = $('input[type=text]', $(this).parent());
    var initial_quantity = $(quantity).attr("defaultValue");
    var q = $(quantity).val();

    $('img', $(quantity).parents('form')).hide();

    //q = parseInt(q, 10);
    //if (!q || q<0 || q.toString(10)!==$(quantity).val()) {
    //  $(quantity).val('???');
    //  $(quantity).focus();
    //  return false;
    //}
    var info = $('#info-basket-order');
    var infototal = $('#info-basket-order-total');
    info.html('<img src="/style/ajax-loader.gif"/>');
    infototal.html('<img src="/style/ajax-loader.gif"/>');
    quantity.after('<img src="/style/accept.gif" style="display: inline;">').fadeIn('slow');
    ajax_timeout = setTimeout(function() {
      $('img', $(quantity).parents('form')).fadeOut('slow');
    }, 3000);

    $.ajax({
      url: $(self).attr('action') + '/' + q,
      type: 'POST',
      data: {'returntype':'json'},
      dataType: "json",
      error: function() { 
        info.html('??'); 
        infototal.html('??'); 
      },
      success: function(data)
      {
        if (data['result']==1) {
          info.html(data['articlecount']); 
          infototal.html(data['basket_subtotal']); 
          //$(theform).html(formhtml);
        }
        else {
          info.html('??'); 
          infototal.html('??');
        }
        $(quantity).val(initial_quantity);
        $('.loader', add_to_order_snippet).remove();
        $(submitbutton).removeClass('busy');
      }
    });
    return false; 
  });

  // var holds height of largest segment (/catalog)
  var max_height = 0;

  /* gives all segments (/catalog) the same height */
  $('#content ul.segments').each(function() {
      if(max_height < $(this).height()) max_height = $(this).height();
  });
  $('#content ul.segments').each(function() {
      var leftover = 0;
      if(max_height > $(this).height()) {
          $('.last', this).before('<li class="dummy" style="height: '+(max_height-$(this).height())+';"></li>');
      }
  });

  /* round corners of snippets */
  $('.snippet').prepend('<img class="top" src="/style/snippet_top.png" alt=""/><img class="bottom" src="/style/snippet_bottom.png" alt=""/>');

  /* clear default value on focus */
  $('.def_value').focus(function() {
    if ( $(this).val() == this.defaultValue) $(this).val('');
  });

  // faq toggle answers
  $('dt').click(function() {
      var dt = this;

      if($(dt).hasClass('active')) {
          $('dt').removeClass('active');
          $('dd').removeClass('active');

          $(dt).removeClass('active');
          $(dt).next().removeClass('active');
      } else {
          $('dt').removeClass('active');
          $('dd').removeClass('active');

          $(dt).addClass('active');
          $(dt).next().addClass('active');
      }
  });

  /* reset default value on focus lose */
  $('.def_value').blur(function() {
    if ( $(this).val() == "") $(this).val(this.defaultValue);
  });

  /* custom selects */
  $('.select').click(function() {
      var cur_select = this;

      if((!$(this).data('open')) || ($(this).data('open') == false)) {
          $(this).data('open', true);
      } else {
          $(this).data('open', false);
      }
      $('.custom_select').each(function() {
          $(this).hide();
      });

      if($(this).data('open') == true) {
          $(cur_select).next().show();
      } else {
          $(cur_select).next().hide();
      }
  });

  $('#dealer_form select').change(function() {
      value = $(this).val();
      $('option', this).each(function() {
          if($(this).val() == value) {
              $(this).parent().prev().html($(this).html());
              $(this).parent().next().attr("value", $(this).val());
          }
      });
      $(this).hide();
      $(this).prev().data('open', false);
  });

  /* custom radiobuttons */
  $('.search-results label img').click(function() {
      var id = $(this).attr("id");
      id = id.replace("filter-", "");

      var button = this;
      var pid = $(this).parent().parent();

      $('.search-results label img').each(function() { 
        $(this).attr("src","/style/radio-button.png"); 
        $(this).removeClass('checked');
      });
      $(button).addClass('checked'); 
      $(button).attr("src","/style/radio-button-selected.png"); 
      $('#search-filter', pid).val(id);
    }
  )

  $('.search-results label').click(function() {
      var id = $('img', this).attr("id");
      id = id.replace("filter-", "");

      var button = this;
      var pid = $(this).parent();
      $('img', '.search-results').each(function() { 
        $(this).attr("src","/style/radio-button.png"); 
        $(this).removeClass('checked');
      });
      $('> img', button).addClass('checked'); 
      $('> img', button).attr("src","/style/radio-button-selected.png"); 
      $('#search-filter', pid).val(id);
    }
  )

  $('#contact_form-gender_choices label img').click(function() {
      var id = $(this).attr("id");
      id = id.replace("contact_form-gender_choices-", "");

      var button = this;
      var pid = $(this).parent().parent().parent();

      $('#contact_form-gender_choices label img').each(function() { 
        $(this).attr("src","/style/radio-button.png"); 
        $(this).removeClass('checked');
      });
      $(button).addClass('checked'); 
      $(button).attr("src","/style/radio-button-selected.png"); 
      $('#contact_form-gender', pid).attr("value", id);
    }
  )

  $('#contact_form-gender_choices label').click(function() {
      var id = $('img', this).attr("id");
      id = id.replace("contact_form-gender_choices-", "");

      var button = this;
      var pid = $(this).parent().parent();
      $('img', '#contact_form-gender_choices').each(function() { 
        $(this).attr("src","/style/radio-button.png"); 
        $(this).removeClass('checked');
      });
      $('> img', button).addClass('checked'); 
      $('> img', button).attr("src","/style/radio-button-selected.png"); 
      $('#contact_form-gender', pid).val(id);
    }
  )

/**/
  $('#contact_form-gender label img').click(function() {
      $('#contact_form-gender label img').each(function() { 
        $(this).attr("src","/style/radio-button.png"); 
        $(this).removeClass('checked');
      });
      $(this).addClass('checked'); 
      $(this).attr("src","/style/radio-button-selected.png"); 
    }
  )

  $('#contact_form-gender label').click(function() {
      $('img', '#contact_form-gender').each(function() { 
        $(this).attr("src","/style/radio-button.png"); 
        $(this).removeClass('checked');
      });
      $('> img', this).addClass('checked'); 
      $('> img', this).attr("src","/style/radio-button-selected.png"); 
    }
  )

/**/
  $('#arnomij_trainingsignupform-date_choices label img').click(function() {
      $('#arnomij_trainingsignupform-date_choices img').each(function() { 
        $(this).attr("src","/style/radio-button.png"); 
        $(this).removeClass('checked');
      });
      $(this).addClass('checked'); 
      $(this).attr("src","/style/radio-button-selected.png"); 
      var hidden_value = $('span', $(this).parents('label')).html();
      $('#arnomij_trainingsignupform-date').val(hidden_value);
    }
  )

  $('#arnomij_trainingsignupform-date_choices label').click(function() {
      $('img', '#arnomij_trainingsignupform-date_choices').each(function() { 
        $(this).attr("src","/style/radio-button.png"); 
        $(this).removeClass('checked');
      });
      $('> img', this).addClass('checked'); 
      $('> img', this).attr("src","/style/radio-button-selected.png"); 
      var hidden_value = $('span', this).html();
      $('#arnomij_trainingsignupform-date').val(hidden_value);
    }
  )

  $('#arnomij_trainingsignupform-gender_choices label img').click(function() {
      $('#arnomij_trainingsignupform-gender_choices img').each(function() { 
        $(this).attr("src","/style/radio-button.png"); 
        $(this).removeClass('checked');
      });
      $(this).addClass('checked'); 
      $(this).attr("src","/style/radio-button-selected.png"); 
      var hidden_value = $('span', $(this).parents('label')).html();
      $('#arnomij_trainingsignupform-gender').val(hidden_value);
    }
  )

  $('#arnomij_trainingsignupform-gender_choices label').click(function() {
      $('img', '#arnomij_trainingsignupform-gender_choices').each(function() { 
        $(this).attr("src","/style/radio-button.png"); 
        $(this).removeClass('checked');
      });
      $('> img', this).addClass('checked'); 
      $('> img', this).attr("src","/style/radio-button-selected.png"); 
      var hidden_value = $('span', this).html();
      $('#arnomij_trainingsignupform-gender').val(hidden_value);
    }
  )

  /* searchbox */
  $('.searchbox .button').click(function() {
    this.submit();
  });

  $('form.searchbox').submit(function() {
      if($('.searchbox', this).attr("value") == $('.searchbox', this).attr("defaultValue")) {
          return false;
      }
      return true;
  });

  /* top menu */
  $('#header-menu li').hover(
    function() {
      var li = this;
      if ($(li).data('closing')) {
        window.clearTimeout($(li).data('closing-timeout'));
        $(li).removeData('closing');
        return;
      }
      $('> ul', this).slideDown('fast');
      $('> a', li).addClass('active');
      $('> a', this).each(function() { 
        var a = this;
        $(li).addClass('clickable'); 
        $(li).click(function() { 
          window.location = $(a).attr('href'); 
        }); 
      });
    },
    function() {
      var li = this;
      $(li).data('closing', true);
      $(li).data('closing-timeout', window.setTimeout(function() {
        $('> ul', li).slideUp('fast', function() { $(li).removeData('closing'); });
      }, 10));
      $('> a', li).removeClass('active');
    }
  );

  /* make documentation lists clickable */
  $('.articlegroup-info .documentation li, #content .search-results .beam .paginator li').click(
    function() {
      if($('a', this).attr('target') == '_blank') {
        window.open($('a', this).attr('href'), "Arnomij");
      } else {
        window.location = $('a', this).attr('href');
      }
    }
  );

  /* add quantity to form action (order basket) onsubmit */
  $('form.ref').submit(
    function() {
      var parentrow = $(this).parents('tr');
      $(this).attr("action", $(this).attr("action")+"/"+$('.q',parentrow).attr("value"))
    }
  )

  /* lightbox */
  var lightboxparams = {
    overlayBgColor: '#c6cacd',
    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);

  // add to order
  $('.add_to_order').each(function () {
    var theform = this;
    var self = this; // form
    var add_to_order_snippet = self;
    var quantity = $('input[name=quantity]', self);
    var initial_quantity = $(quantity).val();
    var submitbutton = $('.add_to_order-submit', add_to_order_snippet);
    $(self).submit(function() {
      $(submitbutton).click();
      return false;
    });
    $(submitbutton).click(function() {
      var formhtml = $(this).parent().html();
      formhtml = $(this).parent().html();
      $('.add_to_order-submit', theform).before('<img src="/style/ajax-loader.gif"/>');
      $('.add_to_order-submit', theform).hide();

      var q = $(quantity).val();
      q = parseInt(q, 10);
      if (!q || q<0 || q.toString(10)!==$(quantity).val()) {
        $(quantity).val('???');
        $(quantity).focus();
        return false;
      }
      var info = $('#info-basket-order');
      var infototal = $('#info-basket-order-total');
      info.html('<img src="/style/ajax-loader.gif"/>');
      infototal.html('<img src="/style/ajax-loader.gif"/>');

      $.ajax({
        url: $(self).attr('action') + '/' + q,
        type: 'POST',
        data: {'returntype':'json'},
        dataType: "json",
        error: function() { 
          info.html('??'); 
          infototal.html('??'); 
        },
        success: function(data)
        {
          if (data['result']==1) {
            info.html(data['articlecount']); 
            infototal.html(data['basket_subtotal']); 
            $(theform).html(formhtml);
          }
          else {
            info.html('??'); 
            infototal.html('??');
          }
          $(quantity).val(initial_quantity);
          $('.loader', add_to_order_snippet).remove();
          $(submitbutton).removeClass('busy');
        }
      });
      return false; 
    });
  });

    /* open basket-print page in new window without statusbar etc */
    $('a[rel="print"]').click( function() {
        window.open('/'+stentor.getLanguage()+'/print-basket/order','','scrollbars=auto','resizable=no','addressbar=no');

        return false;
    });

    /* prevent the display of the pointer cursor of no link is available */
    $('ul.documentation li').each(function() {
        //if($(this).hasClass('tech') || $(this).hasClass('brochures')) continue;
        if(!$('a', this).attr('href') && (!$(this).hasClass('tech') || !$(this).hasClass('brochures'))) {
            $(this).addClass('no-url');
        }
    });

    /* make everything clickable */
    $('.info-logo, .blocks td, .clickable-container').click(function() {
          if(!$('a', this).attr('href')) {
              return;
          }

          if($('a', this).attr('target') == '_blank') {
            window.open($('a', this).attr('href'), "Arnomij");
          } else {
            window.location = $('a', this).attr('href');
          }
    });

    /* im-/explode un-ordered list */
    $('.expand-ul li').click(function() {

        var expand = false;
        if(!$('ul', this).hasClass('active')) expand = true;

        $('.expand-ul ul').removeClass('active');
        $('.expand-ul .arrow').fadeOut();

        if(expand == true) {
            $('.arrow', this).fadeIn();
            $('ul', this).addClass('active');
        }
    });

});
