/********************************************/
// changelog
// mh 10/9/09 - changed onmouseover to onclick to activate the share widget
/********************************************/

document.getElementsByClassName = function(cl) {
	var retnode = [];
	var myclass = new RegExp('\\b'+cl+'\\b');
	var elem = this.getElementsByTagName('*');
	for (var i = 0; i < elem.length; i++) {
		var classes = elem[i].className;
		if (myclass.test(classes)) retnode.push(elem[i]);
	}
	return retnode;
};

function dgi(id) {
    return document.getElementById(id);
}

function dgc(id) {
    return document.getElementsByClassName(id);
}




/********************************************/
// TOP NAVIGATION FUNCTIONS
/********************************************/
var menuWait = 300;
var showNavTimeout;
var hideNavTimeout;
var showCountryTimeout;
var hideCountryTimeout;
var SubLength = new Array();
var SubDefault = new Array();
var navItem;
var testObj;
var g_PopupIFrame;

//sniffing for IE6
var isIE6 = /msie|MSIE 6/.test(navigator.userAgent); 



//initilization function to show navigational panel
function showNav(id, navId, navIdLink) {
	showNavTimeout = setTimeout("forceShowNav('"+id+"', '"+navId+"', '"+navIdLink+"')", menuWait);
}

//force navigation to display, if mouse over
function forceShowNav(id, navId, navIdLink) {
var ie6StyleFilter;
var ie6pngSrc;
var startImgSrc;
var endImgSrc;
var ie6Pngs = new Array();
	forceHideNav();
	try {
		
                //adding iframe for IE6 to prevent select boxes to show though 
		if (isIE6){

		//Increase default zIndex of div by 1, so that DIV appears before IFrame                 
                var iframeOn = 'iframe'+id;
		//Next line removed 2/17 - DG - z-index is in CSS
                //dgi(iframeOn).style.zIndex=2;
	        dgi(iframeOn).style.display='block';
		 // removed by MTH for re-skin	
         //       dgi(id).childNodes[0].style.backgroundImage="url('/shared/img/global/bkg-nav-flyout_btm.png')"; 
                //check if pngs exist
                var iePNGtoLoad = new Array();
                //code below responsible for displaying png in ie6
               var iePanel = dgi(id).childNodes[0];
               for (n=0; n<iePanel.getElementsByTagName('IMG').length; n++){  
                       ie6Img = iePanel.getElementsByTagName('IMG')[n];
                       var ieIMGclass=ie6Img.className;

                       if(ieIMGclass.indexOf('png')>-1){
                        var pngAlt = ie6Img.getAttribute('alt');
		        ie6StyleFilter=ie6Img.style.filter;
                        startImgSrc = ie6StyleFilter.indexOf('src=');
                        endImgSrc = ie6StyleFilter.indexOf('.png');
                        ie6pngSrc = ie6StyleFilter.substring(startImgSrc+5, endImgSrc+4);                        
                         var ie6pngParent = ie6Img.parentNode;
                         ie6pngParent.removeChild(ie6Img);                        
                         //recreate png image   
                         var ie6newpng = document.createElement("img");  
                         ie6newpng.setAttribute("src",ie6pngSrc);  
                         ie6newpng.setAttribute("class",ieIMGclass);                 
                         if(pngAlt){
                         ie6newpng.setAttribute("alt",pngAlt);
                         }                         
                         
                         ie6pngParent.appendChild(ie6newpng);
		  				 }
               }                                                	
         }	
	
               //display nav panel	
		dgi(id).style.display = "block";
               //switch navbar item background when navpanel is on	
		dgi(navId).style.backgroundImage='url(/shared/img/header/bkg-navbar-hover.gif)';
		dgi(navIdLink).style.color='#1a1a1a';
		dgi(navIdLink).style.backgroundImage='url(/shared/img/header/arrow-navbar-open.gif)';		
		
	} catch (e) {}
}

//initilization function to hide navigational panel
function hideNav(navId) {
	clearTimeout(showNavTimeout)
	hideNavTimeout = setTimeout("forceHideNav()", menuWait);
}

