/*
 *------------------------------------------------------------------
 * sitewide.js
 *
 * Copyright (c) 2003-2006 by cisco Systems, Inc.
 * All rights reserved.
 *------------------------------------------------------------------
 */

var DLIM_WhSp = /[\s]+/;
var DLIM_WhSp_slash = /[\/\s]+/;
var DLIM_WhSp_comma = /[\,\s]+/;
var DLIM_WhSp_parens = /[\(\)\s]+/;
var DLIM_WhSp_colon = /[\:\s]+/;
var DLIM_newline = /[\r\n]+/;
var DLIM_nonword          = /[\W]+/;
var DLIM_nonword_period   = /[^a-zA-Z0-9_\.]+/;
var DLIM_nonword_colon    = /[^a-zA-Z0-9_:]+/;

//disable right click
document.oncontextmenu = new Function("return false");

// method to Print the page
/*
function printPage(){  
	if (top.mainFrame.window.print) {
		top.mainFrame.window.focus();
	    top.mainFrame.window.print() ;  
	} else {
	    var WebBrowser = '<OBJECT ID="WebBrowser1" WIDTH=0 HEIGHT=0 CLASSID="CLSID:8856F961-340A-11D0-A96B-00C04FD705A2"></OBJECT>';
		document.body.insertAdjacentHTML('beforeEnd', WebBrowser);
	    WebBrowser1.ExecWB(6, 2);
		
	}
}
*/

/*
 * This function set the embedded help text in a screen
 */
 
function setHelpText(helpText) {
	document.writeln('\
						<table border=0 cellspacing="0" cellpadding="0"> <tr>');
	document.writeln('\
						<td class="xpcontent">');						
	document.writeln(helpText);
	
	document.writeln('\
						</td> </tr> </table>');				
}

/*
 * This function sets the text for quick tip, this need to be further 
 * enhanced to show and hide the quick tip.
 */
 
function setQuickTipText(quickTipText) {
	document.writeln('\
						<table border=0 cellpadding=0 cellspacing="1"> <tr> <td bgcolor="#454545">');
	document.writeln('\
						<table border=0 cellspacing="1" cellpadding=10> <tr>');
	document.writeln('\
						<td style="FILTER: progid:DXImageTransform.Microsoft.gradient (GradientType=0, startColorstr=#FFF1B3, endColorstr=#FFE781);" class="xpcontent" bgcolor="#FFE781">');						
	document.writeln(quickTipText);
	
	document.writeln('\
						</td> </tr> </table>');				
   document.writeln('\
						</td> </tr> </table>');						   					
}

/*
 * This function converts the short interface name to long interface names
 */
function toLongPortName(intName) {

 	var GIG_SHORT_PRE = "GI";
 	var FA_SHORT_PRE = "FA";
 	var LO_SHORT_PRE = "LO";
   if (intName.toUpperCase().indexOf(GIG_SHORT_PRE)!= -1) {
		return ("GigabitEthernet" + intName.substring(GIG_SHORT_PRE.length,intName.length));
	}    if (intName.toUpperCase().indexOf(FA_SHORT_PRE)!= -1) {
		return ("FastEthernet" + intName.substring(FA_SHORT_PRE.length,intName.length));
	}    if (intName.toUpperCase().indexOf(LO_SHORT_PRE)!= -1) {
		return ("LongReachEthernet" + intName.substring(LO_SHORT_PRE.length,intName.length));
	} 
} 

/*
 * This function converts the long interface name to short interface names
 */
function toShortPortName(intName) {

 	var GIG_LONG_PRE = "GIGABITETHERNET";
 	var FA_LONG_PRE = "FASTETHERNET";
 	var LO_LONG_PRE = "LONGREACHETHERNET";
   if (intName.toUpperCase().indexOf(GIG_LONG_PRE)!= -1) {
		return ("Gi" + intName.substring(GIG_LONG_PRE.length,intName.length));
	}    if (intName.toUpperCase().indexOf(FA_LONG_PRE)!= -1) {
		return ("Fa" + intName.substring(FA_LONG_PRE.length,intName.length));
	}    if (intName.toUpperCase().indexOf(LO_LONG_PRE)!= -1) {
		return ("Lo" + intName.substring(LO_LONG_PRE.length,intName.length));
	} 
}


