$(document).ready(function() {
  var storedHash = window.location.hash;
  
  $('.catalogHeader, .catModal').click(function(e){
    e.preventDefault();
    window.location.hash = $(this).attr('class').match(/catModal/) ? 'catModalOpen' : 'catalogHeaderOpen';
    return false;
  });

  $('.FSCatClose, .catOverlay, .closeButton').live('click', function() {
    var hashAdded = window.location.hash;
    if(hashAdded.match(/catalogHeader/) || hashAdded.match(/catModal/)) {
      closeOverlays();
    }
  });

  $(window).bind('hashchange hashLoad', function(e){
    e.preventDefault();
    currHashable = window.location.hash;
    if(currHashable.match(/catalogHeader/) || currHashable.match(/catModal/)) {
      if ( $.browser.msie  &&  $.browser.version < 7 ) {
        $('.' + currHashable.replace('Open', '')).colorbox({
          iframe:true,
          width:"1094px",
          scrolling:false,
          height:"778px",
          title:'' + FS.button({buttonName: "closeButton", buttonClass: "closeButton", buttonId: "closeButton", buttonLabel: FS.local_lang.labels.close}),
          onClosed: function() {
            closeOverlays();
          }
        });
      } else {
        $.fn.fswebcatalog({
          catalog: 'Spring1_UK'
        });
      }
    } else {
      $('.FSCatClose, .catOverlay, .closeButton').click();
    }
  });
  
  // We need to replace the hash - best to use a meaningful term.
  function closeOverlays() {
    if (storedHash) {
      window.location.hash = storedHash;
    } else {
      window.location.hash = 'closedModal';
    }
  }
});

// We want the Modal to open if the hash is present on page load.
$(window).load(function() {
  var currHashable = window.location.hash;
  if(currHashable.match(/catalogHeader/) || currHashable.match(/catModal/)) {
    $(window).trigger('hashLoad');
  }
});
