$(document).ready(function() {
	$('#TGOV_lang ul').fauxSelect({selected: lang});
//	$('.splain').tooltip();
	$('#TGOV_SF_Input input').overlay().gSuggest({label:getMsg('suggestions')});
	$('#TGOV_FF_SC_SearchInput input').overlay();
	$('#TGOV_GS_Summary_Input input').overlay();
	$('#TGOV_GS_Content_Input textarea').overlay();

	// If the form element has discover in the action attribute (aka, discover page)	
	//if('form[action*=discover]') {
		// call the Find in page on the node to attach to scoped to certain pages and pass it the filter set
		//$('#TGOV_ContentSubListing_Control').findInPage($('#TGOV_ContentSubListing_Control li'));
	//}
	// call the add accelerator function with methods to get the messaging
	//$('#TGOV_SDPCRC_RCBottom_WebpartZone', '.search').addAccelerator({button:{txt:getMsg('addAccel')},splain:{txt:getMsg('accelSplain')}});

	
	// Track plugins
	$.track.pluginDetect();
	// Track link clicks
	$('a[href]').trackLinkClicks();
	//if ($("#evtAudienceSearchBox").length) {
	if ($("#evtContentArea").length) {
		var searchBoxDiv = $('<div />')
			.attr('id', 'evtAudienceSearchBox')
			.css('marginBottom', '5px')
			.css('marginLeft', '10px');

		$("#evtContentArea").parent().prepend(searchBoxDiv);
	//$("#evtAudienceSearchBox")
		//.css('marginBottom', '5px')
		//.css('marginLeft', '10px');
   var newText = document.createTextNode("Search in Page ");
   var newLabel = $('<label />')
    .attr('id', 'findInPageLabel')
    .css('font-size', '1.5em')
    .css('float', 'left')
    .css('paddingRight', '10px')
    .css('marginTop', '2px')
    .attr('for', 'target');
   newLabel.append(newText);
   $("#evtAudienceSearchBox").append(newLabel);
   var newDiv = $('<div />')
    .css('border', 'none')
    .css('height', '32px')
    .css('padding', 0)
    .css('float', 'left')
    .css('width', '181px')
    .css('background', 'url("/_layouts/images/tgovimgbin/TGOV_bg_Finder_SearchBox.png") no-repeat');
    
    
   var newBox = $('<input />')
    .attr('id', 'target')
    .css('width', '165px')
    .css('background', 'transparent')
    .css('border', 'none')
    .css('marginTop', '7px')
    .css('marginLeft', '7px')
    .attr('type', 'text');
   $(newDiv).append(newBox);
   $("#evtAudienceSearchBox").append(newDiv);
   var clearDiv = $('<div />')
   	.attr('id', 'clearfix')
   	$("#evtAudienceSearchBox").append(clearDiv);
   	
   $('#target').keyup(function(e) {
      var $this = $(e.target), val = $this.val();
    var newRegEx = new RegExp(val.toUpperCase());
    $('.evtContentRow').each(function(index) {
     var tempRow = $(this).find('div').find('a').text().toUpperCase();
     var rowHeader = jQuery.trim(tempRow);
     var ndx = rowHeader.search(newRegEx);
     if (ndx != 0) {
      $(this).hide();
     } else {
      $(this).show();
     }
      });
   });
  }
});

// Google Analytics Script
var _gaq = _gaq || [];
// Tracking number updated 06/04/2010 - J.Winslow
_gaq.push(['_setAccount', 'UA-5014953-19']);
_gaq.push(['_setLocalRemoteServerMode']);
_gaq.push(['_trackPageview']);

