// JavaScript Document

$(document).ready(function(){
	//Ribbon Exclusions
	//RibbonExclusions();
	mainmenu2();
    doWatermark();
	contentTabs();
	contentVideoHead();
	contentSuiteAccordion();
	contentTabsAccordion();
	rightnavbar();	
	LeftNavRelated();
	assignBodyID();
	addLeftNavSelectState();
	unHideContent();


});

//Top Nav
/*
function mainmenu(){
$(" #topNav ul ").css({display: "none"}); // Opera Fix
$(" #topNav li").hover(function(){
		$(this).find('ul:first').css({visibility: "visible",display: "none"}).show(400);
	},function(){
 		$(this).find('ul:first').css({visibility: "hidden"});
	});
}
*/

//Search Watermark
function doWatermark() {
    $('form').submit(function() {
        $('.textWatermark').each(function() {
            if ($(this).attr('value') == $(this).attr('defaultvalue'))
                $(this).attr('value', '');
        });
    });

    $('.textWatermark').each(function() {
        if ($(this).attr('value') == '')
            $(this).attr('value', $(this).attr('defaultvalue'));

        if ($(this).attr('value') == $(this).attr('defaultvalue'))
            $(this).css('color', $(this).attr('watermarkcolor'));
    });

    $('.textWatermark').focus(function() {
        if ($(this).attr('defaultvalue') == $(this).attr('value')) {
            $(this).attr('value', '');
            $(this).css('color', 'black');
        }
    });

    $('.textWatermark').blur(function() {
        if ($(this).attr('value') == '') {
            $(this).attr('value', $(this).attr('defaultvalue'));
            $(this).css('color', $(this).attr('watermarkcolor'));
        }
    });
}

function ShowDefault2()
{

   if (typeof collapseAccordionPanes != "undefined") {
   } else {
      var collateral = jQuery.url().param("sBD");
      if ( typeof(collateral) != 'undefined' &&  
		$('div.suiteBox > h3#'+collateral).length ) {
			$('div.suiteBox> div').hide();	
			$('div.suiteBox > h3#'+collateral).next('div').show('fast')
			.end().find('span:eq(0)').addClass('open');

      } else {

		$('div.suiteBox> div:gt(0)').hide();	
		$('div.suiteBox> div:eq(0)').show('fast');
		$('div.suiteBox> h3 > span:eq(0)').addClass('open');
		$('#acc-w-tabs .suiteBox > h3:eq(0)').addClass('open');
	}
    } 
}


function contentSuiteAccordion() {
	
	if(typeof accordianShow2 != "undefined")
	{
		if(isNaN(accordianShow2) || accordianShow2 <0 || accordianShow2 >=4)
			ShowDefault2();
		else
		{
			var txt = '('+accordianShow2+')';
			
			$('div.suiteBox> div:gt'+txt).hide();
			$('div.suiteBox> div:lt'+txt).hide();
			$('div.suiteBox> div:eq'+txt).show('fast');
			$('div.suiteBox> h3 > span:eq'+txt).addClass('open');
			$('#acc-w-tabs .suiteBox > h3:eq'+txt).addClass('open');
		}
	}
	else
		ShowDefault2();
		
 	$('div.suiteBox > h3').click(function() {
		//enable omniture tracking	
		if ($(this).next('div').is(':hidden') ){
				 	node = $(this).find("span:first");
					strText =  $(node).text() + " Content Accordion";
					omnitureTrackClick(strText,"suiteBox");
		}								  
										  
										  
 		$(this).next('div').slideToggle('fast')
 		.siblings('div:visible').slideUp('fast');
		
		$(this).children('span').toggleClass('open');
		$(this).siblings().children('span').removeClass('open'); 
	});
	$('#acc-w-tabs .suiteBox > h3').click(function() {
		$(this).toggleClass('open');
		$(this).siblings('h3').removeClass('open'); 
	});

}

