/**
 *  Utility functions
 *  util.js
 *  $Revision: 1.19 $
 */

if (typeof (cdc) == "undefined") cdc = new Object();
if (typeof (cdc.util) == "undefined") cdc.util = new Object();
cdc.util.ensureNamespace = function (namespaceStr) {
    if (!namespaceStr) return;
    var parts = namespaceStr.split (".");
    var o = window;
    for (var i = 0; i < parts.length; i++) {
        var aPart = parts[i];
        if (typeof (o[aPart]) != "object") {
            o[aPart] = new Object();
        }
        o = o[aPart];
    }
}

// skeleton debug framework
if (typeof cdc.debug == "undefined") cdc.debug = {};
cdc.debug.log   = function() {};
cdc.debug.dump  = function() {};
cdc.debug.alert = function() {};

// Window Opening / Closing Functions

function openChildWindow( appurl, windowname ) {
  global_openCdcPopup({address:appurl,width:798,height:547,top:25,left:0,windowName:windowname});
}

function global_openCdcPopup(url, width, height) {
  if (!url) {return true;} //where url is not supplied do nothing

  var windowControls='';
  var windowOptions='';
  var windowName = 'globalCDCpopup';

  if(typeof(url) == "object"){
     // create temp variables to function params map
     width  = url.width;
     height = url.height;
     xtop = typeof(url.top) != "undefined" ? url.top : ''; //named "xtop" because "top" kills IE
     left = typeof(url.left) != "undefined" ? url.left : '';
     windowOptions = "top="+xtop+",left="+left+",";
     if(typeof(url.windowName) != "undefined"){windowName = url.windowName;};

     if (url.controls != false){ //undefined = true
       if(typeof(url.location) != "undefined" && url.location == "no"){
          var windowControls = ",toolbar=yes,location=no,menubar=yes";
       }else{
          var windowControls = ",toolbar=yes,location=yes,menubar=yes";
       }
     }
     url = url.address;   // doing this last because it nukes the url object
  }

  width = isNaN(parseInt(width)) ? 550 : parseInt(width);
  height = isNaN(parseInt(height)) ? 550 : parseInt(height);

  /* ie scrollbar behaviour adjustment */
  if(document.all){ width = width+20; }

  windowOptions +=  "width="+width+",height="+height+",status=yes,scrollbars=yes,resizable=yes"+windowControls;
  var popup = window.open ( url, windowName, windowOptions);
  if (popup) popup.focus();
  return false;
}

// This function openLargePopup is now deprecated. Please don't use.
function openLargePopup( url, windowname ) {
  var popup = window.open( url , windowname, "toolbar=yes,status=yes,scrollbars=yes,menubar=yes,locationbar=no,top=50,left=70,outerWidth=643,outerHeight=468,width=643,height=468,resizable=yes");
  if (popup) popup.focus();
}

// This function openMediumPopup is now deprecated. Please don't use.
function openMediumPopup( url, windowname ) {
  var popup = window.open( url , windowname, "toolbar=no,status=yes,scrollbars=yes,menubar=no,locationbar=no,top=90,left=170,outerWidth=445,outerHeight=390,width=445,height=390,resizable=yes");
  if (popup) popup.focus();
}

// This function openSmallPopup is now deprecated. Please don't use.
function openSmallPopup( url, windowname ) {
  var popup = window.open( url , windowname, "toolbar=no,status=yes,scrollbars=yes,menubar=no,locationbar=no,top=90,left=290,outerWidth=220,outerHeight=390,width=220,height=390,resizable=yes");
  if (popup) popup.focus();
}

function closeWindow() {
  self.close();
}

function changeParentUrl( newurl ) {
  var openerClosed = false;
  if( document.all && !document.getElementById() ) {
    // opener.closed always returns false in IE ... makes sense, right?
    // let's roll our own function in VB, where we can trap errors...
    openerClosed = isOpenerClosed();
  } else {
    if( top.opener ) {
      openerClosed = top.opener.closed;
    } else {
      openerClosed = true;
    }
  }
  if( openerClosed ) {
    var newwin = window.open( newurl);
    newwin.focus();
  } else {
    top.opener.location.href = newurl;
    top.opener.focus();
  }
}

