/**
 * Initialize the jQuery functions
 */ 
jQuery(function($)
{
  initHover();
  initTraining();
  initSlideshow();
  initSearch();
  initImageToggle();
  initProjectSearch();
  initFancybox();
});

/**
 * This function makes blocks clickable. 
 */ 
function initHover()
{
  if (! $('.clickable').length ) return;
  
  $('.clickable')
  .hover(
    function()
    {
      $(this).addClass('clickableHover');
    },
    
    function()
    {
      $(this).removeClass('clickableHover');
    }
  )
  .click(function()
  {
    window.location = $('a', this).attr('href');
  });
}

/**
 * This function makes all the Javascript on the "Schulungsunterlagen" page.
 */ 
function initTraining ()
{
  if (! $('.presentation').length &&
      ! $('.terms').length) return;
  
  $('.slideDownloads li').hover(
    function()
    {
      $(this).addClass('hover');
    },
    function()
    {
      $(this).removeClass('hover');
    }
  );
  
  initTermsForm ();
  
  /* Set the fancybox size according to the current window size */
  var browserWidth = document.documentElement.clientWidth;
  var browserHeight = document.documentElement.clientHeight;
  var frameWidth = browserWidth > 900/0.8 ? 900 : browserWidth * 0.8;
  var frameHeight = browserHeight > 600/0.8 ? 600 : browserHeight * 0.8;
  
  $('#termsLink').fancybox(
  {
    zoomOpacity: true,
    zoomSpeedIn: 100,
    zoomSpeedOut: 300,
    zoomSpeedChange: 200,
    overlayShow: true,
    overlayOpacity: 0.6,
    frameWidth: frameWidth,
    frameHeight: frameHeight,
    hideOnContentClick: false,
    callbackOnStart: function()
    {
      $('.slidePreview').css({visibility: 'hidden'});
      
      /* Change the target-URL to only display the content */
      var targetURL = $('#termsLink').attr('href') + '&contentonly';
      $('#termsLink').attr('href', targetURL);
    },
    callbackOnShow: function()
    {
      initTermsForm ()
    },
    callbackOnClose: function()
    {
      $('.slidePreview').css({visibility: 'visible'});
    }
  });
}

function initTermsForm ()
{
  var submit = $('#submitTerms');
  var accept = $('#acceptTerms');
  
  submit.attr('disabled', 'disabled');
  accept.removeAttr('checked');
  
  accept.click(function()
  {
    if ( $(this).attr('checked') ) {
      submit.removeAttr('disabled');
    } else {
      submit.attr('disabled', 'disabled');
    }
  });
}


/**
 * This function initializes the slide show in the header.
 */ 
function initSlideshow()
{
  if (! $('#slideshow').length ) return;
  
  /* Initialize variables */
  var current;
  var interval;
  var intital;
  
  /* Retrieve slideshow status from cookie */
  var slideshowStatus = $.cookie('solarfassade_show');
  
  /* Insert the play/pause buttons */
  $('#slideshow').prepend(
    '<div id="slideshowControls"><a id="slideshowPause" href="#"><span class="hidden">Animation forsetzen</span></a><a id="slideshowPlay" href="#"><span class="hidden">Animation anhalten</span></a></div>'
  );
  
  /* Assign the play/pause functions */
  $('#slideshowPlay').click(play);
  $('#slideshowPause').click(pause);
  
  /* Retrieve the current element */
  current = $("#slideshow").find("img:visible").parent();
  
  /* Move the image-paths from longdesc to src */
  $("#slideshow").find("img[longdesc]").each(function(){
    var path = $(this).attr("longdesc");
    $(this).attr("src", path);
  });
  
  /* Start to play the slideshow if enabled */
  if (slideshowStatus && slideshowStatus == 'slideshowPause')
  {
    $('#slideshowPause').hide();
  }
  else
  {
    $('#slideshowPlay').hide();
    playSlideshow(9000);
  }
  
  function playSlideshow(initialTime)
  {
    var initialTime = initialTime || 0;
    initial = setTimeout(changeSlide, initialTime);
    interval = setInterval(changeSlide, 15000);
  }
  
  function changeSlide()
  {
    $('#slideshow').fadeTo(1000, 0, function()
    {
      $(current).addClass("none");
      if($(current).attr("href") == $("#slideshowImages a:last").attr("href"))
      {
        current = $("#slideshowImages a:first");
      }
      else
      {
        current = $(current).next();
      }
      $(current).removeClass("none");
      $(this).fadeTo(1000, 1);
    });
  }
  
  function play(event)
  {
    event.preventDefault();
    
    /* SET COOKIE */
    var date = new Date();
    date.setTime(date.getTime() + 604800);
    $.cookie('solarfassade_show', $(this).attr("id"), { path: '/', expires: date });
    
    playSlideshow();
    $(this).hide();
    $('#slideshowPause').show();
  }
  
  function pause(event)
  {
    event.preventDefault();
    
    /* SET COOKIE */
    var date = new Date();
    date.setTime(date.getTime() + 604800);
    $.cookie('solarfassade_show', $(this).attr("id"), { path: '/', expires: date });
    
    clearTimeout(initial);
    clearInterval(interval);
    $(this).hide();
    $('#slideshowPlay').show();
  }
}


