// Fix background image flickering in IE
try {
  document.execCommand('BackgroundImageCache', false, true);
} catch(e) { }

/* Special search behavior */
var Search = {
	prompt: "Search", // default value - should get real value from markup
	init: function() {
		Search.prompt = jQuery('#search').focus(Search.focus).blur(Search.blur).val();
	},
	focus: function() { if (this.value == Search.prompt) { this.value = ''; } },
	blur: function() { if (this.value.length == 0) { this.value = Search.prompt; } }
};
$(document).ready( Search.init );

// Function to support retrieving a cookie
function getCookie(c_name)
{
	if (document.cookie.length>0)
	  {
	  c_start=document.cookie.indexOf(c_name + "=");
	  if (c_start!=-1)
		{
		c_start=c_start + c_name.length+1;
		c_end=document.cookie.indexOf(";",c_start);
		if (c_end==-1) c_end=document.cookie.length;
		return unescape(document.cookie.substring(c_start,c_end));
		}
	  }
	return "";
}

// Set the default value for the Country field on forms
$(document).ready(function() {
	var cookies = document.cookie;
	
	// Check for the existence of the 'tl_website' cookie which stores values previous submitted by the user
	if (!getCookie("tl_website")) {
		// If the cookies doesn't exist, set the default value for the field
		$("#country option[value='United States']").attr('selected', true);
	}
});

var DD_belatedPNG;
if (DD_belatedPNG) { // Only execute for IE6
	// Selectors need to match what's in the CSS exactly
	DD_belatedPNG.fix('#Content ul.documents li a.pdf, #Content ul.documents li a.video');
	DD_belatedPNG.fix('#SiteId img, .focusBox li.column div.content, #Content img');	
	DD_belatedPNG.fix('.tooltip .header, .tooltip .channel');
	DD_belatedPNG.fix('.tooltip .header .content, .tooltip .channel .content');
	DD_belatedPNG.fix('ul.customers div.more a, #Content ul.legend li');
	DD_belatedPNG.fix('#NavigationPrimary .dropdown .header, #NavigationPrimary .dropdown .header .content, #NavigationPrimary .dropdown .channel, #NavigationPrimary .dropdown .channel .content');
	DD_belatedPNG.fix('#AnalystReports li, #Whitepapers li, #CaseStudies li, #Datasheets li, #ServicesMaterials li, #OverviewsWhiteboards li, #ProductQuicktours li');
}

/* begin - Navigation Primary */
var NavigationPrimary = {
	init: function() {
		var $n = $('#NavigationPrimary > ul');
		
		$n
			.find('> li')
				.hover(NavigationPrimary.mouseenter, NavigationPrimary.mouseleave)
				.find('div.dropdown')
				.each( function() {
					$(this).find('.content > ul').addClass('selfClear');
				});
	},
	mouseenter: function() { $(this).addClass('over').children('a').addClass('over'); },
	mouseleave: function() { $(this).removeClass('over').children('a').removeClass('over'); }
};
$(document).ready(NavigationPrimary.init);
/* end - Primary Navigation */

var SolutionBox = {
	init: function() {
		$('.solutionBox').find('input:submit').each(function() {
			var $a = $('<a href="#" class="button"><span><em>' + this.value + '</em></span></a>');
			$a.click(SolutionBox.submit);
			$(this).replaceWith($a);
		});
	},
	submit: function() {
		// handle form submission;
	}
};
$(document).ready(SolutionBox.init);