// Creates a browser-generated alert or message box
// note:
// this was abstracted just in case we ever want to do anything
// with the string or send to non-pcs devices
function openMessage(str) {
  alert(str);
}

// Grabs a parameter from the URL.  Returns an empty
// string if parameter does not exist.
function getParameter(param) {

        var val = "";
        var qs = window.location.search;
        var start = qs.indexOf(param);

        if (start != -1) {
                start += param.length + 1;
                var end = qs.indexOf("&", start);
                if (end == -1) {
                        end = qs.length
                }
                val = qs.substring(start,end);
        }
        return val;
}

// Get the BaseTag, if specified in the current page
function get_baseTag() {
	var baseTag = "";
	if ( document.all ) {
		var baseTagsCol = document.all.tags("BASE");
		if (baseTagsCol.length!=0){
			baseTag = baseTagsCol[0].href;
		}
	} else if (window.opera) {
		var baseTag
		if (document.getElementById('basehref')){
			baseTag = document.getElementById('basehref').href;
			baseTag = baseTag.substring(0, baseTag.length-1);
		}
	}
	return baseTag;
}

// Drop-down location.href redirection
function dropdown_redirect(select_name,reset) {
	if (reset == null) { reset = true };
	var theselect=eval(select_name);
	var tmp=theselect.selectedIndex;
	if (reset) { theselect.options[0].selected=true; }
	if(theselect.options[tmp].value != "") {
		location.href=get_baseTag()+theselect.options[tmp].value;
	}
}

// Area drop-down redirection
var areanav_current = 0;
function set_areanav_current( index ) {
	// xsl position starts at 1, array index starts at 0
	areanav_current = index-1;
}
function areanav_redirect(select_name) {
  var theselect=eval(select_name);
  var tmp=theselect.selectedIndex;
  if(theselect.options[tmp].value != "") {
	 theselect.options[areanav_current].selected=true;
	 location.href=get_baseTag()+theselect.options[tmp].value;
  }
}


// functions used to register functions that execute on the global onClick event
var globalBodyOnClickList = new Array();

//function called to add a handler to the event
function addToBodyOnClick(funct){
    //assign the wrapper function to the event
    //this blows away any traditionally assigned handlers
    document.onclick = bodyOnClick;

    //add the function to the array
    globalBodyOnClickList[globalBodyOnClickList.length] = funct;
}

//function that gets called by the body's onClick event
function bodyOnClick(){
    for (var i=0;i<globalBodyOnClickList.length;i++){
        //do each of the functions in the array
        globalBodyOnClickList[i]();
    }
}

/* function used to register functions that execute on the global onLoad event
 * Revised Dec 2005 /gs
 */
/* Please note: this function is currently supported only for the homepage use
 * with Visual Sciences.  If it is used on any other pages, please be aware that
 * if there is an onload attribute in the body tag this function will not work.
 */
function addToWindowOnLoad(funct){
var oldOnload = window.onload;
if (typeof window.onload != 'function') {
window.onload = funct;
} else {
window.onload = function() {
oldOnload();
funct();
        }
    }
}

/* ---------------------------------------------------------------
   Cookie functions -
   global_setCookie and global_getCookie match the ones in
     collapsing_list.js for tdts-books. The rest are new.
   ---------------------------------------------------------------- */

//function returns the date that is 'days' days from now.
// (in milliseconds since 1/1/70 of course)

function global_daysFutureToTimeMS (days) {
  var mydate = new Date();
  var ms;
  mydate.setTime(mydate.getTime()+((days)*24*60*60*1000));
  ms = Date.parse(mydate);
  return ms;
}

function global_setCookie(name, value, days) {
  if (days) {
    var dateobj = new Date(global_daysFutureToTimeMS (days));
    var expdate = dateobj.toGMTString();
    var expires = "; expires="+expdate;
  } else {
    var expires = "";
  }
  //alert("expires="+expires);
  document.cookie = name+"="+value+expires+"; path=/; domain=cisco.com";
}