// open a page in a specified targer
function land(ref, target)
{
lowtarget=target.toLowerCase();
if (lowtarget=="_self") {window.location=loc;}
else {if (lowtarget=="_top") {top.location=loc;}
else {if (lowtarget=="_blank") {window.open(loc);}
else {if (lowtarget=="_parent") {parent.location=loc;}
else {parent.frames[target].location=loc;};
}}}
}

// Calculate the netmask from the number of masked bits of an octet
function calcNetMaskField(numberOfBits) {
   if (numberOfBits <= 0) {
      return "0";
   } else if (numberOfBits >= 8) {
      return "255";
   } else if (numberOfBits == 7) {
      return "254";
   } else if (numberOfBits == 6) {
      return "252";
   } else if (numberOfBits == 5) {
      return "248";
   } else if (numberOfBits == 4) {
      return "240";
   } else if (numberOfBits == 3) {
      return "224";
   } else if (numberOfBits == 2) {
      return "192";
   } else if (numberOfBits == 1) {
      return "128";
   }
}


// calculate the netmask string from the masked number of bits
function calcNetMask_string(numberOfBits) {
   var subNetMask = "";
   subNetMask += calcNetMaskField(numberOfBits);
   subNetMask += ".";
   numberOfBits -= 8;
   subNetMask += calcNetMaskField(numberOfBits);
   subNetMask += ".";
   numberOfBits -= 8;
   subNetMask += calcNetMaskField(numberOfBits);
   subNetMask += ".";
   numberOfBits -= 8;
   subNetMask += calcNetMaskField(numberOfBits);
   return subNetMask;
}

// calculate the netmask
function calcNetMask(numberOfBits) {
   var str;
   if (numberOfBits) {
      if (numberOfBits == "undefined") {
         document.write("unassigned");
      } else {
         str = calcNetMask_string(numberOfBits);
         document.write(str);
      }
   } else {
      document.write("unassigned");
   }
}

// extract the name server details
function NameServerPresent(serverString)
{
  if ((token_string_blank(DLIM_nonword_period, 1, serverString) == "255.255.255.255") && 
       isBlank(token_string_blank(DLIM_nonword_period, 3, serverString)) && 
       isBlank(token_string_blank(DLIM_nonword_period, 5, serverString))) {
	 return false
  }
  return true
}

// to split the string with the specified delimiter
function split (delimiter, string) { 
   localstring = string;
   word = localstring.split(delimiter);
   if (word.length>1) {
      
      while ((word.length>1)&&(word[0]=="")) {
         localstring = localstring.substr(1);
         word = localstring.split(delimiter);
      }
      
      while ((word.length>1)&&word[word.length-1]=="") {
         localstring = localstring.substr(0,localstring.length-1);
         word = localstring.split(delimiter);
      }
   }
   return word;
}

// will return the token at the index specified,
// string will be splitted with the delimiter specified
function token_string (delimiter, index, string) { 
    tok = null;
    word = split(delimiter, string);
    last_token = word.length - 1;
    if (index >= 0) {
       if (index <= last_token) {
          tok = word[index]; 
       }
    } else {
       backindex = last_token + index + 1;
       if (backindex >= 0) {
          tok = word[backindex]; 
       }
    }
    return tok;
}

//will write the token at the specified index to the document after splitting the string with the delimiter
function token (delimiter, index, string) {
   if (-1 != string.search(/exec cmd/)) {
      document.write("*undefined*");
   } else {
      tok = token_string(delimiter, index, string);
      if (tok) {
          document.write(tok);
      } else {
          document.write("&nbsp;");
      }
   }
}

//will write the token at the specified index to the document after splitting the string with the delimiter
// if token is not found, will write undefined.
function token_undefined (delimiter, index, string) {
   if (-1 != string.search(/exec cmd/)) {
      document.write("*undefined*");
   } else {
      tok = token_string(delimiter, index, string);
      if (tok) {
         document.write(tok);
      } else {
         document.write("undefined");
      }
   }
}


