// Expire cookies in 30 days
var cookie_expiration = new Date(new Date().getTime() + 1000 * 60 * 60 * 24 * 30);

// Initial page setup, once the document is fully loaded
$(document).ready(function() {
	// Hooks for search field focus/blur
	if ($(".form_websearch_field") != null) {
		$(".form_websearch_field").focus(function(event) {
			if ($(this).hasClass("defaultvalue")) {
				$(this).attr("value", "");
				$(this).removeClass("defaultvalue");
			}
		});
		$(".form_websearch_field").blur(function(event) {
			if ($(this).attr("value") == "") {
				$(this).attr("value", "Search");
				$(this).addClass("defaultvalue");
			}
		});
	}
	// Hook for bookmark script (allows Opera to change the 'rel')
	$("#bookmarker").click(function(evt) {
		bookmarkIt(evt, $(this));
	});
	
	// Video player setup
	if (typeof(fpKey) != "undefined") {
		player = FlowPlayer(fpKey, 'overlay_videoplayer', '');
		// overlay
		$('a[rel]').overlay({
			speed: 'normal',
			expose: {
				color: '#F1F1F1',
				opacity: 0.9
			},
			onClose: function() {
				setTimeout(function() {
					// Opera requires us to call this on a timeout instead of directly,
					// or the overlaid player won't give back control of the page.  It
					// still throws an error that other browsers don't...
					// Appears to be a jQuery bug somewhere between 1.3.2 & 1.4.4
					player.stop();
					player.unload();
				}, 10);
			}
		});
	}

	// scrollable
	$('.mast_items').cycle({
		fx:			'fade',
		speed:		600,
		timeout:	10000,
		pause:		true,
		pauseOnPagerHover: true,
		pager:		'.mast_navi',
		slideExpr: 	'.mast_item'
	});
	
	$("#ticker").cycle({
		fx:			'fade',
		speed:		600,
		timeout:	10000,
		pause:		true,
		prev:		'.browse.next',
		next:		'.browse.prev',
		slideExpr:	'.ticker_item'
	});
	
	// tabs
	$("ul.tabset").tabs("> div", {effect: 'fade', fadeOutSpeed: 400, fadeOutSpeed: 100});
	
	// tooltips
	$("a.tooltip_trigger").tooltip({ effect: 'slide', relative: true, offset:[15, 92]});
	
	//Global Nav Menu
	var config = {
		over: showMenu,
		timeout: 200,
		out: hideMenu
	};
	function showMenu(){
		$('#home #masthead').before('<div class="hero_cover"></div>');
				
		if (jQuery.support.leadingWhitespace) {
			$('.hero_cover').fadeIn('fast');
		} else {
			$('.hero_cover').show();
		}

		$(this).children('.parent').addClass('menu_active');
		$(this).children('.menu_block').show();
	}
	function hideMenu(){
		$(this).children('.menu_block').hide();
		$(this).children('.parent').removeClass('menu_active');
		$('.hero_cover').fadeOut('fast', function(){
			$(this).remove();
		});
	}
	
	$("#mainnav .hasDropdown").hoverIntent(config);
	
	/* Main Menu Product Tab */
	var tabID = '';
	
	$('ul.prod_tabs li a:first').addClass('current');
	
	var prodConfig = {
		over: showProdTab,
		interval: 100, // default
		sensitivity: 7, // px, default
		timeout: 300,
		out: activateProdTab
	};
	
	function showProdTab() {
		$(this).children('a').addClass('current');
		$(this).siblings().children('a').removeClass('current');
		if ($(this).index() === 0) {
			tabID = 1;
		} 
		else if ($(this).index() === 1) {
			tabID = 2;
		}
		else if ($(this).index() === 2) {
			tabID = 3;
		}
		
		$('.prod_tab').hide();
		$('#prod_tab0'+ tabID).show();
	}
	
	function activateProdTab() {
	}
		
	$("ul.prod_tabs li").hoverIntent(prodConfig);
	
	var configLang = {
		over: showLangMenu,
		timeout: 300,
		out: hideLangMenu
	};
	function showLangMenu() {
		$('.global_nav_menu').show();
	}
	function hideLangMenu() {
		$('.global_nav_menu').hide();
	}
	
	$('#global_nav').hoverIntent(configLang);
	
	
	// Change tabs on hash changes w/in the same page:
	$(window).hashchange(function() {
		var newTab = 'a[href="' + location.hash + '"]';
		$(newTab).trigger('click');
	});
	
	// Fix the height of DIVs
	$("#homepage-features > .column > .box-shadow > .box-inner > .text-content").equalHeights();
	$("#ankle > ul > li").equalHeights();
	$(".executives > .two_column > .col").equalHeights();
	$("#oem_support > li").equalHeights();
	$("#oem_support > li").css("overflow","visible");
	
	// Fix the product mega menu
	$(".menu_block").show();
	$(".menu_col").equalHeights();
	menuColOriginalHeight = $(".menu_col").height();
	$(".menu_col").height(menuColOriginalHeight + 24);
	$(".prod_tab").equalHeights();
	$(".menu_block").hide();
	
	// Fix the height of the resource center header
	resourceCenterHeader();
	
	//jQuery Targeting
	$('.video_lib_products:even').addClass('target');
	$('.video_lib_products:last').removeClass('target');
	$('.video_lib_wireless:even').addClass('target');
	$('.video_lib_wireless:last').removeClass('target');
	$('.video_lib_corporate:even').addClass('target');
	$('.video_lib_corporate:last').removeClass('target');
	$('.profile_container .tabbed_content:even').addClass('target');
	$('.profile_container .tabbed_content:last').removeClass('target');
	
	if ($.browser.msie)
		ieHover(); //IE doesn't agree with the standard CSS-based menuing we use
	
	//drawer activator
	$('.btn_activate_content').click(function() {
		if ($.browser.msie && parseInt($.browser.version, 10) < 9) {
			// Re-set heights on toggled elements for IE7/8.  Otherwise it fails to display them
			$(this).parent().siblings('.collapsible').each(function(idx) {
				var el = $(this);
				el.css({height: el.height()});
			});
		}
		$(this).parent().siblings('.collapsible').slideToggle('slow');
		$(this).toggleClass('active');
		
		var linkTxt = $(this).attr('title');
		
		if ($(this).hasClass('active')) {
			$(this).html('- Less ' + linkTxt);
		} else {
			$(this).html('+ More ' + linkTxt);
		}
	});
});