function global_getCookie(name) {
 var CValue = new String();
  CValue = document.cookie;
  var exp = new RegExp("^.*" + name + "=" );
  if (CValue.match(exp)){
    CValue = CValue.replace(exp,'');
    CValue = CValue.replace(/;.*/,'');
    //alert(name +" is currently set to "+CValue);
    return CValue;
  }
  //alert(name+" has no value yet");
  return "";
}

function global_extractCookieChip(cookiename,parmname) {
  //alert("extracting "+parmname+" from "+cookiename);
  var CValue = unescape(global_getCookie(cookiename));
  var PValue = new String();
  var namestr = "&"+parmname+"=";
  var start = CValue.indexOf(namestr);
  if (start > -1) {
    start += namestr.length;
    PValue = CValue.substring(start,CValue.length);
    //alert(PValue+"=PValue");
    if (PValue.indexOf("&") > -1) {
      PValue = PValue.substring(0,PValue.indexOf("&"));
    }
    return PValue;
  }
  return "";
}

function global_crumbleCookieChip(cookiename, parmname) {
  /* get cookie values in array */
  var CValue = unescape(global_getCookie(cookiename));
  if ( CValue.indexOf ("&", CValue) > -1) {
    var chips = CValue.split("&");
    var newchips = new String();

    /* reassemble without parm and rewrite */
    for ( var i=0; i < chips.length; i++) {
      if ( chips[i].indexOf(parmname) != 0 ) {
        if ( newchips == "") { chips[i] = "&"+chips[i]; }
        newchips += chips[i];
      }
    } /* end stepping through array */
    global_setCookie(cookiename, newchips, 366);
  } /* if there was no '&' we did nothing */
}

function global_addCookieChip(cookiename, newname, newvalue ) {
  global_crumbleCookieChip(cookiename,newname);
  var CValue = global_getCookie(cookiename);
  CValue += escape("&"+newname+"="+ newvalue);
  global_setCookie (cookiename, CValue, 366);
}

/*---------------------------------------------------------
  Intercept popup window decision process functions
------------------------------------------------------------ */

/* ------------------------------------------------------------------
  Use timedPop() to popup an intercept window only if they've been
  on-site for a while.

  They will NEVER get this window on the first page they come to,
  even if minutes=0. Use randomPop() instead if you need that

   minutes: how long they need to be onsite before getting popup
   frequency: how often to ask people - random number between 1 & frequency generated
   url: url of window to pop open
   stopcookie: name of cookie that lets you know they've been asked already
   expires: number of days to keep the stopcookie active
   windowsize: small, medium, large - defaults to large -- sizes defined in window opening functions
---------------------------------------------------------------------*/

function timedPop(minutes, frequency, url, stopcookie, expires, windowsize ) {
  myDomain = window.location.host;

  if ( (myDomain == "cisco.com" || myDomain == "www.cisco.com" || myDomain == "elovejoy-lnx" || myDomain == "maunaloa" || myDomain == "maunaloa.cisco.com" || myDomain == "newsroom.cisco.com" ) && window.location.pathname.match("/en/US/") ) { /* don't let this interfere w/ apps or theaters */

    timeCookie= "CDCsitetimer";

    /* check for time cookie */
    now = new Date();
    nowMinutes = now.getTime()/60000;

    if ( cookietime = global_getCookie(timeCookie)) {
      // alert("long enough? cookietime="+cookietime +" & now is " 	+nowMinutes);

      if ( cookietime != "Done" && (nowMinutes - cookietime) >= minutes )   {
        // alert("time to pop");
        randomPop(frequency,  url, stopcookie, expires, windowsize);
        global_setCookie(timeCookie,"Done", 0);
      }

    } else {
      /* if they don't have a timer make one */
      global_setCookie(timeCookie,nowMinutes, 0);
   }
   //} else { alert("we don't pop on your domain");

  } /* end domain check */
}

