/**
* SHARED JS
*/
var datavis_search_code = '005210755146566892804:q8epenwzc-q';

$(document).ready(function(){
  initScroll();
  initLightbox();
  initNav();
  //initSearch();
});

function initSearch() {
  google.load('search', '1');
  google.setOnLoadCallback(initSearchCallback);
}

function initScroll() {
  var hash = window.location.hash;
  if (hash) {
    var elem = $('' + hash);
    if (elem) {
      var offset = elem.offset();
	  try {
	      var y = (offset.top) ? offset.top : 0;
	      elem.css({backgroundColor: '#ffff99'});
	      $('html,body').animate({scrollTop: offset.top}, 1000, function() {
	        elem.animate({backgroundColor: 'white'}, 800);
	      });	
      } catch(err) {}
    }
  }
}

function initLightbox() {
  $("a.lightbox").fancybox({
	'transitionIn'	:	'elastic',
	'transitionOut'	:	'elastic',
	'speedIn'		:	200, 
	'speedOut'		:	200, 
	'overlayShow'	:	false
  });
}

function initNav() {
  $("ul#accordion span").expandCollapseAll();
}

/**
 * HELPER FUNCTIONS
 */

//Extracts the users query from the URL.
function getQuery() {
  var url = '' + window.location;
  var queryStart = url.indexOf('?') + 1;
  if (queryStart > 0) {
    var parts = url.substr(queryStart).split('&');
    for (var i = 0; i < parts.length; i++) {
      if (parts[i].length > 2 && parts[i].substr(0, 2) == 'q=') {
        return decodeURIComponent(parts[i].split('=')[1].replace(/\+/g, ' '));
      }
    }
  }
  return '';
}

function inputFocus() {
  document.getElementById('query-input').style['background'] = '';
}

function inputBlur() {
  var queryInput = document.getElementById('query-input');
  if (!queryInput.value) {
    queryInput.style['background'] =
    'white url(http://www.google.com/coop/images/'
      + 'google_custom_search_watermark.gif) no-repeat 0% 50%';
  }
}

function initSearchCallback() {
  google.search.CustomSearchControl.attachAutoCompletion(datavis_search_code,document.getElementById('query-input'), 'two-page-form');
  inputBlur();
}

function submitQuery() {
  window.location = '/search_results.php?q='
  + encodeURIComponent(document.getElementById('query-input').value);
  return false;
}

function onLoad() {
  // Create a custom search control that uses a CSE restricted to datavis.ca
  var customSearchControl = new google.search.CustomSearchControl(datavis_search_code);

  var drawOptions = new google.search.DrawOptions();
  drawOptions.setInput(document.getElementById('hidden-input'));

  // Draw the control in content div
  customSearchControl.draw('results', drawOptions);

  // Run a query
  customSearchControl.execute(getQuery());

  inputBlur();
}

