// ******************************************************************** Handlers

function handleDocumentReady() {
  initFormStyles();
  createNewWindowForExternalLinks();
  initCheckboxState();
  setCheckbox();
}

function handleFocus() {
  if (!aFormDefaultValues[this.id]) {
    aFormDefaultValues[this.id] = this.value;
  }

  if (this.value == aFormDefaultValues[this.id]) {
    this.value = '';
    this.style.color = active_color;
  }
}

function handleBlur() {
  if (this.value == '') {
    this.style.color = inactive_color;
    this.value = aFormDefaultValues[this.id];
  }
}

function handleCheckBoxState() {
  $('#search_events').change(function(){
    checkState($('#search_events').attr('checked'));
  });
}



// ******************************************************************* Helper Methods

function setCheckbox() {
  var state = readCookie("checkboxState");
  if (state == 1){
    $('#search_events').attr('checked', 'checked');
  }
}

function checkState(state) {
  if (state == 1){
    createCookie("checkboxState",1);
  } else {
    createCookie("checkboxState",0);
    $('#search_events').attr('checked', '');
  }
}
			
// ******************************************************************* Initialize

function initFormStyles() {
  $("input.default-value").css("color", inactive_color);
  $("input.default-value").focus(handleFocus);
  $("input.default-value").blur(handleBlur);
}

function initCheckboxState() {
  checkboxState = (readCookie("checkboxState"))?readCookie("checkboxState"):0;
  handleCheckBoxState();
}

// ******************************************* Utilities (Create a general js file?)

function createNewWindowForExternalLinks() {
  $("a[@href^=http]").each(
  function(){
    if(this.href.indexOf(location.hostname) == -1) { 
      $(this).attr('target', '_blank');
      }
  })
}

//Rollover tooltip function ... add class tooltip to an image to display title
function bindTooltips(){	
		xOffset = 10;
		yOffset = 20;		
	$("img.tooltip").hover(function(e){		
		this.t = this.title;
		this.title = "";									  
		$("body").append("<p id='tooltip'>"+ this.t +"</p>");
		$("#tooltip")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px")
			.fadeIn("fast");		
    },
	function(){
		this.title = this.t;		
		$("#tooltip").remove();
    });	
	$("a.tooltip").mousemove(function(e){
		$("#tooltip")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px");
	});			
};





// ************************************************************ Variable Declarations


// Forms
var aFormDefaultValues = new Array();
var active_color = '#C7C7C7'; // Color of user provided text
var inactive_color = '#333333'; // Color of default text

var checkboxState;


// Do It!
$(document).ready(handleDocumentReady);