/* -------------------------------------------------------------------
 randomPop() will popup an intercept window if the randomly generated number = 1
 If frequency=1 this will always get called.
 This _can_ happen on the first page someone lands on.

   frequency: odds of getting popup = 1/frequency times
   url: url of the content for popup window
   stopcookie: name of cookie that keeps them from getting popup again
   expiredays: number of days to keep the stopcookie active
   windowsize: small, medium, large - defaults to large
   -- these sizes are defined in the window opening functions
  ------------------------------------------------------------------- */

function randomPop (frequency, url, stopcookie, expiredays, windowsize){
  var cookiename = 'IntSurP';
  var validDate;
  var random_num;

  frequency <= 1 ? random_num = 1: random_num = Math.ceil( frequency * Math.random()) ;

  if ((random_num == 1) ) {
   validDate = global_extractCookieChip(cookiename,stopcookie);

   if ( validDate && validDate < Date.parse(Date()) ) {
      /* they had the cookie, but it's too old to matter */
      global_crumbleCookieChip(cookiename, stopcookie);
      validDate = "";
   }

   if (!validDate ) {
      /* they don't have a cookie telling us to stop */

      expiredays = global_daysFutureToTimeMS(expiredays);
      global_addCookieChip(cookiename, stopcookie,expiredays);

      if ( windowsize=="medium" ) {
        openMediumPopup(url,"popWin");
      } else if ( windowsize=="small") {
	  openSmallPopup(url,"popWin");
      } else {
        openLargePopup(url,"popWin");
      }

   //} else {
    //alert("You've got the Cookie! " + stopcookie);

  }  /* ends if (!validDate) */
  //} else {
     /* it was a different random number */
    // alert("random_num was "+random_num)  // for debugging purposes only
  } /* ends if (random_num ==1) */
} // end randomPop()


/* ------------------------------------------------------------
   function call to initiate timed survey
   ------------------------------------------------------------ */
// How to use timedPop. Comment out the following line to turn it off.
// timedPop(1, 50, "http://www.cisco.com/survey/intercept.html", "cdcsurvey", 183, "small" );

/* ------------------------------------------------------------
   function call for framework to render right grey bar if framework-content-right has a certain # of child nodes
   ------------------------------------------------------------ */

function setRightColumnBar(){
	var thisCol = document.getElementById('framework-content-right').childNodes;
	for(i=0;i < thisCol.length;i++){
		if(thisCol[i].nodeType == 1 || (thisCol[i].nodeType == 3 && (/\S/.test(thisCol[i].nodeValue)))){
			document.getElementById('framework-base-main').className="framework-base-main-override";
			document.getElementById('framework-content-right').style.width="189px";
		}
	}
}

/* ---------------------------------------------------------------
        Search box -- Function to clear the word Search
 	when you go into the field. Could be used for other
	default text
   --------------------------------------------------------------- */

function checkClear(input,defaultPhrase) {
  if (input.value == defaultPhrase) input.value = "";
  if (input.id == "searchPhrase") {
    if (!document.getElementById("search-drop-down")){
      setupSearch();
    }
    if (document.getElementById("search-drop-down")){
      showSuggestionsContainer();
    }
  }
}


/* ---------------------------------------------------------------
       Sitewide Tools Rollover Functions
   --------------------------------------------------------------- */

/* Window opening script for Sitewide Toolkit only */

function sitewide_toolkit_window(url,winName) {
	if(!winName) { winName = "swtwin"; }

        var swtwin = window.open(url, winName, 'width=643,height=492,outerWidth=643,outerHeight=492,top=50,left=70,resizable=yes,scrollbars=yes,toolbar=yes,menubar=yes,status=yes,locationbar=no');

	if (swtwin) swtwin.focus();
}

/* ---------------------------------------------------------------

	Function for Performing redirect.
   ---------------------------------------------------------------

must pass Burl other parameters are optional:

doRedirect('http://cisco.com');

This will default to 50/50 chance of a redirect.  To adjust the chance of a redirect, use a second parameter.  To get a one in 5 chance:

doRedirect('http://cisco.com',5);

If they want session consistency then they must choose and pass in a unique cookie name.  If you use a cookieName, you MUST specify the frequency even if it is 2.  The cookie name can be composed of letters, numbers, dashes and underscores and be less than 20 charaters.

doRedirect('http://cisco.com',2,'you-inc-AorB');
*/