(function() {
  var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
  ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
  var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();


// Set object for messages and anything else we want
(function($) {
	$.txGov = {
		msgs: {
			suggestions: ['Suggestions','Sugerencias'],
			addAccel: ['Install Search Accelerator', 'Instalar Acelerador de Búsqueda'],
			accelSplain: ['Search texas.gov accelerator allows you to search texas.gov from any site by just highlighting text and right clicking.','Buscar texas.gov acelerador le permite buscar texas.gov desde cualquier sitio con sólo resaltando texto y haciendo clic derecho.']
		}
	};
})(jQuery);

/*
 * @description	This plugin adds the tooltip to the DOM
 * @return {jQuery Object}
 * @param {Object} options
 * @type {jQuery Plugin Method}
 * @author Mike Cravey
 * @version 0.1
 */

;(function($) {
	$.fn.tooltip = function(options) {
	  var opts = $.extend({}, $.fn.tooltip.defaults, options);

	  return this.each(function() {
	    var $this = $(this);

	    // Support for the Metadata Plugin.
	    var o = $.meta ? $.extend({}, opts, $this.data()) : opts;

		// Set local variable for the content of the tooltip
	  	var content = opts.content.length ? o.content : $.trim($this.html());

			// Create tooltip node with appropriate markup around it. Consider abstracting the classes to defaults.
			var $tooltip = '<div class="tooltip hidden"><div class="txt">' + content + '</div><div class="tail"></div></div>';

			// Remove the contents of the selected node and insert the new content		
			$this.empty().append($tooltip);

			// Hover event listener (mouseover & mouseout combo) to show and hide the tooltip.
			$this.hover(function() {
				$(this).find('.tooltip').removeClass('hidden');
			}, function() {
				$(this).find('.tooltip').addClass('hidden');
			});


	  });

	  // private function for debugging
	  function debug($obj) {
	    if (window.console && window.console.log) {
	      window.console.log($obj);
	    }
	  }
	};

	// default options
	$.fn.tooltip.defaults = {
		content: ''
	};

/*
 * @description Simulate a select box
 * @return {jQuery Object}
 * @param {Object} options
 * @type {jQuery Plugin Method}
 * @author Mike Cravey
 * @version 0.1	
 */

	$.fn.fauxSelect = function(options) {
		var opts = $.extend({}, $.fn.fauxSelect.defaults, options);

		return this.each(function() {
			var $this = $(this);

			// Support for the Metadata Plugin.
		    var o = $.meta ? $.extend({}, opts, $this.data()) : opts;
		    // Set the selected item. If one is not selected, select the first item.
			var selected = o.selected ? $('[lang=' + o.selected + ']', $this) : $this.find('li:first');
			// Remove 'selected' class.
			$('.selected', $this).removeClass('selected');
			// Remove the selected item from the list and put it at the top. Add 'selected' class.
			selected.remove().prependTo($this).addClass('selected');

		});

		// private function for debugging
		function debug($obj) {
			if (window.console && window.console.log) {
				window.console.log($obj);
			}
		}
	};

	// set good defaults
	$.fn.fauxSelect.defaults = {
		selected: ''
	};
	
/*
 * @description Filter page contents by what is typed in an input
 * @return {jQuery Object}
 * @param {Object} {Object} options
 * @type {jQuery Plugin Method}
 * @author Mike Cravey
 * @version 0.1	
 */
	$.fn.findInPage = function(filterSet, options) {
		var opts = $.extend(true, {}, $.fn.findInPage.defaults, options);

		return this.each(function() {
			var $this = $(this);

			// Support for the Metadata Plugin.
	    var o = $.meta ? $.extend(true, {}, opts, $this.data()) : opts,
			// Build div wrapper for search box
			$wrapper = $('<div />').addClass(o.wrapper.classes.join(' ')).attr(o.wrapper.attrs),
			// Build input for search, attach to wrapper
			$input = $('<input />').addClass(o.input.classes.join(' ')).attr(o.input.attrs).appendTo($wrapper);
			// Attach wrapper to DOM
			$wrapper.prependTo($this);
			// Cache filter set as a public variable
			o.filterSet = filterSet;
			o.textArr = [];
			
			// Populate public array with text from filter set
			o.filterSet.each(function(i){
				o.textArr[i] = $(this).find('*').text();
			});
			// set length number to public integer for speed purposes	
			o.textArr.leng = o.textArr.length;
			
			// On keyup
			$input.keyup(function(e) {
				// Set this to the element that the action was committed against and grab the value
				var $this = $(e.target), val = $this.val();
				// for each item in the text array, search for the value of the input
				for(var i=0; i<o.textArr.leng;i++) {
					// If not matched, hide the item from the filter set
					if(o.textArr[i].indexOf(val) == -1) {
						o.filterSet.filter(':eq(' + i + ')').hide();
					}
				}
			});

		});

		// private function for debugging
		function debug($obj) {
			if (window.console && window.console.log) {
				window.console.log($obj);
			}
		}
	};

	// set good defaults
	$.fn.findInPage.defaults = {
		input: {
			attrs: {},
			classes: []
		},
		wrapper: {
			attrs: {},
			classes: []
		}
	};

/*
 * @description Filter page contents by what is typed in an input
 * @return {jQuery Object}
 * @param {Object} options
 * @type {jQuery Plugin Method}
 * @author Mike Cravey
 * @version 0.1	
 */

	$.fn.findInPage = function(filterSet, options) {
		var opts = $.extend(true, {}, $.fn.findInPage.defaults, options);

		return this.each(function() {
			var $this = $(this);

			// Support for the Metadata Plugin.
	    var o = $.meta ? $.extend(true, {}, opts, $this.data()) : opts,
			// Build div wrapper for search box
			$wrapper = $('<div />').addClass(o.wrapper.classes.join(' ')).attr(o.wrapper.attrs),
			// Build input for search, attach to wrapper
			$input = $('<input />').addClass(o.input.classes.join(' ')).attr(o.input.attrs).appendTo($wrapper);
			// Attach wrapper to DOM
			$wrapper.prependTo($this);
			// Cache filter set as a public variable
			o.filterSet = filterSet;
			o.textArr = [];
			
			// Populate public array with text from filter set
			o.filterSet.each(function(i){
				o.textArr[i] = $(this).find('*').text();
			});
			// set length number to public integer for speed purposes	
			o.textArr.leng = o.textArr.length;
			
			// On keyup
			$input.keyup(function(e) {
				// Set this to the element that the action was committed against and grab the value
				var $this = $(e.target), val = $this.val();
				// for each item in the text array, search for the value of the input
				for(var i=0; i<o.textArr.leng;i++) {
					// If not matched, hide the item from the filter set
					if(o.textArr[i].indexOf(val) == -1) {
						o.filterSet.filter(':eq(' + i + ')').hide();
					}
				}
			});

		});

		// private function for debugging
		function debug($obj) {
			if (window.console && window.console.log) {
				window.console.log($obj);
			}
		}
	};

	// set good defaults
	$.fn.findInPage.defaults = {
		input: {
			attrs: {},
			classes: []
		},
		wrapper: {
			attrs: {},
			classes: []
		}
	};

/*
 * @description Build out accelerator link and registration config
 * @return {jQuery Object}
 * @param {Object} options
 * @type {jQuery Plugin Method}
 * @author Mike Cravey
 * @version 0.1	
 */

	$.fn.addAccelerator = function(options) {
		if ($.fn.addAccelerator.support()) {
			var opts = $.extend(true, {}, $.fn.addAccelerator.defaults, options);

			return this.each(function() {
				var $this = $(this);

				// Support for the Metadata Plugin.
				var o = $.meta ? $.extend(true, {}, opts, $this.data()) : opts,
					// Build div wrapper for button and put button and explanation into it
					$wrapper = $('<div />').addClass(o.wrapper.classes.join(' ')).attr(o.wrapper.attrs),
					$button = $('<button />').addClass(o.button.classes.join(' ')).attr(o.button.attrs).text(o.button.txt).appendTo($wrapper);
					$splain = $('<p />').addClass(o.splain.classes.join(' ')).attr(o.splain.attrs).text(o.splain.txt).appendTo($wrapper);
					$wrapper.prependTo($this);
				   	switch (lang) {
				   		// if lang is set to es, grab appropriate message
						case 'es':
							o.serviceConf = o.serviceConfPath + '/es/' + o.serviceConfFile;
							break;
						// otherwise grab en message	
						default:
							o.serviceConf = o.serviceConfPath + '/en/' + o.serviceConfFile;
							break;
					}
				
				$button.click(function(e){
					var $this = $(e.target);
					// add accelerator
					window.external.AddService(o.serviceConf);
					// register the adding of accelerator with analytics
					_gaq.push(['_trackEvent', 'install', 'click', o.button.txt]);
					return false;
					
				});
			});
		}

		// private function for debugging
		function debug($obj) {
			if (window.console && window.console.log) {
				window.console.log($obj);
			}
		}
	};
	
	$.fn.addAccelerator.support  = function() {
		if (window.external&&typeof window.external.addService != "undefined") {
			return true;
		}
		return false;
	};
	

	// set good defaults
	$.fn.addAccelerator.defaults = {
		button: {
			attrs: {},
			classes: ['button'],
			txt: ''
		},
		splain: {
			attrs: {},
			classes: [],
			txt: ''
		},
		wrapper: {
			attrs: {},
			classes: []
		},
		serviceConfPath: '/Style%20Library/Assets',
		serviceConfFile: 'searchTXGov.xml'
	};
})(jQuery);

/*
 * @description Query the server for the messages file and return the expected value
 * @return message
 * @param key
 * @type function
 * @author Mike Cravey
 * @version 0.1	
 */
function getMsg(k) {
	// TODO: replace hard coded msg with xhr request to get message object. May be post production.
	var msgs = {};

	// extend the local object with new messages
	$.extend(true, $.txGov.msgs, msgs);

   	switch (lang) {
   		// if lang is set to es, grab appropriate message
		case 'es':
			return $.txGov.msgs[k][1];
		// otherwise grab en message	
		default:
			return $.txGov.msgs[k][0];
	}
};