//end $(document).ready


/*
 * Page Layout Functions
 */
function resourceCenterHeader() {
	$(".content_header_alpha .content_header_container, .content_header_alpha .box-inner").equalHeights();
	originalHeight = $(".header_resource_center").height();
	$(".header_resource_center").height(originalHeight - 24);
	$(".content_header_alpha .box-inner").removeAttr("style");
}


function OpenBrWindow(url, winName, features, myWidth, myHeight, isCenter) {
	if (isCenter) {
		var myLeft = ($(window).width() - myWidth) / 2;
		var myTop = ($(window).height() - myHeight) / 2;
		features += (features != '') ? ',' : '';
		features += ',left=' + myLeft + ',top=' + myTop;
	}
	window.open(url, winName,
		features + ((features != '') ? ',' : '') + 'width=' + myWidth + ',height=' + myHeight);
}

/*
 * Page Functions
 */
// Bookmark Page
function bookmarkIt(evt, elem) {
	// Don't follow the link:
	var dontFollow = true;
	var bookmarkTitle = document.title;
	var bookmarkUrl = document.location;

	if (window.sidebar && window.sidebar.addPanel) {
		window.sidebar.addPanel(bookmarkTitle, bookmarkUrl, "");
	} else if ($.browser.msie) {
		window.external.AddFavorite(bookmarkUrl, bookmarkTitle);
	} else if ($.browser.opera) {
		$(elem).attr("href", bookmarkUrl);
		$(elem).attr("title", bookmarkTitle);
		$(elem).attr("rel", "sidebar");
		dontFollow = false; // Opera "follows" the link -> bookmark sidebar
	} else { // for other browsers which does not support
		 alert("Your browser does not appear to support automated bookmarking.  Please bookmark this page using your browser's menu.");
	}
	if (dontFollow)
		evt.preventDefault();
}
// Print Page
function printIt() {
	if (typeof window.print === "function")
		self.print();
	else
		alert("Your browser doesn't appear to support this feature, please select the Print option from your browser's menu.");
}
// Email Page
function shareWebPageLink(link) {
	var url = window.location.href.replace("&", "%26");
	var title = document.title.replace("&", "%26");
	
	var href = "mailto:?subject=You have received a link from broadcom.com" +
		"&body=Title: " + title + "%0A%0ALink: " + url +
		"%0A%0AFor more information about Broadcom products please visit http://www.broadcom.com/";
	
	link.href = href;
}