function doRedirect(Burl,chance,cookieName) {
    if(!Burl) {
        return;
    }
    if (!chance) {
        chance = 2;
    }
    if (cookieName) {
        var cookie = global_getCookie(cookieName);
        if (cookie == 'b') {
            window.location.replace(Burl);
            return;
        }
        if (cookie == 'a') {
            return;
        }
    }
    var chooser = Math.ceil(Math.random()*chance);
    if (chooser == 1) {
        if (cookieName) {
             global_setCookie(cookieName, 'b');
        }
        window.location.replace(Burl);
    }
    else {
        if (cookieName){
             global_setCookie(cookieName, 'a');
        }
    }

	var chooser = Math.ceil(Math.random()*chance);
	if (chooser == 1) {
		window.location.replace(Burl)
	}
}


// bam adaptive/targeted media
cdc.bam = {};
cdc.bam.mediaCallback = function(data){
   jQuery(data.domId).show();
   jQuery(data.domId).html(data.blob);
   data.readyCallback();
};


// test src url before showing image
// invoke with: onload="cdc_display_image_when_loaded(this,'my_source_url.jpg');"
function cdc_display_image_when_loaded(img,url){
	// we're extending img with .tempImg to do a test load of the src with a new image object
	img.tempImg = new Image();
	img.tempImg.onload = function(){
		// this prevents the image src in html from firing the onload again
		img.onload=null;
		img.src = img.tempImg.src;
		img.tempImg.onload=null;

		if(img.id == "bam_img"){
			img.parentNode.href = img.src.replace('image.ng','click.ng');
		}
	};
	// putting this after the onload handler above
	img.tempImg.src = url;
}

// cache buster - puts a cache avoidance param on a url with a random number
// invoke with:
// cdc_cache_bust('http://www.cisco.com');          = YourUrl?cacheReset=rand#
// cdc_cache_bust('http://www.cisco.com','foo');    = YourUrl?foo=rand#
// cdc_cache_bust('http://ng-prod1/image');         = YourUrl&cacheReset=rand#
// cdc_cache_bust('http://cisco.com/edit.pl?a=3');  = YourUrl&cacheReset=rand#
function cdc_cache_bust (url,param){
	if (!param) {param = 'cacheReset'};
	var delim = "?";
  // if url is ng-prod1(bam) or has ?, set param delimeter to &
  if (url.match(/(ng-prod1|\?)/)) {delim = "&"};
  var fullParam = delim+param+'=';
	// degug alert(url+fullParam+cdc_rand_num());
	return url+fullParam+cdc_rand_num();
}

// randum number generator
// input: takes param limit to set random max, default is 1000
// output: 'TimeInSeconds-RandNum'
// invoke with: cdc_rand_num(50); or cdc_rand_num();
function cdc_rand_num(limit){
	if (!limit) {limit = 1000};
	var sNum = Math.floor(Math.random()*limit)+1;
  var sTime = (new Date).getTime();
  var rNum = sTime+"-"+sNum;
  return rNum;
}