/**
 * This function takes care of the String replacement in the search field.
 */ 
function initSearch()
{
  if (! $('#searchterm').length ) return;
  
  var searchterm = $('#searchterm').prev('label').html();
  $('#searchterm').val(searchterm);
  $('#searchterm').focus(function()
  {
    if( $(this).val() == searchterm ) $(this).val('');
  });
  $('#searchterm').blur(function()
  {
    if( $(this).val() == '' ) $(this).val(searchterm);
  });
  
  /* supress click when there is no input */
  $('#search form')
  .submit(function()
  {
    if( $('#searchterm').val() == searchterm || $('#searchterm').val().length == 0 )
    {
      return false;
    };
    return true;
  })
  .hover(
    function()
    {
      $(this).addClass('searchhover');
    },
    
    function()
    {
      $(this).removeClass('searchhover');
    }
  );
}


function initImageToggle ()
{
  /* Preview Image functions */
  $(".thumbnail").click( function()
  {
    $(this).hide().parent().find(".largeimg").show();
    return false;
  });
  
  $(".largeimg").click( function()
  {
    $(this).hide().parent().find(".thumbnail").show();
  });
}


/**
 * Manipulate the project search results. 
 */ 
function initProjectSearch()
{
  if (! $('#searchfilter').length ) return;
  
  var updateLock = false;
  
  /* Register update function on hide button */
  $('#searchfilter')
  .submit(function()
  {
    /* Update the results list */
    updateFilter();
    
    return false;
  });
  
  /**
   * Change the selected filter. Available filters are:
   * filterbuilding, filterintegration 
   * */
  $('#searchfilter option')
  .click(function()
  {
    /* Update the results list */
    updateFilter();
    
    return false;
  });
  
  /* Handle submit events and update the result's list */
  function updateFilter()
  {
    var selectedCats = [];
    
    /* Filter manipulation for "Anbieterverzeichnis" */
    if($('.results').length)
    {
      var productType = $("#searchfilter #productType option:selected").attr("class");
      
      //alert("found results: " + selectedCats.join('|'));
      $('#searchfilter select#moduleType36').attr('disabled','disabled').addClass("none");
      $('#searchfilter select#moduleType37').attr('disabled','disabled').addClass("none");
      $('#searchfilter select#moduleType111').attr('disabled','disabled').addClass("none");
      $('#searchfilter select#moduleType112').attr('disabled','disabled').addClass("none");
      
      if (productType == 'catid_36')
      {
        //alert("found 36");
        $('#searchfilter select#moduleType36').attr('disabled','').removeClass("none");
        
      }
      if (productType == 'catid_37')
      {
        //alert("found 37");
        $('#searchfilter select#moduleType37').attr('disabled','').removeClass("none");
      }
      if (productType == 'catid_111')
      {
        //alert("found 111");
        $('#searchfilter select#moduleType111').attr('disabled','').removeClass("none");
      }
      if (productType == 'catid_112')
      {
        //alert("found 112");
        $('#searchfilter select#moduleType112').attr('disabled','').removeClass("none");
      }
    }
    
    /* retrieve active options */
    $("#searchfilter select:not(.none) option:selected")
    .each(function(i)
    {
      /* ignore the option to select all */
      if($(this).attr("class").indexOf("all_") < 0)
      {
        selectedCats.push($(this).attr("class"));
      }
    });
    
    /* hide no results message */
    $("#noResults").addClass("none");
    
    /* scan list for elements that match our options */
    if(selectedCats && selectedCats.length)
    {
      $("ul.examples>li, ul.results>li")
      .each(function(i)
      {
        var foundClasses = 0;
        for (var i = 0; i < selectedCats.length; i++)
        {
          if ($(this).hasClass(selectedCats[i]))
          {
            $(this).removeClass("none");
            foundClasses++;
          }
        }
        
        if(foundClasses < selectedCats.length)
        {
          $(this).addClass("none");
        }
      });
    }
    else
    {
      $("ul.examples>li, ul.results>li")
      .removeClass("none");
    }
    
    /* check the number of results */
    var resultCount = $("ul.examples>li:visible, ul.results>li:visible").length;
    if (!resultCount)
    {
      /* display no results message */
      $("#exampleCount").addClass("none");
      $("#noResults").removeClass("none");
    }
    else
    {
      /* display results */
      $("#exampleCount span").text(resultCount);
      $('#exampleCount').removeClass("none");
      if(!updateLock)
      {
        updateLock = true;
        $('ul.examples, ul.examples>li, ul.results').effect('highlight', {}, 2000, releaseUpdateLock);
      }
    }
    
    return false;
  };
  
  function releaseUpdateLock ()
  {
    updateLock = false;
  };
}

function initFancybox () {
  if (! $('.imageSmall a').length ) return;
  
  $('.imageSmall a').fancybox({
    zoomOpacity: true,
    zoomSpeedIn: 300,
    zoomSpeedOut: 300,
    zoomSpeedChange: 200,
    overlayShow: true,
    overlayOpacity: 0.6
  });
}

