/* avenue.popup-1.1.js */

//v1.1 - fixes when navigating back from the popup hash to home hash, the code now automatically closes the popup, where in v1.0, this didn't happen and the popup window was still up.

jQuery(function($) {

  //Create modal hyperlinks given the first title in the modal box
  var modalwindows = $('div.modal').each(function() {
    var title = $(this).find('h1').html().toLowerCase().replace(/[\.\-\_\!\?\@\#\&\*\(\)\+\=]/, ' ');    
    var href = '#!/popup/' + title.split(' ').join('-');
    $(this).prev().find('a').attr('href', href);
  });

  //Create our modal dom elements
  var dom_body = $('body');
  var dom_popup = $('<div id="popup">').hide().prependTo(dom_body);
  var dom_popup_overlay = $('<div id="overlay">').prependTo(dom_popup);
  var dom_popup_container = $('<div id="container">').prependTo(dom_popup);
  var dom_popup_data = $('<div id="data">').prependTo(dom_popup_container);
  var dom_popup_button = $('<div id="button">').prependTo(dom_popup);
  
  //Enable our modal windows    
  $('.modal').prev()
  .css('color','#A40B1E')
  .css('cursor', 'pointer')
  .click(function() {
    if (dom_popup.is(':hidden')) {
      dom_popup_data.html($(this).next('.modal').html());
      dom_popup.fadeIn('fast', 'swing', function() {
        dom_popup_button.click(function() {
          fade_out_popup();
        });
        $(document).keyup(function(event) {
          if (event.keyCode == 27) { 
            fade_out_popup();
          }
        });
        dom_popup_overlay.click(function() {
          fade_out_popup();
        });
      });
    }    
  });
  
  //Fade out the modal window
  function fade_out_popup() {
    dom_popup.fadeOut('fast', 'swing', function() {
      window.location.savedhash ='!/';
      window.location.hash = '!/';
    });
  } //fade_out_popup
  
  //Altering the page behavior
  window.location.savedhash = '!/';
  if (window.location.hash == '') { window.location.hash = '!/'; }
  var modaltimer = window.setInterval(function() {
    if (window.location.savedhash != window.location.hash) {
      if (window.location.hash.match('!/popup/')) {
        $('a[href="' + window.location.hash + '"]').trigger('click');
      }    
      else {
        fade_out_popup();      
      }     
      window.location.savedhash = window.location.hash;
    }
  }, 50);


});