cdc.util.getSiteArea = function(){

/*
must be one of:
-------------------
About_Cisco
Campaign_Sites
Discussion_Forums
Framework
Global
Home_Pages
Industry_Solutions
Learning_and_Events
Mobile
Networking_Solutions
Ordering
Partners_and_Resellers
Products
Search
Security
Services
Tech_Support
Technologies

*/

	var cdcSiteArea='';
	var siteAreaFrom='';
	// Check URL for known matches
	var siteareasArray = [
		["\/web\/about\/", "About Cisco"],
		["\/web\/learning\/", "Learning and Events"],
		["\/web\/ordering\/", "Ordering"],
		["\/web\/partners\/", "Partners and Resellers"],
		["\/web\/strategy\/", "Industry Solutions"]
	];
	for (z = 0; z < siteareasArray.length; z++) {
		if (location.href.search(siteareasArray[z][0]) != -1) {
			cdcSiteArea = siteareasArray[z][1];
			siteAreaFrom = 'url';
		}
	}


	//check hinav
	try{
		//cdcSiteArea = document.getElementById("framework-column-left").getElementsByTagName('li')[1].childNodes[0].innerHTML;

		cdcSiteArea = document.getElementById("framework-column-left").getElementsByTagName('li')[1].getElementsByTagName('a')[0].innerHTML;

		siteAreaFrom = 'hinav';

	} catch(e) {}


	// Check "iaPath" Meta tag data if present
	var metatags = document.getElementsByTagName("meta");
	for (var m = 0; m < metatags.length; m++) {
		var curr_name = metatags[m].getAttribute("name");
		var curr_content = metatags[m].getAttribute("content");
		if (curr_name == "iaPath") {
			var iaPathArray = curr_content.split("#");
			cdcSiteArea = iaPathArray[1]?iaPathArray[1]:cdcSiteArea;
			siteAreaFrom = 'meta';
		}
	}
	for (m = 0; m < metatags.length; m++) {
		var curr_name = metatags[m].getAttribute("name");
		var curr_content = metatags[m].getAttribute("content");
		if (curr_name == "contentType") {
			if (curr_content.indexOf("postSales") > 0){
			  cdcSiteArea = "Support";
			  siteAreaFrom = 'meta(support)';
			}
		}
	}

	cdcSiteArea = cdcSiteArea.toLowerCase();
	var t = cdcSiteArea.split(' ');
	cdcSiteArea="";
	for (var m=0;m<t.length;m++){
		if (t[m]=='and'){
			cdcSiteArea += t[m] + " ";
		}
		else {
			cdcSiteArea += t[m].substring(0,1).toUpperCase() + t[m].substring(1) + " ";
		}
	}
	cdcSiteArea = cdcSiteArea.replace(/ $/,'');

	cdcSiteArea = cdcSiteArea.replace(/ &amp; /,'_and_');
	cdcSiteArea = cdcSiteArea.replace(/ /g,'_');
	cdcSiteArea = cdcSiteArea.replace(/Partner_Central/,'Partners_and_Resellers');
	cdcSiteArea = cdcSiteArea.replace(/Support/,'Tech_Support');
	return cdcSiteArea;

} // end getSiteArea()


/* ------------------------------------------------------------
  page location hash reader/setter for widgets
   ------------------------------------------------------------ */

if (typeof(cdc.util) == 'undefined'){
   cdc.util = new Object();
}

cdc.util.setToHash = function(widget,val){
   var cur = cdc.util.getFromHash();
   var newHash='';
   if (widget&&val){
      cur[widget] = val;
   }
   for (widget in cur){
      newHash += widget+'~'+cur[widget]+',';
   }
   newHash = newHash.substr(0,newHash.length-1);
   newHash = '#~'+newHash;
   window.location.hash = newHash;
};

