/*
  JavaScript used for the Popup help widget
  
  (C) Copyright 2009, Compete Inc.
  
  Depends on:
    JQuery
    JQuery UI
*/ 

if (!popup_help) {var popup_help = {}}

/*
 * Initialize Handler
 */ 
$j(document).ready(function() {
  // Create the help dialog DIV within the page, if it doesn't already exist
  $j('body').append('<div id="popup-help-dialog" class="popup-help-dialog"></div>');
  
  // Bind all the click event handlers
  bind_click_handlers();
});

function bind_click_handlers() {
  /*
      Binds the help popup click event to all elements specified by the 
      class '.popup-help'.
      
      This function can be called to rebind the help handlers if new items
      were added via AJAX.
   */
  $j('.popup-help').live('mousedown', _help_clicked);
}

popup_help.HELP_OPEN = false;

/*
 * Event Handlers
 */ 
function _help_clicked(event) {
  var _popup_div = $j('div#popup-help-dialog');
  
  /*
      Find out the help item by looking at any additional class
      NOTE: only the first class that's not .popups
   */
  var _help_items = this.className.split(' ');
  var _help_item = null;
  $j.each(_help_items, function() {
    _help_item = this;
    if (_help_item[0] == 'q') { return false; }
  });
  
  // Clear and display the loading gif
  _popup_div.empty();
  _popup_div.css('background-image', 'url(/site_media/images/icons/ajax_loading.gif)');
  _popup_div.css('background-position', 'center center');
  _popup_div.css('background-repeat', 'no-repeat');
  
  $j.ui.dialog.defaults.bgiframe = true;
  _popup_div.dialog({ 
      autoOpen: false,
      bgiframe: true,
      dialogClass: "popup-help-dialog",
      draggable: true,
      modal: false,
      height: 285,
      resizable: false,
      width: 460,
      zIndex: "10000",
      beforeclose: function(event, ui) { popup_help.HELP_OPEN = false; }
  });
  
  popup_help.HELP_OPEN = true;
  _popup_div.dialog('open');
  
  $j.getJSON('/s/async/popup_help/' + _help_item + '/', function(json) {
    var _popup_div = $j('div#popup-help-dialog');
    
    // Clear and display the content
    _popup_div.css('background-image', 'none');
    _popup_div.append('<h1>' + json.title + '</h1>');
    
    var _pdiv = '<p>';
    _pdiv += '<a href="' + main_site + '/help/' + _help_item + '">Open FAQs</a>';
    _pdiv += '<span class="vbar"/>';
    _pdiv += '<a href="' + main_site + '/resources/methodology/">Where does the data come from ?</a>';
    _pdiv += '</p>';
    _popup_div.append(_pdiv);
    
    _popup_div.append(json.content);
  });
  
  return false;
}


/*
 * Internal private functions
 */ 