$(document).ready(function() {
	if ($.fn.slidedeck) {
		$('dl.slidedeck .positionOnLoad').removeClass('positionOnLoad');
		if (isFx30()) {
			// It's Firefox 3.0 - need to use the IE6 variant of slide deck
			$('#SlideDeckFrame').attr('id', 'SlideDeckFrameIESix');
		} else {
			$('#SlideDeckFrame').slidedeck();
		}
	}

	if ($.fn.jcarousel) {
		$('.quotesCarousel ul').jcarousel({
			visible: 1,
			scroll: 1,
			wrap: 'both'
		});
	}

	if ($.fn.tooltip) {
		$('.tooltipped a[title]').each(function() {
			var offset = [20, -50];
			if ($(this).parents('ul:first').hasClass('options')) {
				offset = [5, -50];
			}
			$(this).tooltip({
				layout: '<div class="tooltip" />',
				position: 'top right',
				offset: offset,
				onBeforeShow: function() {
					var $$ = this.getTip();
					if (this.getTrigger().parents('.solutionBox').length != 0) {
						$$.addClass('solutionTip');
					}
					// Finalize HTML setup
					if ($$.find('.header').length == 0) {
						$$	.wrapInner('<div class="content" />')
							.wrapInner('<div class="channel" />')
							.prepend('<div class="header"><div class="content" /></div>');
					}
				}
			});
		});

		// Products Landing page tooltips
		$('.focusBox .tooltipped a').each(function() {
			// Turn the following text into a tooltip
			var $$ = $(this).addClass('trigger');
			var $tip = $$ // the trigger
						.parent() // the LI
						.find('span') // Tooltip text
						.prepend($$.text() + ' ') // Put the product name at the start
						.prepend( // Put the linked product name at the start
							$$.clone() // Clone it so we don't lose the trigger
							.addClass('title') // Add .title class so we can style it
							.removeClass('trigger') // It isn't a trigger here.
						);
			$tip = $tip	.replaceWith(
						'<div class="tooltip focusBoxTip" style="display: none;">'
						// + $(this).html()
						+ $tip.html()
						+ '<a class="more" href="' + this.href + '">Learn More</a>'
						+ '</div>'
					);
			
			// Enable the link as a tooltip
			$$.tooltip({
				relative: true,
				position: 'top right',
				offset: [20, -100],
				onBeforeShow: function() {
					var $$ = this.getTip();
					// Finalize HTML setup
					if ($$.find('.header').length == 0) {
						$$	.wrapInner('<div class="content" />')
							.wrapInner('<div class="channel selfClear" />')
							.prepend('<div class="header"><div class="content" /></div>');
					}
				},
				onShow: function() {
					this.getTrigger().parents('li.column:first').addClass('active').siblings().removeClass('active');
				}
			});
		});
		$('ul.customers div.more a').each(function() {
			$(this)	.attr('title', $(this).text());
			$(this)	.tooltip({
						layout: '<div class="tooltip small" />',
						// relative: true,
						position: 'top right',
						offset: [0, -45],
						onBeforeShow: function() {
							var $$ = this.getTip();
							// Finalize HTML setup
							if ($$.find('.header').length == 0) {
								$$	.wrapInner('<div class="content" />')
									.wrapInner('<div class="channel" />')
									.prepend('<div class="header"><div class="content" /></div>');
							}
						}				
						
					});
		});
	}
});

var SlideDeckIE = {
	init: function() {
		$('#SlideDeckFrameIESix dt').click(function() {
			$(this).siblings('dd').hide();
			$(this).addClass('active').siblings('dt').removeClass('active');
			$(this).next().show();
		}).each(function() {
			$(this).html('<span class="index">' + $(this).attr('title') + '</span>');
		}).first().addClass('active')
		  .siblings('dd:not(:first)').hide();
	}
};
$(document).ready(SlideDeckIE.init);