cdc.util.getFromHash = function(){
   var ret = new Object();
   var h = window.location.hash;
   if (h.indexOf("#~")<0){
      return ret;
   }
   h = h.substr(2);

   currHashArr = h.split(",");
   for (h=0; h<currHashArr.length; h++){
      var pair = new Array();
      pair = currHashArr[h].split('~');
      if (!(pair[1])){
         ret['tab']=pair[0];
      } else {
         ret[pair[0]] = pair[1];
      }
   }
   return ret;
};

 cdc.util.sso = function () {
 	if ((window.location.host == 'cisco.com')||(window.location.host == 'www.cisco.com')||(window.location.host == 'www-test.cisco.com')){
 		var url = "https://fedps.cisco.com/idp/startSSO.ping?PartnerSpId=https://fedam.cisco.com&IdpAdapterId=fedsmidpCCO&TargetResource=http%3A//www.cisco.com/cisco/psn/web/site/collab/sign.html";
 	}
 	else {
 	   var url = "https://fedps-stage.cisco.com/idp/startSSO.ping?PartnerSpId=pfoam&IdpAdapterId=fedsmidpCCO&TargetResource=http%3A//cepx-active-stage1.cisco.com/cisco/psn/web/site/collab/sign.html";
 	}
	if (global_getCookie("SMSESSION")!='') {
		if (global_getCookie("LtpaToken")==''||global_getCookie("cdc_ltpa_timeout")=='') {
			document.tempImg = new Image();
			document.tempImg.src = url;
			/*
			try{
				var t = jQuery.ajax({'url':url,
					complete:function(x,t){
						//todo: check if this has been redirected to a login page
						//and if so clear cookies
						//console.log('success');
					},
					error: function(x,t){
						if (x.status == '302'){
							cdc.util.setCookie({cookieName:"SMSESSION",cookieValue:'',msecs:2});
							cdc.util.setCookie({cookieName:"LtpaToken",cookieValue:'',msecs:2});
							cdc.util.setCookie({cookieName:"cdc_ltpa_timeout",cookieValue:'',msecs:2});
						}
					}
				});
			}catch(e){
				//console.log('catch');
			}
			*/
			var msecsFromNow = (1000*60*19);
			var n = new Date();
			n.setTime(n.getTime()+msecsFromNow);
			cdc.util.setCookie({cookieName:"cdc_ltpa_timeout",cookieValue:n.getTime(),msecs:msecsFromNow});
		}
		if (global_getCookie("cdc_ltpa_timeout")){
			//set timeout for as long as cookie has left; call self at timeout end.
			var n = new Date();
			var timerDuration = global_getCookie("cdc_ltpa_timeout") - n.getTime() + 100;
			if (timerDuration>0){
				setTimeout(cdc.util.sso,timerDuration);
			}
		}
	}
}

/**
 * htmlEscape: Replace escapable characters by their encoded HTML equivalents.
 * Each occurrence of one of the escapable characters in the string is replaced by its
 * numerically-HTML-escaped form. (For example, the '<' symbol is replaced by the string &#60;)
 * @param aString the string to escape
 * @param escapeChars (optional) the characters in the string that should be escaped. If this parameter is not
 * specified, it is assumed to be the string "<>'", thus escaping the three characters ", < and >.
 * @return the escaped string
 */
cdc.util.htmlEscape = function (aString, escapeChars) {
    if (!aString || typeof (aString) != "string") return aString;
    if (typeof (escapeChars) == "undefined") escapeChars = "<>\'";
    var escapeCharsRegex = new RegExp ("([" + escapeChars + "])", "g");
    return aString.replace (escapeCharsRegex, function (match) {
        return "&#" + match.charCodeAt(0) + ";";
    });
};

/**
 * cdc.util.addCorners - takes the jQuery selector string to hunt for as required input.
 * then adds spans to put the corners in
 * css needs to be written separately to specify what images to use for corners and how to position them
 */
cdc.util.addCorners = function (myselect,doDiv) {
    if (doDiv) {
       jQuery(myselect).append(
          '<div class="ctl"></div><div class="ctr"></div><div class="cbl"></div><div class="cbr"></div>'
       );
    }
    else {
       jQuery(myselect).prepend('<span class="cl-top-corners"><span></span></span>').append('<span class="cl-bottom-corners"><span></span></span>');
    }
}

cdc.util.setCookie = function (a) {
   var expireStr = '';
   if (a.msecs){
	   var ex=new Date();
	   ex.setTime(ex.getTime()+a.msecs);
	   expireStr = ";expires="+ex.toGMTString();
   }
   document.cookie=a.cookieName + "=" + escape(a.cookieValue) + expireStr + "; path=/; domain=cisco.com";
}



/**
 * formatString: A simple string formatting utility
 *
 * Example:
 *    var fName = "Joe", lName = "Smith";
 *    var formatted = cdc.util.formatString ("Dear {0} {1}", fName, lName);
 */
cdc.util.formatString = function (formatStr) {
    var args = arguments.length > 1 ? Array.prototype.slice.call (arguments, 1) : [];
    var str = formatStr.replace (/\{\d+\}/g, function (match) {
        var index = parseInt (match.substring (1, match.length-1));
        return args.length > index ? args[index] : match;
    });
    return str;                             
};



