var swap_text_boxes = [];

function initialize_search()
{
	
	$('#keywords').addClass('search-greyed');
	//Store the default value for each box
	$('#keywords').each(function() {
	  swap_text_boxes[$(this).attr('id')] = $(this).attr('value');
	});

	//Add focus and blur events to set or clear the value
	$('#keywords').bind('focus', function() {
	  if($(this).val() == swap_text_boxes[$(this).attr('id')]) {
	    $(this).removeClass('search-greyed');
		$(this).val('');
	  }
	});

	$('#keywords').bind('blur', function() {
	  if($(this).val() == '') {
		$(this).addClass('search-greyed');
	    $(this).val(swap_text_boxes[$(this).attr('id')]);
	  }
		});
}

function dd_show()
{
	$(this).find("ul").slideDown('fast').show('slow', function(){
				//$(this).find('ul').height("auto");
				}); //Drop down the subnav
}

function dd_hide()
{
	$(this).find("ul").slideUp('slow'); //When the mouse hovers out of the subnav, move it back up
}

$(document).ready(function(){
	
	initialize_search();
	
	$("ul.topnav li.sub-level-0 ul").parent().prepend("<span></span>").addClass('has-subnav'); //Only shows drop down trigger when js is enabled - Adds empty span tag after ul.subnav

	$("ul.topnav li").hoverIntent({
			sensitivity: 3, //
			interval: 100, // milliseconds delay before onMouseOver
			over: dd_show, 
			timeout: 100, // milliseconds delay before onMouseOut
			out: dd_hide
		});
	
	/*External Links*/
	$('a[rel="external"]').click( function() {
	        window.open( $(this).attr('href') );
	        return false;
	    });
	
	/*
	================
	Homepage Flash
	================
	*/
	
	// Embed Flash
	var flashvars = {};
	flashvars.dataURL = "/_api/_homepage-tabs/";
	var params = {"wmode":"transparent"};
	var attributes = {};
	attributes.id = "featured-flash";
	swfobject.embedSWF("/flash/PPROTabHeader.swf", "alternate-content", "720", "233", "9.0.0", false, flashvars, params, attributes);
	
	/*
	================
	Video Gallery
	================
	*/
	
	if ( $("#video_cats").length > 0 ) {
		var category = null;
		var page = null;
		
		$('#video_cats').change(function(){
			var index = this.selectedIndex;
			category = (this.options[index].value !== '') ? this.options[index].value+'/' : '';
			page = '';
			
			load_videos(category, page)
		});
		
		register_events();
	}
	
	function handle_paging(link)
	{
		var category_select = $('#video_cats')[0];
		var index = (category_select.selectedIndex === "" || category_select.selectedIndex === undefined) ? 0 : category_select.selectedIndex;
		category = (category_select.options[index].value !== '') ? category_select.options[index].value+'/' : '';
		page = (qs(link.href,'page') !== '') ? qs(link.href, 'page') : '';
		load_videos(category, page);
	}
	
	function load_videos(category, page)
	{	
		var video_url = '/_components/_video-gallery/';
		page = (page === '') ? '' : '?page='+page;
		$("div.gallery").load(video_url+category+page, register_events);
	}
	
	function register_events()
	{
		$(".pagination a").click(function(){
			handle_paging(this);
			return false;
		});
	}
	
	/*
	================
	Image Gallery
	================
	*/
	
	if ( $("#flickr_sets").length > 0 ) {
		var photoset_id = null;
		
		$('#flickr_sets').change(function(){
			var index = this.selectedIndex;
			photoset_id = (this.options[index].value !== '') ? this.options[index].value+'/page1/' : '';
			
			$("div.gallery").load('/_components/_gallery/'+photoset_id, paging);
		});
		
		$('ul.flickr-gallery a.thumb').colorbox({transition:"elastic", inline:true, width:"50%", href:function(){return '#'+returnHash(this.href);}});
		
		function paging()
		{
			$(".flickr-pagination a").click(function(){
				$("div.gallery").load(this.href, paging);
				return false;
			});

			$('ul.flickr-gallery a.thumb').colorbox({transition:"elastic", inline:true, width:"50%", href:function(){return '#'+returnHash(this.href);}});
			
			//$.fn.colorbox.init();
		}

	}
	
	$('.flickr-grid a').colorbox({transition:"elastic", inline:true, width:"50%", href:function(){return '#'+returnHash(this.href);}});
		
	if($('#sendMessage').length >0)
	{
		$('#learnmore').hide();

		$("#sendMessage").validate({
	        rules: {recipients: {required: true,emailList: true}
	        }    
	    });
	
		$('#cBoxAnonymous').change(function(){
			$('.additional-message').slideToggle('fast');
		});
		
		$('.back').click(function(){
			history.go(-1);
			return false;
		});
	}
	
	if($('#icpsignup').length > 0)
	{
		$.metadata.setType("attr", "validate"); 
		$("#icpsignup").validate();
	}
	
	/*
	================
	Was this helpful?
	================
	*/
		
	$(".helpful a").colorbox({width:"50%", inline:true,	href:function(){return $(this).attr('href')+'-form';}}, loadComplete);
		
	$('.helpful-container').hide();
	$('.hidden-form-field').hide();
	
	function loadComplete()
	{			
		if(this.href != '' || this.href != 'undefined')
		{
			var url = '#'+returnHash(this.href)+'-form';
			
			$(url).bind("submit", function(event){
				event.preventDefault();
				var str = $(url).serialize();

				$(url).fadeOut('slow', function(){ 
					$('#cboxLoadedContent').append('<div class="ajax-loader></div>');
						$.ajax({
					        type: "POST",
					        url: $(url).attr('action'),
					        data: str,
					        success: function(msg) {
								$('#cboxLoadedContent .ajax-loader').fadeOut().remove();
								$('#cboxLoadedContent').append('<div class="helpful-message" style="display:none;">' + msg + '</div>');
								$('#cboxLoadedContent .helpful-message').fadeIn();
							}
					    });// .ajax
				});// .fadeOut
			});// .bind
		}// if
	}
	
	/*
	================
	Poll
	================
	*/
	$('.poll-results').hide();

	$('p.results-lnk a').click(function(){
		$('.poll-results').toggle();
		$('.poll-question').toggle();
	});
	
	$('p.poll-lnk a').click(function(){
		$('.poll-question').toggle();
		$('.poll-results').toggle();
	});
	
	$('.anon').qtip({	style: {
							border: {
								width: 5,
								radius: 10
							},
							padding: 10, 
							textAlign: 'center',
							tip: true, // Give it a speech bubble tip with automatic corner detection
	                  		name: 'cream' // Style it according to the preset 'cream' style
	               }
	 });
	
	if($('form.email-signup').length > 0)
	{
		var specialname = '';
		
		$("input[name='listid']").change(function(){
		var formid = '';
		var special = '';
		var specialval = '';
		
		if ($("input[name='listid']:checked").val() == '18168')
	    {
			// Code for handling value 'caregiver'
			formid = '1830';
			special = 'specialid:18168';
			specialval = 'I3U5';
		}    
		else if ($("input[name='listid']:checked").val() == '18257')
        {
			// Code for handling value 'school nurse'
			formid = '1831';
			special = 'specialid:18257';
			specialval = 'G2TW';
		}	
		else if ($("input[name='listid']:checked").val() == '18169')
		{
			// Code for handling value 'doctor'
			formid = '1832';
			special = 'specialid:18169';
			specialval = 'WZ9X';
		}
		else if ($("input[name='listid']:checked").val() == '18171')
		{
			// Code for handling value 'nurse'
			formid = '1833';
			special = 'specialid:18171';
			specialval = 'KW1B';
		}       
		else
		{
			// Code for handling 'pharm'
			formid = '1834';
			special = 'specialid:18170';
			specialval = '83H3';
		}
		
		if(specialname !== '')
		{
			$("input[name='"+specialname+"']").remove();
		}
		
		specialname = special;
		
		$("input[name='formid']").val(formid);
		$('form.email-signup').append('<input type="hidden" name="'+special+'" value="'+specialval+'" />');
		
		});
	}
	
	/*
	================
	Flash Map
	================
	*/
	
	if($('#flashmap').length > 0)
	{
		var flashvars = {};
				flashvars.headLiceDataURL = "/googleMap/googleInsightXML.xml";

				var params = {};
				params.allowScriptAccess = "always";


				var attributes = {};
				attributes.id = "flashmap";
				attributes.name = "flashmap";

				swfobject.embedSWF("/flash/headlicemap.swf", "flashmap", "435", "370", "9.0.0","/flash/expressInstall.swf", flashvars, params, attributes);
		
		
	}
	
	/*
	================
	Alert Warning
	================
	*/
	
	if($('#sendMessagePreview').length > 0)
	{
		$('#email-warning').hide();
		$('#send_submit').bind('click keypress', function(event) {
            if(pageTracker){
                fixedLink = '/popup-alert-a-friend';
                pageTracker._trackPageview(fixedLink);
            };
        });
		$('#sendMessagePreview').bind("submit", function(event){
			event.preventDefault();
			$.fn.colorbox({width:"50%", inline:true, href:'.warning-message', open:true}, createBoxListeners);
		});
		
	}
	
}); //document.ready

function createBoxListeners()
{
	$('a#warning_cancel').click(function(event){
		event.preventDefault();
		$.fn.colorbox.close();
	});
	
	$('a#warning_proceed').click(function(event){
		event.preventDefault();
        if(pageTracker){
                fixedLink = '/popup-alert-a-friend/proceed';
                pageTracker._trackPageview(fixedLink);
        };
		$('#sendMessagePreview').unbind('submit');
		$('#sendMessagePreview').submit();
	});
	
}

/*
================
Utility Functions
================
*/

function returnHash(link){
	var hash = 0;
	if((link.match(/#(\w.*)/) != null))
	{
		hash = link.match(/#(\w.*)/)[1];
	}
	return hash;
}

function qs(url, name)
{
	name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	var regexS = "[\\?&]"+name+"=([^&#]*)";
	var regex = new RegExp( regexS );
	var results = regex.exec( url );
	if( results == null )
		return "";
	else
		return results[1];
}