//force navigation to hide, if mouse out
function forceHideNav() {
	try {
	
         //removing iframe properties and killing it 
	if (isIE6)
		{		
		dgi('iframeflyout1').style.display='none';
		dgi('iframeflyout2').style.display='none';
		dgi('iframeflyout3').style.display='none';		
		}
                
                //remove background from navigation item
		dgi('_solutions_').style.backgroundImage='';
                //remove link color from navigation item to change it to default
		dgi('topbarlink1').style.color='';
                //remove background image from link in navigation item
		dgi('topbarlink1').style.backgroundImage='';
		
		dgi('_products-services_').style.backgroundImage='';
		dgi('topbarlink2').style.color='';
		dgi('topbarlink2').style.backgroundImage='';
		
		dgi('_company_').style.backgroundImage='';		
		dgi('topbarlink3').style.color='';
		dgi('topbarlink3').style.backgroundImage='';
                //dgi('topbarlink1div').style.backgroundImage='';
                //dgi('topbarlink2div').style.backgroundImage='';
                //dgi('topbarlink3div').style.backgroundImage=''; 
                //dgi('topbarlink1div').style.color='';
                //dgi('topbarlink2div').style.color='';
                //dgi('topbarlink3div').style.color='';   

	    //hiding flyout panels
	   dgi("flyout1").style.display = "none";
	   dgi("flyout2").style.display = "none";
	   dgi("flyout3").style.display = "none";

	} catch (e) {}
}

/********************************************/
// COUNTRY SELECTION DROP DOWN IN HEADER
/********************************************/

function showCountry() {
	clearTimeout(hideCountryTimeout)
	showCountryTimeout = setTimeout("forceShowCountry()", menuWait);
}

function forceShowCountry() {
	dgi("topCountryDrop").style.display = "block";
	try{
          if (isIE6){
		dgi('topCountryDrop').childNodes[0].style.background="url('/shared/img/global/bkg-countryDrop.png')";
            }
	} catch(e) {}
}

function hideCountry() {
	clearTimeout(showCountryTimeout)
	hideCountryTimeout = setTimeout("forceHideCountry()", menuWait);
}

function forceHideCountry() {
    dgi("topCountryDrop").style.display = "none";
}

/*
function showCountry() {
	clearTimeout(hideCountryTimeout)
	showCountryTimeout = setTimeout("forceShowCountry()", menuWait);
}

function forceShowCountry() {
	dgi("topCountryDrop").style.display = "block";
}

function hideCountry() {
	clearTimeout(showCountryTimeout)
	hideCountryTimeout = setTimeout("forceHideCountry()", menuWait);
}

function forceHideCountry() {
    dgi("topCountryDrop").style.display = "none";
}

*/

//HOME PAGE FEATURE CLICK THROUGH
function showHomeFeature(id) {
	dgi(lastHomeFeature).style.display = "none";
	//dgi(homeTabLink+lastHomeFeature).style.color = "#4b4b4b";
	lastHomeFeature = id;
	dgi(lastHomeFeature).style.display = "block";
	//dgi(homeTabLink+lastHomeFeature).style.color = "#006FBA";
}

function showHomeSub(id, diff) {
	dgi(id+SubDefault[id]).style.display = "none";
	SubDefault[id] = SubDefault[id] + diff;
	if (SubDefault[id] < 1) SubDefault[id] = SubLength[id];
	if (SubDefault[id] > SubLength[id]) SubDefault[id] = 1;
	dgi(id+SubDefault[id]).style.display = "block";
}

/********************************************/
// toggle function to open close content by 
//clicking on '-' '+' buttons
/********************************************/

function toggleSimple(id, btnId){
var btnOn='url(/shared/img/global/btn-tClose-s.gif)';
var btnOff='url(/shared/img/global/btn-tOpen-s.gif)';
	if (dgi(id).style.display=='none'){
		dgi(id).style.display='';
		dgi(btnId).style.backgroundImage=btnOn;
	}
	else {
		dgi(id).style.display='none';
		dgi(btnId).style.backgroundImage=btnOff;
   }
}

/* AddThis vars */
var addthis_pub  	= 'webanalytics';
var addthis_brand	= 'Juniper Networks';
addthis_options		= '';