function token_help (delimiter, index, string) { 
   local_index = 0;
   tok = token_string(delimiter, local_index, string);
   if (33 == tok.charCodeAt(1)) {
      document.write("missing");
   } else {
      if (tok) {
         while (tok) {
            document.write('\n');
            if (index == local_index) {
               document.write('<FONT COLOR="red">');
            }
            document.write('('+local_index+')="'+tok+'"');
            if (index == local_index) {
               document.write("</FONT>");
            }
            document.write("<br>");
            local_index += 1;
            tok = token_string(delimiter, local_index, string);
         }
      } else {
         document.write('<FONT COLOR="red">NULL</FONT>');
      }
   }
}

//trim_string method matches spaces at beginning and end of text and replace
//with null strings
function trim_string(string)
{ 
  return string.replace(/^\s+/,'').replace(/\s+$/,'');
} 

// compact_line method removes multiple spaces between words
// this will not remove the space at the start and end of the line
// for that pass the retunr value of this method to trim_string.
// O/p of the call compact_line("   The    line to   be compacted   "); will be
// " The line to be compacted "
function compact_line(line)
{ 
  return line.replace(/\s+/g,' ');
} 

// replace_string returns found if target is found in the string
// else return notfound.
function replace_string (target, found, notfound, string)
{
   if (-1 != string.search(target)) {
      return found;
   } else {
      return notfound;
   }
}

// replace writes 'found' if target is found in the string
// else return 'notfound'.
function replace (target, found, notfound, string)
{
   if (-1 != string.search(target)) {
      document.write(found);
   } else {
      document.write(notfound);
   }
}

// grep_string returns the first line that contains the pattern
function grep_string (pattern, string) {
   line = split(DLIM_newline, string);
   for (curline = 0; curline < line.length; curline++) {
      if (-1 != line[curline].search(pattern)) {
          return line[curline];
      }
   }
}

// grep_string writes the first line that contains the pattern
function grep (pattern, string) {
   line = grep_string(pattern, string);
   if (line) {
      document.write(line);
   }
}

// grep_string returns all the lines that contains the pattern
function multi_grep_string (pattern, string) {
   var result = new Array();
   var i = 0;
   line = string.split(DLIM_newline);
   for (curline = 0; curline < line.length; curline++) {
      if (-1 != line[curline].search(pattern)) {
         result[i] = line[curline];
         i += 1;
      }
   }
   return result;
}

// find_string finds the first line matching the pattern and then
// returns token at the specified index after splitting with the delimiter
function find_string (pattern, delimiter, index, string) {
   line = grep_string(pattern, string);
   if (line) {
      tok = token_string(delimiter, index, line);
      if (tok) {
          return tok;
      }
   }
}

// find_string finds the first line matching the pattern and then
// writes token at the specified index after splitting with the delimiter
function find (pattern, delimiter, index, string) {
   if (-1 != string.search(/exec cmd/)) {
      document.write("*undefined*");
   } else {
      line = grep_string(pattern, string);
      if (line) {
         tok = token_string(delimiter, index, line);
         if (tok) {
            document.write(tok);
         } else {
            document.write("&nbsp;");
         }
      } else {
         document.write("&nbsp;");
      }
   }
}

// find_string finds the first line matching the pattern and then
// writes token at the specified index after splitting with the delimiter
// if the pattern is not matched or the token is not found it writes 'undefined'
function find_undefined (pattern, delimiter, index, string) {
   if (-1 != string.search(/exec cmd/)) {
      document.write("*undefined*");
   } else {
      line = grep_string(pattern, string);
      if (line) {
          tok = token_string(delimiter, index, line);
          if (tok) {
              document.write(tok);
          } else {
             document.write("undefined");
          }
      } else {
          document.write("undefined");
      }
   }
}

// find_string finds the first line matching the pattern and then
// writes token at the specified index after splitting with the delimiter
// if the pattern is not matched or the token is not found it writes o/p of token_help
function find_help (pattern, delimiter, index, string) {
   if (-1 != string.search(/exec cmd/)) {
      document.write("*undefined*");
   } else {
      line = grep_string(pattern, string);
      if (line) {
         tok = token_help(delimiter, index, line);
      } else {
         document.write("undefined");
      }
   }
}

// token_string_label will returnt the next token after the Label
// in the string.
function token_string_label(delimiter, label, string)
{
    word = string.split(delimiter);
    for (var index=0; index<word.length; index++) {
      if (word[index] == label) 
        return word[index+1]; 
    }
}