/*
 * Cookie functions
 */
function setCookie(name, value, expires) {
	document.cookie = name + "=" + escape(value) +
		((expires) ? "; expires=" + expires.toGMTString() : "") +
		"; path=/";
}
function getCookie(name) {
	var dc = document.cookie;
	var prefix = name + "=";
	var begin = dc.indexOf("; " + prefix);
	if (begin == -1) {
		begin = dc.indexOf(prefix);
		if (begin != 0) return null;
	} else {
		begin += 2;
	}
	var end = document.cookie.indexOf(";", begin);
	if (end == -1) {
		end = dc.length;
	}
	return unescape(dc.substring(begin + prefix.length, end));
}
function deleteCookie(name) {
	if (getCookie(name))
		document.cookie = name + "=; path=/; expires=Thu, 01-Jan-70 00:00:01 GMT";
}

/*
 * UI functionality
 */
function toggleNewsDiv(aID, divID, plus, minus) {
	var a = $('#' + aID);
	var div = $('#' + divID);

	if (!a || !div)
		return;

	var show = !div.is(":visible");

	swapToggleNewsImg(a, show, plus, minus);
	toggleDivVisibility(div, show);
}

function swapToggleNewsImg(a, show, plus, minus) {
	if (!a || !plus || !minus)
		return;

	if (show)
		$(a).text(minus);
	else
		$(a).text(plus);
}

function toggleDiv(imgID, divID) {
	var img = $('#' + imgID);
	var div = $('#' + divID);

	if (!img || !div)
		return;

	var show = !div.is(":visible");

	swapToggleImg(img, show);
	toggleDivVisibility(div, show);
}

function toggleAllDiv(imgID, divID, hidID) {
	var img = $('#' + imgID);
	var hid = $('#' + hidID);

	if (!img || !hid)
		return;

	var show = $(hid).val() == "0";
	$(hid).val(show ? "1" : "0");

	swapToggleImg(img, show);

	$('#' + divID + ' div.toggle_body').each(function() {
		toggleDivVisibility($(this), show);
	});
	$('#' + divID + ' div.toggle_header img').each(function() {
		swapToggleImg($(this), show);
	});
}
function swapToggleImg(img, show) {
	if (!img)
		return;

	if (show)
		$(img).attr("src", $(img).attr("src").replace("directory_plus.gif", "directory_minus.gif"));
	else
		$(img).attr("src", $(img).attr("src").replace("directory_minus.gif", "directory_plus.gif"));
}
function toggleDivVisibility(div, show) {
	if (!div)
		return;

	if ($.browser.msie && parseInt($.browser.version, 10) < 9) {
		// Re-set heights on toggled element for IE7/8.  Otherwise it may fail to display them
		var el = $(div);
		el.css({height: el.height()});
	}
	if (show)
		$(div).slideDown('slow');
	else
		$(div).slideUp('slow');
}

function toggleInputInGroups(divAllId, divId) {
	if (divAllId) {
		// select all inputs w/in the container & uncheck or clear as necessary
		$('#' + divAllId + " :input").each(function(idx) {
			$(this).filter(":checkbox").attr("checked", false);
			$(this).filter(":radio").attr("checked", false);
			$(this).filter(":text").val("");
			$(this).filter("textarea").val("");
			$(this).attr("disabled", true);
		});
		// disable all subcontainers
		$('#' + divAllId + " span").each(function(idx) {
			$(this).addClass("disabled_text");
		});
	}

	// enable all inputs w/in the container
	$('#' + divId + " :input").each(function(idx) {
		$(this).attr("disabled", false);
	});
	// enable sub-containers
	$('#' + divId + " span").each(function(idx) {
		$(this).removeClass("disabled_text");
	});
}
// IE requires a special approach for the main menu:
function ieHover() {
	$("#header li").hover(
		function () {
			$(this).addClass("hover");
		},
		function () {
			$(this).removeClass("hover");
		}
	);
	// And for our CSS dropdown list:
	$(".dropdownList").hover(
		function () {
			$(this).addClass("hover");
		},
		function () {
			$(this).removeClass("hover");
		}
	);
}