/********************************************/
// SHARE WIDGET FUNCTIONALITY
/********************************************/
function drawShare(options) {
	  addthis_options = options;
	  
	  var el = document.createElement('script');
	if(document.location.protocol == "https:") {
		dgi("shareBtn").innerHTML = "<a href=\"#\" onclick=\"return addthis_open(this, '', '[URL]', '[TITLE]')\" onmouseout=\"addthis_close()\"><img src=\"https://secure.addthis.com/static/btn/lg-share-"+addthis_language+".gif\" width=\"125\" height=\"16\" border=\"0\" alt=\"Share\" /></a>";
		el.src = 'https://secure.addthis.com/js/152/addthis_widget.js';
	} else {
		dgi("shareBtn").innerHTML = "<a href=\"#\" onclick=\"return addthis_open(this, '', '[URL]', '[TITLE]')\" onmouseout=\"addthis_close()\"><img src=\"http://s7.addthis.com/static/btn/lg-share-"+addthis_language+".gif\" width=\"125\" height=\"16\" border=\"0\" alt=\"Share\" /></a>";
		el.src = 'http://s7.addthis.com/js/152/addthis_widget.js';
	}
	  dgi("shareBtn").appendChild(el);
}

//function which adds to the queue of functions to execute upon window.onload
function addToOnload(newFunc,params) {
	var currentOnload = window.onload;
	window.onload = function() {
		if(currentOnload != null && typeof currentOnload == "function") {
			currentOnload();
		}
		if (params != null) {
			newFunc(params);
		} else {
			newFunc();
		}
	};
}

/******************************************/
// loading gallery images in order to fire gallery widget from flash
/********************************************/
function genGallery() {
/*	mmGalleryArray = new Array();
	for (i=0;i<arguments.length;i++) {
		mmGalleryArray[i] = new Image()
		mmGalleryArray[i].href=arguments[i];
	}
*/


}

/******************************************/
//function to call thickbox for ProductCompare
//PRODUCT COMPARISON TABLE
/******************************************/
//comparison table call variables
var tb_PComp_title = "Product Comparison";
var tb_xslPath = "/shared/xsl/product-compare/compare.xsl";
var tb_fragmentPath="/fragment.do";
var tb_xmlPath="/us/en/modules/compare-test-z-series.xml";
var tb_PCopm_params = "&height=300&width=500&compPP=true"

//function to  call comparison table in thickbox
function productCompareThickBox(xmlPath){
	pathToPCompFile="http://"+location.hostname+tb_fragmentPath + "?xmlPath="+tb_xmlPath + "&xslPath="+tb_xslPath +tb_PCopm_params;
	tb_show(tb_PComp_title, pathToPCompFile);		
}

function showDefaultEvent() {
	if (typeof(defaultEvent) != "undefined") {
		dgi("eventTable" + defaultEvent).parentNode.style.display = "block";
	} else {
		var eventTables = dgc("eventTableDiv");
		if(eventTables.length > 0 ) {
			eventTables[0].parentNode.style.display = "block";
		}
	}
	
	checkEventHash();
}

function switchEvent(id) {
		var eventTables = dgc("eventTableDiv");
		for (i in eventTables) {
			eventTables[i].parentNode.style.display = "none";
		}
		dgi("eventTable" + id).parentNode.style.display="block";
}

//this is useful to strip location URL in object
//i do not use this yet  ~ emk(12/08/08)
function parseUri (str) {
	var	o   = parseUri.options,
		m   = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
		uri = {},
		i   = 14;

	while (i--) uri[o.key[i]] = m[i] || "";

	uri[o.q.name] = {};
	uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
		if ($1) uri[o.q.name][$1] = $2;
	});

	return uri;
};

parseUri.options = {
	strictMode: false,
	key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],
	q:   {
		name:   "queryKey",
		parser: /(?:^|&)([^&=]*)=?([^&]*)/g
	},
	parser: {
		strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
		loose:  /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
	}
};

/******************************************/
// NAVIGATION HIGHLIGHT 
/********************************************/

/*  
exeptions for support
/customers/ 
/support/   
/spgdownloads/ 
/techpubs/ 

 for partners
/partners/ 
*/ 

//exceptions for navigation highlight, where name is id for nav item div, 
//value - exeption in URL to be highlighted
var navExceptions = new Array(
	 {name:'_support_', value:'/customers/'},
	 {name:'_support_', value:'/support/'},
	 {name:'_support_', value:'/spgdownloads/'},
	 {name:'_support_', value:'/techpubs/'},
	 {name:'_training_', value:'/training/'},
	 {name:'_partners_', value:'/partners/'},
	 {name:'_company_', value:'/company/partners/'});