/* *** For Newsfeeds, code used by N05v17 can be used by others *** */
   cdc.util.ensureNamespace('cdc.newsfeed');

   cdc.newsfeed.renderNews = function (json) {
      alert("cdc.newsfeed.renderNews() has not been defined by a consumer! Specify for your own component incoming json: " + json);
   }
 
   cdc.util.ensureNamespace('cdc.homepage.newsfeed');
   cdc.homepage.newsfeed.renderNews = function (json) { cdc.newsfeed.renderNews(json); }
 
 

jQuery(document).ready(function(){
    jQuery("#skiplinks").addClass('skiplinks').removeClass('skiplinkShow');
    jQuery("#skiplinks a").focus(function() { jQuery("#skiplinks").addClass('skiplinkShow').removeClass('skiplinks');});
    jQuery("#skiplinks a").blur(function() { jQuery("#skiplinks").addClass('skiplinks').removeClass('skiplinkShow');});
});

cdc.util.is1x = (window.location.href.indexOf("/en/US/") >1 );
cdc.util.campPlatforms = new Array ("tools.cisco.com","tools-dev.cisco.com","tools-stage.cisco.com","apps.cisco.com","apps-dev.cisco.com","apps-stage.cisco.com","/cgi-bin/","/pcgi-bin/");
cdc.util.isCamp = false;
for (platform in cdc.util.campPlatforms) {
    if (window.location.href.indexOf(cdc.util.campPlatforms[platform]) >1 ) {
        cdc.util.isCamp = true;
        break;
    }
}

if ( cdc.util.is1x || cdc.util.isCamp ) {
    jQuery(document).ready(function() {
        var loggedInCookie = global_getCookie('SMSESSION');
    	if ( loggedInCookie && loggedInCookie != '' && loggedInCookie != 'LOGGEDOFF'){
    		jQuery(".nav-secondary :contains(Register)").prev().remove();
    		jQuery(".nav-secondary :contains(Register)").remove();
    		jQuery(".nav-secondary a.login").replaceWith('<span class="loggedin">Logged In</span>');
    	}
    });
}



/**
 * Replaces 1.x footer copyright current year with id specified year.
 * Will only replace inside correctly id'd item, in this case a span tag.
 * This is only a turn of the year band-aid.
 * "footer_nav_legal.xsl" must still be updated.
*/
jQuery(document).ready(function() {
   var copyrightYear = '2010';
   if (jQuery("#footer-copyright-year").html() < copyrightYear) {
      jQuery("#footer-copyright-year").html(copyrightYear);
   }
});

cdc.mru = {
	serviceHost: "",
	serviceUrl: "/cisco/web/cdc/psa/mru?command=update",
	timeOutMsecs: 250,
	makeMruRequest: function(anchor,args) {

		var updateUrl = cdc.mru.serviceHost + cdc.mru.serviceUrl;
		if (args){
		   updateUrl += args;
		}
		else if (anchor.mruExpando){
		   updateUrl += anchor.mruExpando;
		}
		else if (anchor.rel) {
		   updateUrl += anchor.rel;
		}

		var serviceReturnUrl = anchor.href;
		var timeoutUrl = anchor.href;
		if (cdc.debug.on){
			timeoutUrl += "?timeout";
			serviceReturnUrl += "?serviceReturn";
		}
		var loadHandler = function(){window.location.href=serviceReturnUrl;};
		cdc.mru.tempDoc = document.createElement('iframe');
		document.getElementById('framework-footer').appendChild(cdc.mru.tempDoc);
		if (cdc.mru.tempDoc.attachEvent){
			cdc.mru.tempDoc.attachEvent('onload', loadHandler);
		}
		else {
			cdc.mru.tempDoc.onload = loadHandler;
		}
		cdc.mru.tempDoc.src = updateUrl;
		jQuery(cdc.mru.tempDoc).hide();

		setTimeout("window.location.href='" + timeoutUrl+"'", cdc.mru.timeOutMsecs);
		return false;
	}
};


//!!!!!!important!!!! this is an override for QA testing!!!! REMOVE FOR PROD USE!!!!
cdc.mru.timeOutMsecs = 50000;

document.write('<style>.showForJs{display:block;}.showInlineForJs{display:inline;}.hideForJs{display:none;}</style>');