/*
 * Video support
 */
var player = null;

function FlowPlayer(key, videoID, videoFile) {
	var player = flowplayer(videoID,
		"/flowplayer/flowplayer.commercial-3.2.2.swf",
		{
			key: key,
			clip: {
				baseUrl: '/flash/',
				url: videoFile,
				autoPlay: true, 
				autoBuffering: true,
				bufferLength: 5,
				fadeInSpeed: 500
			},
			canvas: {
				backgroundColor: "#000000"
			},
			plugins: {
					TMPlugin: {
					url: 'http://static.inplay.tubemogul.com/bootloader/TubeMogulFlowPlayer.swf',
					playerID: 'P-EFS-IKY',
					trackerIDs: 'TR-J6U-XNS',
					publisherID: 'broadcom.com',
					videoID: videoFile,
					displayName: videoFile
				},
				gatracker: {
					url: "/flowplayer/flowplayer.analytics-3.2.0.swf",
					labels: {
						start: "Start",	
						play: "Play",	
						pause: "Pause",	
						resume: "Resume",	
						seek: "Seek",	
						stop: "Stop",	
						finish: "Finish",	
						mute: "Mute",	
						unmute: "Unmute",	
						fullscreen: "Full Screen",	
						fullscreenexit: "Full Screen Exit"	
					},
				debug: false,
				trackingMode: "AS3",
				googleId: "UA-2678116-1"
				},
				viral: {
					url: "/flowplayer/flowplayer.viralvideos-3.2.1.swf",
					share: {
						description: 'Broadcom Video',
						digg:false,
						myspace:false,
						livespaces:false,
						orkut:false,
						stubmbleupon:false,
						bebo:false
					},
					email: false,
					embed: false
				},
				controls: {
					timeBgColor: '#555555',
					buttonOverColor: '#B30924',
					sliderGradient: 'none',
					durationColor: '#FFFFFF',
					volumeSliderColor: '#000000',
					progressGradient: 'medium',
					timeColor: '#EB0024',
					backgroundColor: '#000000',
					tooltipTextColor: '#FFFFFF',
					progressColor: '#9E0005',
					bufferColor: '#8F0005',
					tooltipColor: '#5F747C',
					backgroundGradient: 'low',
					borderRadius: '0',
					volumeSliderGradient: 'none',
					buttonColor: '#750012',
					bufferGradient: 'none',
					sliderColor: '#000000',
					height: 20,
					opacity: 1.0
				}
			}
		});
	
	return player;
}

function playOverlayVideo(videoFile, videoID, showPlaylist) {
	if (typeof(fpKey) == "undefined")
		return;

	var divInfo = document.getElementById("overlay_videoinfo");
	if (divInfo != null && videoID != null) {
		var title = videos[videoID][1];
		var description = videos[videoID][2];
		divInfo.innerHTML = description;
	}

	//NB: This depends on being the same global 'player' var as the overlay,
	//    so that stop-on-close works
	player = FlowPlayer(fpKey, "overlay_videoplayer", videoFile);
	$(function() {
		player.play([{url: videoFile}]);
	});

	if (showPlaylist == null)
		showPlaylist = false;
	$("#overlay_videoplaylist").toggle(showPlaylist);
}

/*
 * Downloads
 */
function eulaDownload(file) {
	window.open('/support/license.php?file=' + file, '_download',
		'height=550,width=640,location=no,menubar=no,resizable=yes,status=no,toolbar=no,scrollbars=yes');
	statDownload('eula/' + file);
	return false;
}

function statDownload(file) {
	if (googleTracker != null)
		googleTracker._trackPageview(file);
}

function statSubmitEvent(category) {
	if (googleTracker != null)
		googleTracker._trackEvent(category, 'Submit', "'" + window.location + "'", 1);
}

/* survey */
function toggleSurveyQuestion(key) {
	if (key) {
		$('#div_license').hide();
		$('#div_survey').show();
	}
}