//define correct directory for highlight
function getDir(){
	var cDir = location.pathname;
	var cDirEx ='';
	for(i=0; i<navExceptions.length; i++){
	  if(cDir.indexOf(navExceptions[i].value)>-1){
		cDirEx = navExceptions[i].name;	
	  }										  
	}
	
	if(cDirEx!=''){
	cDir=cDirEx;
	}
	else{
	cDir=cDir.substring(7, cDir.length);
	cDir=cDir.substring(0, cDir.indexOf('/'));
	//var reFirstDir = /^/
	cDir = '_'+cDir+'_';
	}
	return cDir;	
 }

var navSections = new Array('solutions', 'products-services', 'company', 'partners', 'support', 'training');

var navOnObj='';
var topNavBar;

//actual highlight
function topNavOn(){
 	
	var navDir = getDir();
	topNavBar = document.getElementById('navbar');
	
	for (i=0; i<topNavBar.childNodes.length; i++){
		if(topNavBar.childNodes[i].nodeName=='DIV'){
			var divAttr = topNavBar.childNodes[i].attributes;
			for (j=0; j<divAttr.length; j++){
				if(divAttr[j].name=='id'){
					var idValue = divAttr[j].value;
					if(idValue.indexOf(navDir) >-1) {
						topNavBar.childNodes[i].className += ' navOn'; 
						navOnObj = topNavBar.childNodes[i];
					}
				}
			}
		}
	}
}

//adding navigation highlight on window load

addToOnload(topNavOn);

function fillMetaDesc(name, value) {
	var elemArray = document.getElementsByTagName("META");
	for (i in elemArray) {
		if(elemArray[i].name == name) {
			elemArray[i].content = value;
			return;
		}
	}
}

//Set Content Group and subgroup and search subgroup
function setPathMeta() {
	var subStrings = location.pathname.substring(1,location.pathname.length).split("/");
	try {
		fillMetaDesc("WT.cg_n", subStrings[2]);
	} catch(e) {}
	var subCatString = "";
	if (subStrings.length > 3) {
		for (i=subStrings.length-1; i > 2; i--) {
			if ((subCatString.length + subStrings[i].length + 1) < 80) {
				if(subCatString != "") {
					subCatString = subStrings[i] + ";" + subCatString;
				} else {
					subCatString = subStrings[i];
				}
			} else {
				break;
			}
		}
	} 
	try {
		fillMetaDesc("WT.cg_s", subCatString );
	} catch(e) {}

	try {
		dgi("searchSubgroup").value = subStrings[2];

	} catch(e) {}
}
	
//necessary for javascript to call actionscript functions
function getFlashMovie(movieName) 
{
      var isIE = navigator.appName.indexOf("Microsoft") != -1;
      return (isIE) ? window[movieName] : document[movieName];
}

//------------------------------

function newsTickerInit() {
	if (newsItems > 0) {
		for (i=1; i<=newsItems;i++) {
				tickerItemArray.push("news"+i);
		}
	}
	if (eventItems > 0) {
		for (i=1; i<=eventItems;i++) {
				tickerItemArray.push("event"+i);
		}
	}
	if (tickerItemArray.length > 0) {
			currentTickerObj = 0;
			tickerInterval = setInterval("newsTicker(1);", 15000);
	}
}

function newsTicker(which) {
	try {
		nextTickerObj = currentTickerObj + which;
		if (nextTickerObj < 0) nextTickerObj = tickerItemArray.length - 1;
		if (nextTickerObj == tickerItemArray.length) nextTickerObj = 0;
		dgi(tickerItemArray[currentTickerObj]).className = "tickerBodyOff";
		dgi(tickerItemArray[nextTickerObj]).className = "tickerBody";
		currentTickerObj = nextTickerObj;
	} catch (e) {	}
}

function newsTickerClick(which) {
		clearInterval(tickerInterval);
		newsTicker(which);
}

//+++++++++++++++++++++++++++++
//COOKIE'S FUNCTIONS
//+++++++++++++++++++++++++++++
//set up cookie with parameters
function setCookie(c_name, c_value, c_path, c_expiredays, c_secure){
	if(c_expiredays){
     var exdate=new Date();
     exdate.setDate(exdate.getDate()+c_expiredays);
	 }
	 
   document.cookie=c_name+ "=" +escape(c_value)+ 
   ((c_expiredays==null) ? "" : ";expires="+exdate.toGMTString())+
   ((c_path == null) ? "" : ";path=" + c_path)+
   ((c_secure==null) ? "" : ";secure");
   ;
}