// token_string_label_index will return the tokenIndex'th token after the Label
// in the string.
function token_string_label_index(delimiter, label, string, tokenIndex)
{
    var blank = ""
    word = string.split(delimiter);
    for (var index=0; index<word.length; index++) {
      if (word[index] == label) 
        return word[index+tokenIndex]; 
    }
	return blank
}

// token_string_label_to_label will return the string between the Label1 and
// Label2 in the string.
function token_string_label_to_label(delimiter, label1, label2, string)
{
    word = string.split(delimiter);
	var str = ""
	var index1 = 0
	var index2 = 0
    for (var index=0; index<word.length; index++) {
      if (word[index] == label1)
	    index1 = index 
      if (word[index] == label2)
	    index2 = index  
    }
	for (var i = index1; i < index2-1; i++) {
	  str += word[i+1] + " "
	}
	return str
}

// token_string_label_blank will return the next token after splitting the string after the label
// with the delimiter
function token_string_label_blank(delimiter, label, string)
{
   if (string) {
      match = string.search(label);
      if (-1 != match) {
         remainder = string.substring(match+label.length);
         tok = token_string(delimiter, 0, remainder);
         if (tok)
            return tok;
      }
   }
   return ""
}

// token_string_label_blank will return the string between the label and the end of line
function token_string_label_to_eol(label, string)
{
   if (string) {
      match = string.search(label);
      if (-1 != match) {
         remainder = string.substring(match+label.length);
         tok = token_string(DLIM_newline, 0, remainder);
         if (tok)
            return tok;
      }
   }
}

// token_string_blank will return a blank if the token is not
// found in the string
function token_string_blank (delimiter, index, string) { 
    var val = ""
    val = token_string(delimiter, index, string)
    if (!val)
      return ""
    else
      return val
}

// makeArray creates an array with the specified size.
function makeArray(n)
{
  this.length = n;
  return this;
}

function token_offset_str (pattern, delimiter, index, defalt, string) {
   var tok = defalt;
   var exp_str = "";
   var exp;
   var debug = 0;
   var result;
   if (arguments.length > 5) {
      debug = arguments[5];
   }
   if (string) {
      if (index < 0) {
         exp_str += "([^\\r\\n]+)"+delimiter.source;
         exp_str += "("+pattern.source+")";
         exp_str += delimiter.source;
         exp = new RegExp(exp_str);
         result = string.match(exp);
         result_pattern = 2;
         result_index = 1;
         tokens_offset = 0;
         tokens_multiplier = 1;
      } else {
	     if (string.search(pattern) != 0) {
           exp_str += delimiter.source ;
		 }
         exp_str += "("+pattern.source+")";
         exp_str += delimiter.source+"([^\\r\\n]+)";
         exp = new RegExp(exp_str);
         result = string.match(exp);
         result_pattern = 1;
         result_index = 2;
         tokens_offset = -1;
         tokens_multiplier = 0;
      }
      if (result != null) {
         tokens = split(delimiter, result[result_index]);
         tokens_index = index + tokens_offset + (tokens.length * tokens_multiplier);
         if ((tokens_index >= 0) && (tokens_index < tokens.length)) {
            if (debug == 0) {
               tok = tokens[tokens_index];
            } else {
               tok = "";
               if (tokens_multiplier == 0) {
                  tok += result[result_pattern]+"<BR>";
               }
               br_str = "";
               for (i=0; i<tokens.length; i++) {
                  j = i - tokens_offset - (tokens.length * tokens_multiplier);
                  tok += br_str;
                  if (i == tokens_index) {
                     tok += '<FONT COLOR="red">';
                     tok += '('+j+')='+tokens[i];
                     tok += '</FONT>';
                  } else {
                     tok += '('+j+')='+tokens[i];
                  }
                  br_str = "<BR>";
               }
               if (tokens_multiplier != 0) {
                  tok += "<BR>"+result[result_pattern];
               }
            }
         }
      }
   }
   return tok;
}

function token_offset (pattern, delimiter, index, defalt, string) {
   if (-1 != string.search(/exec cmd/)) {
      document.write("*undefined*");
   } else {
      if (document.forms[0].DEBUG != null) {
         tok = token_offset_str(pattern, delimiter, index, defalt, string, 1);
      } else {
         tok = token_offset_str(pattern, delimiter, index, defalt, string);
      }
      if (tok != null) {
         document.write(tok);
      }
   }
}