function contentTabs() {
	// Tabs
	$(function() {
		//$("#flowtabs").tabs("#flowpanes > div").history();
		// format for jquery 1.4.3+
		$("#flowtabs").tabs("#flowpanes > div",{history:true});
	
		try {
		//allow multiple tab containers on single page - no history 
		//Toolbox history plugin does not maintain history properly when multiple flowtabs
		//if ($(".subtabs").tabs(".subpanes > div").history  == 'function')
		   //$(".subtabs").tabs(".subpanes > div").history();
		   $("#acc-w-tabs .subtabs").tabs(".subpanes > div");
		} catch (err) {}
	});
	$("#flowtabs a").click(function() {
			omnitureTrackClick(this,"flowtabs");
	});
	
	// tabs within accordian
	$("#acc-w-tabs .subtabs a").click(function() {
			accItem = $(this).parents('div').prev('h3');
			idx = $("#acc-w-tabs .suiteBox > h3").index(accItem);				
			omnitureTrackClick(this,"flowtabs", "Content Accordion " + idx + " -- ");
	});
}

function contentVideoHead() {

	// Initialize the video tabs (thumbnails)
        // When toggling between tabs, send a stop event for the previous
        // visible video
        $(".vidHeadThumbs").tabs(".vidHead > div", {

		onBeforeClick: function() {
        		if ($('#video1').is(':visible') ){
				//alert('send stop for video 1');
                		$('#video1')[0].sendEvent('STOP');
       		 
			}
        		if ($('#video2').is(':visible') ){
				//alert('send stop for video 2');
                		$('#video2')[0].sendEvent('STOP');
        		
			}
		}

	});


	//set up tooltips
	try {
	$(".vidHeadThumbs li a[title]").qtip({ 
		style: { 
		background:'transparent url("/images/videoHeader/tooltip.gif") repeat scroll 0 0',
		color:'#424241',
		border:0 
		}, 
                position: { corner: { target:'topLeft', tooltip:'bottomLeft' }, adjust:{x:0,y:-2}  } ,
		hide: { delay: 0 },
		show: { effect: { length: 2 } }
        });
 	} catch(err) {}

      // IE only: Add support for opening tabs from named hash links without a page refresh
      if (jQuery.browser.msie && (jQuery.browser.version < 8 || document.documentMode < 8) )
	{
      		$('.vidHeadLeft a').click(function() {
                		var url = $(this).attr('href');
				if (!url.match("^#.*"))
                                        return;
				if (url != '' && url != "#") {
                			url = url.replace(/^.*#/, '');
					//alert('url ->' + url);
					targetTab = $('#flowtabs li').find("a[href='#"+url+"']");
                			targetTab.click();
				 }
				return false;
		});
	}
}

function LeftNavRelated()
{
	// Related Info Drop Down
	// Show 3 items, show the more if remainding items is > 1
	var Count = 2;
	var minShow = Count;
    var liCount = $("#leftsidebar #relatedinfo li").size();
	
	//don't hide one item
	if ( (liCount > Count+1) && (liCount - (Count+1)) == 1 )		
    	Count=Count + 1;
		
    ShowItems(Count);
	
	if (liCount <= Count || liCount <= Count+1){
		return false;		
	}
	
	if ( $("#more").length )
		$("#more").text('More');
	else
		$('#leftsidebar #relatedinfo > ul').after('<p id="more" class="link">More</p>');
			
    $("#more").click(function(){
		
		if($(this).hasClass('less')){
			Count = minShow;
			ShowItems(Count);
			$("#more").text('More');
			$(this).removeClass('less');
		}
		
		else {
			Count = $("#leftsidebar #relatedinfo ul li").size();
			ShowItems(Count);	
			$("#more").text('Less');
			$("#more").addClass('less');
		}
    });
}


function ShowItems(Count) {
    if (Count > $("#relatedinfo li").size()) { Count = $("#list li").size() };
    $("#leftsidebar #relatedinfo ul li:lt(" + Count + ")").show();
	$("#leftsidebar #relatedinfo li:gt(" + Count + ")").hide();
	
}

function rightnavbar() {
	// Default slide  to display is 1 unless specific. You can set the default slide  
	// by setting the variable sideBoxDefault=slideId OR passing the parameter in the URL
	// ?sideBoxDefault=slideId
	// Order:  (1) Uses URL parameter first if passed, (2) explict defined variable, (3) default to
	// first slide.
	// Example: 
	       //<script> sideBoxDefault=sideNews <\/script> OR
		   // in the URL: ?sideBoxDefault=sideNews
	//var collateral = jQuery.url.param("sBD");	
	var collateral = jQuery.url().param("sBD");	

	if (typeof(collateral) != 'undefined') {
		sideBoxDefault = collateral;
		if (!$("div.sideBoxes h3[id='"+sideBoxDefault+"']").length)
			sideBoxDefault = undefined;
	} 
	
	if (typeof(sideBoxDefault) != 'undefined')
		$('div.sideBoxes h3#'+sideBoxDefault).next('ul').show('fast');
	else 
		$('div.sideBoxes> ul:lt(1)').show('fast');
 	// $('div.sideBoxes> ul:gt(0)').hide();
 	$('div.sideBoxes> h3').click(function() {
		if ($(this).next('ul').is(':hidden') || $(this).parents(':hidden').length)
				omnitureTrackClick(this,"sideBoxes");
 		$(this).next('ul').slideToggle('fast')
 		.siblings('ul:visible').slideUp('fast');
 	});
	
}

// assign body id
// get base folder using url.segment(0)
// and match folder with navigation menu
// use following mapping (foldername<|> --> Body ID we need to set to)
// aboutus|careers|investors|news_events|partners --> aboutUs
// innovation --> innovation
// markets|portfolios|products|product_index --> products
// services|product_services|training --> services
// solutions --> solutions
// success --> success
function assignBodyID() {
	var map = new Object();  
	map['aboutus'] = 'aboutUs';  
	map['careers'] = 'aboutUs';  
	map['investors'] = 'aboutUs';
	map['news_events'] = 'aboutUs';
	map['news-events'] = 'aboutUs';
	map['partners'] = 'aboutUs';
	map['products'] = 'products';
	map['markets'] = 'products';
	map['portfolios'] = 'products';
	map['product_index'] = 'products';
	map['services'] = 'services';
	map['product_services'] = 'services';
	map['training'] = 'services';
	map['solutions'] = 'solutions';
	map['success'] = 'success';
	map['innovation'] = 'innovation';
   	//var firstnode = jQuery.url.segment(0);
   	var firstnode = jQuery.url().segment(1);
   	var bodyid = map[firstnode];
  
	// assign body id if one doesn't exist to highlight global navigation
	if ($('body').attr('id')) {
    		// do nothing;
	} else {
	    // id attribute does not exist, so go ahead and assign one dynamically
	 	if (typeof(bodyid) == undefined)
		   	return false;
		if (typeof(firstnode) == undefined) {
			if ( firstnode.match('product_index') && jQuery.url().attr("path").search('/services') > -1) {
				bodyid="services";
			}
  		}
	   
		$('body').attr("id",bodyid);
		//$('body').attr("id",jQuery.url.segment(0));   //assigns id to body element
	}
}

function addLeftNavSelectState(){
	//alert(jQuery.url.attr("file"));
	var currentPathOrig = jQuery.url().attr("path") ;
	var currentPathFixed = currentPathOrig;
	var fileName = jQuery.url().attr("file") ;
	var dirName = jQuery.url().attr("directory") ;
	var newsevents = jQuery.url().param('filter');
	
	if ( fileName == "index.html" ) {
		currentPathFixed = dirName;
	} else if ( fileName == null ) {
		currentPathFixed = dirName + "index.html" ;
	}
	// alert("current path: " + currentPathFixed);
	if ($('#pagenav li > a').is('.select'))
		return false;
	
	//highlight news/events subitems (matches url+querystring)
	if(typeof(newsevents) != 'undefined' && !newsevents.match('all'))
		currentPathOrig = jQuery.url().attr('relative');

	if (typeof(leftNavUrlToMatch) != 'undefined')
		currentPathFixed = leftNavUrlToMatch ;

	$('#pagenav li > a').each(
			function(){
				//alert($(this).attr('href'));
				if( ($(this).attr('href') == currentPathOrig) || ($(this).attr('href') == currentPathFixed) ){
						$(this).addClass('select');
						return false;
					
				}
			}
		);

}

function unHideContent(){
	//Show for ClickMap: All related items, show all collapsed sideboxes
	var showText = jQuery.url().param("unHide");
	if (typeof(showText) != 'undefined' && showText == 1) {
		$("#leftsidebar #relatedinfo ul li").each(function() {
		$(this).show();	});
		$('div.sideBoxes> ul').show();
	}		
}

function omnitureTrackClick(node, type, extra) {
			var text = "";
			
			if(typeof(s) != 'undefined') {
				if (type.match("flowtabs")) {
						if (typeof(extra) != "undefined") 
							text = extra;

						text += $(node).text() + " Tab";
						
								}
				else if (type.match("sideBoxes")) {
						text = $(node).find("span:first").text() + " Category";
								}
				else  {
					if(typeof node == "object") {
					 	text = $(node).text(); 
					} else {
						text = node; 
					}
				}				
				
				var linkname = s.pageName + " -- " + text;
				//alert("a text ->" + linkname);
				s.linkTrackVars="None"
				s.linkTrackEvents="None"
				s.tl(this,'o',linkname);
			}
		      //enable google analytics tab click tracking
		      if (typeof(_gaq) != 'undefined') {
			try {
                      	   gaTrackClick(node,type,extra);
			} catch(err) {}
		      }
	
}

// Javascript to support Accordion within Tabs
function contentTabsAccordion() {
	
	  $("#tabs-w-accs #flowpanes>div").each(function() {
	// On page load, open first accordion pane for the active  tab.							   
	  if($(this).is(':visible')) 
		{ 	  
			
			$(this).find('> .suiteBox > div').eq(0).css({'display':'block'});
			$(this).find('> .suiteBox > h3 span').eq(0).addClass('open');
			 	
			  return false;
		 }
	  }); 

	// On click of active tab, show the accordion and open active pane 
	$("#tabs-w-accs ul#flowtabs > li > a").click(function() {
		activePane=0;
		var idx= $('#tabs-w-accs ul#flowtabs > li > a').index(this); 
		//alert('index ' + idx);
		var sel = $("#tabs-w-accs #flowpanes >div:eq("+idx+")");
			
		sel.find('> .suiteBox > div').each(function() {						 
		  if($(this).is(':visible')) {				 
				  activePane=1
				  return false;
			  }
		});
	
		if (activePane == 0 ) {			
			//sel.find('> .suiteBox > h3').eq(0).click();
			sel.find('> .suiteBox > div').eq(0).css({'display':'block'});
			sel.find('> .suiteBox > h3 span').eq(0).addClass('open');
			}
		});

	
	
}

// jquery.history.js - history support for mutliple flowtabs per page
$(document).ready(function(){
try {
  //plugin is loaded
  if ( typeof($.history.init) == 'function' ) {
	$.history.init(function(hash) {
        	if(hash != "") {			
			$(".subtabs li a[href='#"+hash+"']").trigger('click');                
        	}
        });
        $('.subtabs li  a').click(function(e) {
			
                        var url = $(this).attr('href');
                        url = url.replace(/^.*#/, '');
                        $.history.load(url);
                        //return false;
                });
  }
} catch(err) {}

});

//Top Nav
function mainmenu2() {
    $(" #topNav2 li div.flyOut ").css({ display: "none" }); // Opera Fix
    $(" #topNav2 li").hover(function() {
        $(this).find('div:first').css({ visibility: "visible", display: "none" }).show(100);
                $(this).addClass('active');
    }, function() {
        $(this).find('div:first').css({ visibility: "hidden" });
                $(this).removeClass('active');
    });
}

function RibbonExclusions() {
        var exclusions =  [ "/services/government", "/services/security", "/innovation" ];
        var url = window.location.pathname;
        for (var i = 0; i < exclusions.length; i++) {
           if( url.indexOf(exclusions[i]) > -1) {
                $('#top-ribbon').hide();
		$('body').css({'background-image':'none'});
		$('body').css({'margin-top':'20px'});
                return true;
           }
        }

}