//function to get cookie by name
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 "";
}

//function to get akimai cookie country name
//and update meta tag content of 'DCSext.country_origin'
function getACountryName(){
var akimaiCookie = getCookie('CT_AKAMAI');
  if(null != akimaiCookie && akimaiCookie !=""){
  var aCvalue=readACookie(akimaiCookie ,'country_code'); 
  fillMetaDesc('DCSext.country_origin', aCvalue) ;
 }

}

//adding to onload function to check Akimai cookie for country name
//code and if it exist update meta tag with it
addToOnload(getACountryName);

function readACookie(cookie, valueName) {
	var cValue;
	var ca = cookie.split(',');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(valueName) != -1) {
                   cValue=c.substring(c.indexOf('=')+1,c.length);
                  return cValue;
                 }

	}
	return null;
}

//Check logged in status
function checkLoggedIn() {
	var urlLess = document.location.toString();
	urlLess = urlLess.substring(urlLess.indexOf(document.location.pathname));

	//Eject if we are not on a page that should have the links
	if (urlLess.indexOf('/customers/support/') != 0 && urlLess.indexOf('/us/en/partners/') != 0 && urlLess.indexOf('/support/') != 0 && urlLess.indexOf('/spgdownloads/') != 0 && urlLess.indexOf('/partners/') != 0) {
		return true;
	}

	var inPublicCSC = (document.location.pathname == '/customers/support/') ? true:false;
	var inPublicPartners = (document.location.pathname.indexOf('/us/en/partners/')!=-1) ? true:false;
	var partnerCookie = getCookie('JNPRPART');
	var cscCookie = getCookie('JNPRCUST');
	var cscLoggedIn = (null != cscCookie && cscCookie != "" && cscCookie.split("|")[cscCookie.split("|").length - 1] == "loggedin") ? true: false;
	var partnerLoggedIn = (null != partnerCookie && partnerCookie != "" && partnerCookie.split("|")[partnerCookie.split("|").length - 1] == "loggedin") ? true: false;
	var loggedTop = dgi("loggedTop");
	var logOutTag = (null != loggedTop) ? loggedTop.getElementsByTagName('a')[2]:null;

	if (inPublicPartners) {
		if (partnerLoggedIn) {
			if (null != dgi('loginBox')) dgi('loginBox').style.display="none";
			if (null != loggedTop) loggedTop.style.display="block";
			if (null != logOutTag) logOutTag.href = "/partners/partner_center/logout.jsp";
		}
	} else if (inPublicCSC) {
		if (cscLoggedIn || partnerLoggedIn) {
			var lBox = dgi('loginBox');
			if (lBox != null) lBox.style.display="none";
			if (null != loggedTop) loggedTop.style.display="block";
		}
		if (cscLoggedIn && !partnerLoggedIn) {
			if (null != logOutTag) logOutTag.href = "/customers/support/logout.jsp";
		}
		if (!cscLoggedIn && partnerLoggedIn) {
			if (null != logOutTag) logOutTag.href = "/partners/partner_center/logout.jsp";
		}
	} else {
		if ((cscLoggedIn && !partnerLoggedIn) || urlLess.indexOf('/customers/support/') == 0 || urlLess.indexOf('/support/') == 0 || urlLess.indexOf('/spgdownloads/') == 0) {
			if (null != logOutTag) logOutTag.href = "/customers/support/logout.jsp";
		}
		if ((!cscLoggedIn && partnerLoggedIn) || urlLess.indexOf('/partners/') == 0) {
			if (null != logOutTag) logOutTag.href = "/partners/partner_center/logout.jsp";
		}
		if ((null != loggedTop) && (cscLoggedIn || partnerLoggedIn)) {loggedTop.style.display="block";}
	}
}

//adding check logged status on window load
addToOnload(checkLoggedIn);

//Check for addressed event
function checkEventHash() {
	try {
		if (document.location.hash != '') {
			var hashSplit = document.location.hash.split("|");
			if(hashSplit.length > 1) {
				switchEvent(hashSplit[1]);
				toggleSimple('a'+hashSplit[1]+hashSplit[2], 't'+hashSplit[1]+hashSplit[2]);
			}
		}
	} catch (e) {}
}