// Convert un-tabbed display into tabbed display and activate tabs
$(document).ready(function() {
	if (! $.fn.tabs) {
		DD_belatedPNG && DD_belatedPNG.fix('.addthis_toolbox img'); 
		return;
	}

	var $tabs = $('div.tabs');
	if ($tabs.length == 0) {
		DD_belatedPNG && DD_belatedPNG.fix('.addthis_toolbox img'); 
	}
	var $tabnav = $('<ul class="tabNav selfClear"></ul>');
	$tabs.prepend($tabnav);
	// $('.tabNav a').live('click', function() { alert("clicked"); });
	$tabs	.find('> div')
				.each( function(i) {
					var id = this.id;
					var $header = $(this).find('h2:first');
					if ($header.length == 0) {
						$header = $(this).find('h3:first');
					}
					if ($header.length == 0) {
						$header = $(this).find('h4:first');
					}
					var title = $header.attr('title') || $header.html();

					$tabnav.append('<li id="' + id + 'Tab"><a href="#' + id + '" class="noPopup"><span>' + title + '</span></a></li>');
					$header.remove();
				});
	// Need delay for browsers to get their DOM in order
	setTimeout(function() {
		$tabs.tabs({
			// Prevent outline on selection
			select: function(event, ui) {
				$(ui.tab).blur();
			}
		});
		DD_belatedPNG && DD_belatedPNG.fix('.addthis_toolbox img');
		$tabs.find('.hideOnLoad').removeClass('hideOnLoad');
	}, 500);
});

// Hide content on load for browsers that can use JS to show it later
document.write('<style type="text/css">dl.expandableContent p.initialCollapse { display: none; }</style>');

var ExpandableContent = {
	expandLabel: 'Show Executive Summary',
	collapseLabel: 'Hide Executive Summary',
	init: function() {
		$('dl.expandableContent').each(function() {
			
			$(this).find('dd').addClass('selfClear').each(function() {
				var count = $(this).find('p.content').hide().removeClass('initialCollapse').length;
				// Only make expandable if we have content to show on expand
				if (count > 0) {
					$(this)
						.prepend(
							$(this)
								.find('> a')
								.addClass('download')
								.remove()
						)
						.prepend(
							'<div class="controls"><a href="#" class="expand">'
							+ ExpandableContent.expandLabel
							+ '</a><a href="#" class="collapse" style="display: none;">'
							+ ExpandableContent.collapseLabel
							+ '</a></div>'
						);
				}
			});
		});
		$('a.expand').live('click', ExpandableContent.expand);
		$('a.collapse').live('click', ExpandableContent.collapse);
	},
	expand: function(e) {
		e.preventDefault();
		$(this).hide().siblings().show().parents('dd:first').find('p.content').show();
	},
	collapse: function(e) {
		e.preventDefault();
		$(this).hide().siblings().show().parents('dd:first').find('p.content').hide();
	}
};
$(document).ready( ExpandableContent.init );

var SafariSelectFix = {
	init: function() {
		$('#Content select').each(function() {
			var $$ = $(this);
			if ($$.height() < 20) {
				$$.addClass('heightFix');
			}
		});
	}
};
$(document).ready( SafariSelectFix.init );

$(document).ready(function() {
	// style alternate form fields - so that we can clear
	$('#Content form div').not('.radioButtonTall').filter(':even').addClass('alt');
	$('#Content form div.radioButtonTall div.options input:nth-child(4n+1)').addClass('alt');
});

// Google Analytics for tracking non-HTML files
$(document).ready(function() {
	$('a[href$=.pdf], a[href$=.doc]').click(function() {
		if (! $(this).attr('onclick'))
			pageTracker._trackPageview(this.href);
	});
});

/*
	TODO Add support for opening offsite links and PDF links in new windows
*/

