var globalSliderValue = 0;
var slider_used = false; // this would be what's in the cookie
var preventHint = false;


$(function() {

  var oldPosX;
  var oldElement;
  var sliderValue;
  
  var resetButton = $('#age_reset');
  
  resetButton.click(function(event) {
    event.preventDefault();
    ageReset();
  });
  

  var slider = $("#slider").slider({
    animate: false,
    value: 0,
    min: 0,
    max: 150,
    step: 1,
    slide: function(event, ui) {

      $('#slider_progress').width($(ui.handle).css('left'));
      $('#slider_progress').width($('#slider_progress').width()+15) // aligning red background to slider-handle

    },

    change: function (event, ui) {

      var width = $(ui.handle).css('left');
      $('#slider_progress').width(width);


      var width_px = $('#slider_progress').width();
      width_px = width_px + 15;
      $('#slider_progress').width(width_px) // aligning red background to slider-handle


      if($.browser.msie) { // since IE7 tends to get hickups, we have to assign the progress width values twice
        width = $(ui.handle).css('left');

        $('#slider_progress').width(width);

        width_px = $('#slider_progress').width();
        width_px = width_px + 15;
        $('#slider_progress').width(width_px) // aligning red background to slider-handle
      }


      //trigger for slider-steps background images

      if (oldPosX != undefined) {
        oldElement.css('backgroundPosition', oldPosX+'px' + ' -8px')
      }

      var exposedValue = ui.value/10/2;

      exposedValue = Math.ceil(exposedValue);

      globalSliderValue = exposedValue;
      
      if (exposedValue == 0) {
        resetButton.css({'display':'none'});
      } else {
        resetButton.css({'display':'block'});
      }

      var bg_pos = $('#slider_steps li.age_'+exposedValue).css('backgroundPosition'); //used to store old backgroundXPos value
      if ((bg_pos == 'undefined') || (bg_pos == null)) {
        bg_pos = $('#slider_steps li.age_'+exposedValue).css('background-position-x'); // ie6
        bg_pos += ' -16px';
      }

      var bg_pos_x = bg_pos.split(' ')[0].substring(0,bg_pos.split(' ')[0].length-2);

      $('#slider_steps li.age_'+exposedValue).css('backgroundPosition', bg_pos_x + 'px' + ' -67px');
      oldElement = $('#slider_steps li.age_'+exposedValue);
      oldPosX = bg_pos_x;


    },

    start: function (event, ui) {
      slider_hint.fadeOut();
    },

    stop: function (event, ui) {

      // terminate wrong values and map

      var newValue = ui.value/10/2;
      newValue = Math.ceil(newValue); // mapping fine values to a range between 0 and 8

      
      // snapping to positions according the range of 0 to 150 and display reset link
      
      
      if (newValue == 0) {
        $('#slider').slider("value",0);
        resetButton.css({'display':'none'});
      } else {
        $('#slider').slider("value",(newValue*20-10)); //repositioning to steps
        resetButton.css({'display':'block'});
      }

      toggleAgeClasses(newValue);

      // displays the howto for the slider on the startscreen
      if (startpage_flag && (!slider_used)) {
        slider_used = true;
        slider_hint.fadeOut();
        preventHint = true;
        $('#slider-overlay').modal();
      }

      $.post('/mil/de/funktionsseiten/agecookie.jsp?age='+newValue); // posting new value to the server

    }
  });

  $('a.age-inactive').live('click', function(event){
    event.preventDefault();
  });

  $('.pcontainer a').live('click', function(event){
    if ($(this).parent().hasClass('age-inactive')) {
      event.preventDefault();      
    }
  });


  var slider_hint = function(){
    var hint_config = {
      timeout: 5000,
      fadein: 500,
      fadeout: 250
    }

    if (!slider_used) {
      if ((typeof(startpage_flag) !== 'undefined') && (startpage_flag))
      setTimeout(fadeIn, hint_config.timeout);
      $('#slider_wrapper').live('mouseover', fadeIn);
    }

    function fadeIn(){

      if (!slider_used) {
        if (! preventHint) {
          preventHint = true;
          $('.ui-slider-handle').unbind();
          $('#slider_wrapper #hint').fadeIn(hint_config.fadein);
        }
      }
    }

    function fadeOut(){
      $('#slider_wrapper #hint').fadeOut(hint_config.fadeout);
    }

    function sliderUsed(){
      $('.ui-slider-handle').unbind();
      slider_used = true; // this would be what's in the cookie
    }

    return {
      fadeIn: fadeIn,
      fadeOut: fadeOut,
      sliderUsed: sliderUsed
    }

    }(slider_used);


    // if we are on the startpage, we always reset the cookie to 0.
    
    if ((typeof(startpage_flag) !== 'undefined') && (startpage_flag)) 
    {
      ageReset()
      return; // since we know we are at 0 at the beginning, no further GET is necessary
    }


    // else set values for slider initally according to chosen age class from cookie
    $.ajax({
      url: '/mil/de/funktionsseiten/agecookie.jsp',
      type: "GET",
      dataType: "text",
      cache: false, // IE7 needs this param to prevent caching on dataType "text"
      success: function(data) {
        var value = parseInt(data);
        if (startpage_flag) {
          if (! isNaN(value)) {
            slider_used = true; // in case the cookie is already returning a valid value, we assume the slider has already been used
            setSliderValue(value);
            toggleAgeClasses(value);
          }
          else {
            return; // if we are on the first page and the server returns NaN (no value set yet), do not readjust the slider
          }
        }
        else if (isNaN(value)) { // just in case the server response would not be like expected. (changing from startpage to Produkte/Wissen without setting value, set to 0.)
          ageReset()
        } else {
          slider_used = true;
          age_cookie = value;
          setSliderValue(value);
          toggleAgeClasses(value);
        }
      }
    });


  });


  function ageReset() {
    
    age_cookie = 0;
    setSliderValue(0);
    toggleAgeClasses(0);
    $.post('/mil/de/funktionsseiten/agecookie.jsp?age='+0); // also reset age_cookie on the server.
  }



  function toggleAgeClasses(value) {

    // remove inactive styles
    $('.age-inactive').each(function(){
      $(this).removeClass('age-inactive');

      // product-groups:
      if ($(this).hasClass('pcontainer')) {
        $(this).children('a').css('cursor', 'pointer');
        $(this).children('a').first().show();
        $(this).children('img').hide();
      }

      // knowledge container
      if ($(this).hasClass('knowledge_container')) {
        $(this).show();
      }

    });



    if (value != 0) {

      show_class = "age-" + value;


      // sort products within product-groups
      $('.pgroup_wrapper').each(function(){
        var product_order = $(this).data('product_order');
        var new_order = new Array();
        var items = new Array();

        var target = $(this).find('.center');
        target.empty();



        $.each(product_order, function(index, value){
          // remove no-margin class
          if (value.hasClass('no-margin')) {
            value.removeClass('no-margin');
          }

          // what if item possesses the selected class
          if (value.hasClass(show_class)) {
            items.push(value);
            } else { // and what if it doesn't
            value.children('a').css('cursor', 'default');
            value.children('a').first().hide();
            value.children('img').show();

            new_order.push(value);
          }
        });

        new_order = items.concat(new_order);
        // items = items.reverse();
        $.each(new_order, function(index, value){
          if ((index+1)%4 == 0) {
            value.addClass('no-margin');
          }
          target.append(value);
        });

        target.append('<div class="clearfix"></div>'); // sorting kills clearfix. so we need to add it afterwards again

        if ($(this).data('collapse_flag') == false) {
          $(this).find('.pcontainer:gt(3)').hide();
          $(this).find('.pcontainer:lt(4)').show();
        }

      });
      // end of sorting process

      // knowledge_container
      $('.knowledge_container:not(.'+show_class+')').each(function(){
        $(this).hide();
      });

      // add inactive styles
      $('.age:not(.'+ show_class +')').addClass('age-inactive');

    } else {
      // what if 0 is selected


      // sort products within product-groups
      $('.pgroup_wrapper').each(function(){
        var product_order = $(this).data('product_order');

        var target = $(this).find('.center');
        target.empty();

        $.each(product_order, function(index, value){
          // remove no-margin class
          if (value.hasClass('no-margin')) {
            value.removeClass('no-margin');
          }

          if ((index+1)%4 == 0) {
            value.addClass('no-margin');
          }
          target.append(value);

        });

        target.append('<div class="clearfix"></div>'); // sorting kills clearfix. so we need to add it afterwards again

        if ($(this).data('collapse_flag') == false) {
          $(this).find('.pcontainer:gt(3)').hide();
          $(this).find('.pcontainer:lt(4)').show();
        }

      });
      // end of sorting process

    }

    // following will always be executed
    Cufon.refresh();
  }



  // interfaces for slider controlling

  function getSliderValue()
  {
    return globalSliderValue;
  }

  function setSliderValue(val) //accepts values between 0 and 8 and sets slider accordingly to grid
  {

    if (val < 0 || val > 8) { //escaping values for safety reasons
      return;
    }

    if (val == 0)
    {
      $('#slider').slider("value",0);
    }
    else
    {
      val = val*20-10;  //repositioning to steps
      $('#slider').slider("value",val);
    }

  }