function FAQ(faqTxt, faqTag) {
	return new Option(faqTxt, faqTag);
}

/*
 * This function extracts the port number from the interface name
 * parameters: intName - interface name, option - method to be used to extract the number
 * options: 1 - loop from end of the name, 2 - loop forward in the name, 3 - extract all numbers in a name, null - use option 1
 * enhanced to show and hide the quick tip.
 */
function getPortNumber(intName, option) {
	if(intName == null) {
		return;
	}
	
	intName = trim_string(intName);
	
	if(intName == "") {
		return;
	}
	
	var portNumber = "";
	
	if(option == 1 || option == null || option == "") {
		for(var i=intName.length-1; i>=0; i--) {
			var temp = intName.charAt(i);
			if(!isNaN(parseInt(temp))) {
				portNumber = temp + portNumber;
			}
			else {
				break;
			}
		}
	}
	else if(option == 2) {
		for(var i=0; i<intName.length; i++) {
			var temp = intName.charAt(i);
			if(!isNaN(parseInt(temp))) {
				portNumber += temp;
			}
			else {
				break;
			}
		}
	}
	else if(option == 3) {
		portNumber = intName.match(/[0-9]/g).join("");
	}
	
	return portNumber;
}

function replaceSpecialChars(str)
{
	if ( str == null ) return;
	return str.replace(/&/g,"&#38").replace(/</g, "&#60;" );
}

function replaceParams(strToReplace, replacableStrArray) {
	if(strToReplace == null || replacableStrArray == null) {
		return null;
	}
	var paramSearch ;
	for(var i=0; i<replacableStrArray.length; i++) {
		paramSearch = "{" + i + "}";
		strToReplace = strToReplace.replace(paramSearch, replacableStrArray[i]);
	}
	return strToReplace;
}

function replaceString(strToReplace, replacableStr) {
	if(strToReplace == null || replacableStr == null) {
		return null;
	}
	var replacedStr;
	replacedStr = strToReplace.replace("{0}", replacableStr);
	return replacedStr;
}

function replaceTags(strToReplace, replacableStrArray) {
	if(strToReplace == null || replacableStrArray == null) {
		return null;
	}
	var re = /{[^}]+}/ig;
	var strMatch = strToReplace.match(re);
	for(var i=0; i<strMatch.length; i++) {
		if(replacableStrArray[i] != null)
			strToReplace = strToReplace.replace(strMatch[i], replacableStrArray[i].replace("><", ">" + strMatch[i].replace(/{|}/g, "") + "<"))
	}
	
	return strToReplace;
}

function doesStringHasUcodeChar(stringtoCheck)
{
	if (stringtoCheck==null) return;
	for (var index = 0; index< stringtoCheck.length; index++)
	{
		if ( stringtoCheck.charCodeAt(index) > 255 ) return true;
	}
	return false;
}

function localizeUptime(str)
{
	if (str==null || top.resourceFrame==null) return;
	var uptime = str.toLowerCase();
	var singularUnits = new Array("year", "week", "day", "hour", "minute");
	var singularResource = new Array(top.resourceFrame.re_Uptime_year,top.resourceFrame.re_Uptime_week,top.resourceFrame.re_Uptime_day,top.resourceFrame.re_Uptime_hour, top.resourceFrame.re_Uptime_minute);
	var pluralUnits = new Array("years", "weeks", "days", "hours", "minutes");
	var pluralResource = new Array(top.resourceFrame.re_Uptime_years,top.resourceFrame.re_Uptime_weeks,top.resourceFrame.re_Uptime_days,top.resourceFrame.re_Uptime_hours, top.resourceFrame.re_Uptime_minutes);
	for (var i=0; i<pluralUnits.length; i++)
	{
			if (uptime.indexOf(pluralUnits[i]) != -1)
			{
				uptime = uptime.replace(pluralUnits[i], pluralResource[i])
			}
			else if (uptime.indexOf(singularUnits[i]) != -1)
			{
				uptime = uptime.replace(singularUnits[i], singularResource[i])
			}
	}
	return uptime;
}