/* Modal window capabilities */
$(document).ready(function() {
	if (! $.fn.prettyPhoto)
		return;

	$("a[rel^='prettyPhoto'],a.video").prettyPhoto({
		animationSpeed:'fast',
		slideshow:10000,
		showTitle: false,
		markup: '<div class="pp_pic_holder"> \
						<a class="pp_close" href="#">Close</a> \
						<div class="ppt">&nbsp;</div> \
						<div class="pp_top"> \
							<div class="pp_left"></div> \
							<div class="pp_middle"></div> \
							<div class="pp_right"> \
							</div> \
						</div> \
						<div class="pp_content_container"> \
							<div class="pp_left"> \
							<div class="pp_right"> \
								<div class="pp_content"> \
									<div class="pp_loaderIcon"></div> \
									<div class="pp_fade"> \
										<a href="#" class="pp_expand" title="Expand the image">Expand</a> \
										<div class="pp_hoverContainer"> \
											<a class="pp_next" href="#">next</a> \
											<a class="pp_previous" href="#">previous</a> \
										</div> \
										<div id="pp_full_res"></div> \
										<div class="pp_details clearfix"> \
											<p class="pp_description"></p> \
											<div class="pp_nav"> \
												<a href="#" class="pp_arrow_previous">Previous</a> \
												<p class="currentTextHolder">0/0</p> \
												<a href="#" class="pp_arrow_next">Next</a> \
											</div> \
										</div> \
									</div> \
								</div> \
							</div> \
							</div> \
						</div> \
						<div class="pp_bottom"> \
							<div class="pp_left"></div> \
							<div class="pp_middle"></div> \
							<div class="pp_right"></div> \
						</div> \
					</div> \
					<div class="pp_overlay"></div>'
	});
});

var BestPracticesDiagram = {
	init: function() {
		var $$ = $('ul.bestPractices');
		if ($$.length == 0)
			return;
		
		var $bpNav = $('<ul class="bestPracticesNav" />');
		$('ul.bestPracticesNav a').live('mouseover', BestPracticesDiagram.mouseover).live('click', BestPracticesDiagram.click);
		var count = 1;
		$$.find('li:not(.default)').each(function() {
			$bpNav.append('<li id="Item' + count + '"><a href="#BP' + count + '"></a></li>');
			$(this).attr('id', 'BP' + count++).hide();
		});
		$$.before($bpNav);
	},
	mouseover: function(e) {
		var id = this.hash;
		$(this).addClass('over').parent().siblings().find('a').removeClass('over');
		if (id.substring(0, 1) != '#') {
			id = '#' + id;
		}
		var $li = $(id);
		$li.show().siblings().hide();
	},
	click: function(e) {
		e.preventDefault();
	}
};
$(document).ready( BestPracticesDiagram.init );

/* begin - open new window for external links and pdfs */
$(document).ready(function() {
	$('#Wrapper a[href^=http://],#Wrapper a[href^=https://]')
		.not($('a.noPopup,a[rel="prettyPhoto"]'))
		.popupwindow(); // Fully qualified links
	$('#Wrapper a[href$=.pdf]').popupwindow(); // PDFs by URL
	$('#Wrapper a.popup').popupwindow(); // specific links
});
/* end - open new window for external links and pdfs */

$(document).ready(function() {
	$('#ContentChannel a').printPage({appendLinksToId: 'ContentChannel'}); // Footnote the content
});

// Clean up hide on load bits
$(document).ready(function() {
	$('.hideOnLoad').not('.tabContent').removeClass('hideOnLoad');
	$('dl.slidedeck .positionOnLoad').removeClass('positionOnLoad');
});

var NavigationSecondary = {
	init: function() {
		$("#NavigationSecondary a[href*='#']").click(NavigationSecondary.click);
	},
	click: function(e) {
		if ($.fn.tabs) {
			var $$ = $('div.tabs');
			if ($$.length > 0) {
				$$.tabs('select', this.hash);
				e.preventDefault();
			}
		}
	}
};
$(document).ready(NavigationSecondary.init);

// Fix add this text not being hidden correctly
$('body').ready(function() {
	// #PageTools .addthis_toolbox a 
	if (isFx30()) {
		$('#PageTools .addthis_toolbox a').text('');
	}
});

function isFx30() {
 	//test for Firefox/x.x or Firefox x.x (ignoring remaining digits);
	if (/Firefox[\/\s](\d+\.\d+)/.test(navigator.userAgent)) {
		// capture x.x portion and store as a number
		var ffversion=new Number(RegExp.$1); 
 		if (ffversion >= 3 && ffversion < 3.1) {
			return true;
		}
	}
	return false;
}
