function setWrapperVPos()
{
  wrapperVPos = Math.ceil($(window).height()-500)/2;
  $("#wrapper").css("top", wrapperVPos);
  switch($('body').attr('id'))
  {
    case 'media':
      initGallery();
      break;
  }
}
$(document).ready(function() {
  setWrapperVPos();
});
$(window).resize(function() { 
  setWrapperVPos();
});


function initGallery()
{
  currentStep = 0;
  
  //  Number of items in the gallery
  galleryCount = Math.ceil($("#gallery a").length/2);
  
  //  Initialize the array that will contain the width steps for scrolling
  galleryScrollSteps = new Array();
  galleryScrollSteps[0] = 0;
  
  i=1;
  
  //  Let's parse the gallery items
  jQuery.each($("#gallery a"), function()
  {
    //  Bind an event on the click that will fire a popup
    $(this).bind("click", function (e)
    {
      e.preventDefault();
      launchwin($(this).attr('href'), "gallery", "toolbar=no,location=no,status=no,menubar=no,scrollbars=no,resizable=no,width=2000,height=2000")
    })
    
    //  Let's initialise width table element
    parsingPos = Math.floor((i+1)/2);
    
    if (galleryScrollSteps[parsingPos] == undefined)
    {
      galleryScrollSteps[parsingPos] = new Number(galleryScrollSteps[parsingPos-1]);
    }

    // alert(galleryScrollSteps[parsingPos]);

    jQuery.each($(this).children(), function ()
    {
      galleryScrollSteps[parsingPos] += new Number($(this).attr('width'))+1;
    })
    
    i++;
  })
  
  //  Init the previous button
  $("#gallery-previous").bind("click", function (e)
  {
    e.preventDefault();
    if (currentStep > 0)
    {
      $("#gallery-next").removeClass("disabled");
      currentStep--;
      animateToStep(currentStep);
      if (currentStep == 0)
      {
        $(this).addClass("disabled");
      }
    }
  })

  //  Init the next button
  $("#gallery-next").bind("click", function (e)
  {
    e.preventDefault();
    if (currentStep < (galleryCount-1))
    {
      $("#gallery-previous").removeClass("disabled");
      currentStep++;
      animateToStep(currentStep);
      if (currentStep == (galleryCount-1))
      {
        $(this).addClass("disabled");
      }
    }
  })
}

function animateToStep(stepToGo)
{
  targetX = galleryScrollSteps[stepToGo];
  $("#gallery-list").animate({
    left: -targetX
  }, 700 );
}

var newwin;
function launchwin(winurl,winname,winfeatures,parentname)
{
  if (!document.images)
  {
    newwin = null;
  }
  if (newwin == null || newwin.closed)
  {
    newwin = window.open(winurl,winname,winfeatures);
    if (newwin.opener == null)
    {
      newwin.opener = window;
    }
    newwin.opener.name = parentname;
  }
  else
  {
    newwin.focus();
  }
}
