// JavaScript Document

function initListPopups(parent) {
      for (var i=0; i<parent.childNodes.length; i++) {
        var node = parent.childNodes[i];
        if (node.nodeName=="LI") {
          node.onmouseover=function() {
            this.className+=" over";
          }
          node.onmouseout=function(e) {
            this.className=this.className.replace(" over", "");
          }
	}
	initListPopups(node);
      }
}

function initMenus() {
  var menuDivs = document.getElementsByTagName("div");
  if (menuDivs) {
    if (menuDivs.length > 0) {
      // search for menus
      for (var i = 0; i < menuDivs.length; i++) {
        if (menuDivs[i].className == 'primary-menu') {
          initListPopups(menuDivs[i]);
        }
      }
    }
  }
}

startList = function() {
  if(!/MSIE (5|6)/.test(navigator.userAgent)) return;
// Required update: if the page has no primary nav, don't do anything, don't give an error.
  if (document.all&&document.getElementById) {
    navRoot = document.getElementById("primarynav");
    if (navRoot) {
      initListPopups(navRoot);
    }
    /*langList = document.getElementById("langlist");
    if langList) {
      initListPopups(langList);
    }*/
  }
  initMenus();
}

// Set up onclick events for popup windows
initPopups = function() {
  var x = document.getElementById('channels');
  if (x) { x = x.getElementsByTagName('a'); } // Collect all <a/> tags within the channels area
  if (x) {
    for (var i=0; i < x.length; i++) {
      if (x[i].className == "popupLink") {
        if (!x[i].onclick) { // Make sure not to overwrite an existing onclick event
          x[i].onclick = function() {
            var width = 800; var height = 600; var scroll = 1; var resize = 1; var status = 1;
            var wHref = this.href;
            var wName = this.target;
            if (wName=="_blank" || wName=="") { wName = "default"; }
            if (wName=="wDownloadHelp") { width = 640; height = 480; status = 0; }
            if (wName=="wForm") { width = 640; height = 480; scroll = 0; status = 0; }
            if (wName=="wDownload") { status = 0; }
            popup(wHref, wName, width, height, scroll, resize, status);
            return false;
          }
} } } } }

initFilter = function() {
  var filterCell = document.getElementById("langfilter");
  if (filterCell) {
    filterCell.style.display = "none";
    var preTags = document.getElementsByTagName("pre");
    if (preTags) {
      if (preTags.length > 0) {
        // search for languages
        var langsArray = new Array();
        for (var i = 0; i < preTags.length; i++) {
          var langAttr = preTags[i].attributes.item("language");
          if (langAttr) {
            if (langAttr.specified && langAttr.name == "language" && langAttr.value.length > 0) {
              langName = langAttr.value;
              langFound = false;
              for (j = 0; j < langsArray.length; j++) {
                if (langsArray[j] == langName) {
                  langFound = true;
                  break;
                }
              }
              if (!langFound) {
                langsArray[langsArray.length] = langName;
              }
            }
          }
        }
        
        if (langsArray.length > 1) {
          // more than one language is available on the page
          langsArray = langsArray.sort();
          filterCell.style.display = "";
          if (filterCell.tagName == "DIV") {
            filterCell.style.display = "block";
            jQuery("#article-inner-div").css("margin-left", "28px");
          }
          var langTable = document.getElementById("langfiltertable");
          for (j = langsArray.length - 1; j >= 0; j--) {
            var newRow = langTable.insertRow(0);
            var newCell = newRow.insertCell(0);
            
            var displayName = langsArray[j];
            if (displayName.indexOf("lt") == 0) {
              displayName = displayName.substr(2);
            }
            if (displayName == "CSharp") {
              displayName = "C#";
            }
            
            newCell.innerHTML = "<a>" + displayName + "</a>";
            var langLinks = newCell.getElementsByTagName("a");
            langLinks[0].href = "javascript:showLanguage('" + langsArray[j] + "', '" + displayName + "');";
          }
        }
      }
    }
  }
}

execOnLoad = function() {
  startList();
  initPopups();
  initFilter();
}

window.onload=execOnLoad;


// General popup window function
function popup(URL,name,w,h,scroll, resize, status, buttons) {
  var featureStr = "";
  if (scroll) { scroll = 'yes'; } else { scroll = 'no'; }
  if (resize) { resize = 'yes'; } else { resize = 'no'; }
  if (status) { status = 'yes'; } else { status = 'no'; }
  if (!buttons) { buttons = 'no'; } else { buttons = 'yes'; } // This includes location bar, menubar and toolbar
  featureStr = "width=" + w + ",height=" + h + ",directories=no,location=" + buttons + ",menubar=" + buttons + ",resizable=" + resize + ",scrollbars=" + scroll + ",status=" + status + ",toolbar=" + buttons;
  var newWin = window.open(URL,name,featureStr);
  newWin.focus(); // Bring window to focus (in case of updating an existing window)
}

// Open Downloads Popup Window, for backwards compatibality
function makeNewWindowLogin(URL) {
  popup(URL, 'newWindow', 800, 600, 1, 1, 1, 1);
}


function setCookie(name, value, expires, path, domain, secure) {
  if (expires) {
  // 'expire' can be either a date string or a number of days
    if (!isNaN(parseInt(expires))) {
      var date = new Date();
      date.setTime(date.getTime()+(expires*24*60*60*1000));
      expires = date;
    }
    expires = "; expires="+expires.toGMTString();
  } else { expires = ""; }
  if (!path) { path = ""; }

  document.cookie = 
    name + "=" + escape(value) + expires + "; path="+path;
}

// Read/Delete cookie code from: http://www.quirksmode.org/
function getCookie(name) {
  var nameEQ = name + "=";
  var ca = document.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(nameEQ) == 0) return unescape(c.substring(nameEQ.length,c.length));
  }
  return null;
}

function delCookie(name) {
  createCookie(name,"",-1);
}

//-----------------------------------------------------------------------------
// rememberWW
//  This fucntion sets the cookie 'preferredCountry' if a checkbox 'remember'
//  is present and checked, or if a parameter is passed forcing the setting of
//  the cookie.
// Two arguments:
//  1 - The value of the cookie, it should be a URL or path.
//  2 - A boolean.  1 -> set the cookie regardless of the checkbox.
function rememberWW(site, forceSet) {
    // if 'forceSet' is true, we set the cookie irrespective of the checkbox status
    var daysValid = 90; // Number of days the cookie remains active
    var check = document.getElementById('remember');
    if ((check && check.checked) || forceSet) {
      setCookie('preferredCountry', site, daysValid, "/");
    }
    return false;
}

//-----------------------------------------------------------------------------
// toggleImage
//  This function cycles through a series of images and sets all the visibility 
//  of all but one to hidden. The other is made visible.
//  It takes two arguments:
//   1 - The image name, minus it's sequence number: 'image' in the case of
//       'image0', 'image1', 'image2', etc...
//   2 - The image number to make visible.
//  By convention, 0 is the default image. Initial states of the images must
//   be defined elsewhere.
function toggleImage(img,which) {
  var i = 1;
  var x = document.getElementById(img+i);

  // Cycle through all rollover images (starting at 1, ending at the first sequentially non-existant element)
  while (x) {
    // Set all images hidden, except 'which'
    if (which != i) { x.style.visibility="hidden"; }
    x = document.getElementById(img+(++i));
  }

  // Make the selected image visible
  document.getElementById(img+which).style.visibility="visible";
}

//-----------------------------------------------------------------------------
// showLanguage
//  This function cycles through all <pre> tags with a language attribute
//  and shows only the specified language. To show all languages, pass an empty
//  string for the language.
function showLanguage(lang, displayName) {
  var filterName = document.getElementById("langfiltername");
  if (filterName) {
    filterName.innerHTML = "[" + displayName + "]";
  }

  var preTags = document.getElementsByTagName("pre");
  if (preTags) {
    if (preTags.length > 0) {
      for (var i = 0; i < preTags.length; i++) {
        var langAttr = preTags[i].attributes.item("language");
        if (langAttr) {
          if (langAttr.specified && langAttr.name == "language" && langAttr.value.length > 0) {
            langName = langAttr.value;
            if (lang == "" || langName == lang) {
              preTags[i].style.display = "";
            } else {
              preTags[i].style.display = "none";
            }
          }
        }
      }
    }
  }
  hideLangFilter();
}

var
  docClick = null;
  
//-----------------------------------------------------------------------------
// showLangFilter
//  Displays the language filter table
function showLangFilter() {
  var langTable = document.getElementById("langfiltertable");
  if (langTable) {
    langTable.style.display = "";
    docClick = document.onclick;
    document.onclick = function(event) {
      outsideFilterClick(event);
    }
  }
}

//-----------------------------------------------------------------------------
// hideLangFilter
//  hides the language filter table
function hideLangFilter() {
  var langTable = document.getElementById("langfiltertable");
  if (langTable) {
    langTable.style.display = "none";
    document.onclick = docClick;
  }
}

//-----------------------------------------------------------------------------
// outsideFilterClick
//  onclick event handler when language filter table is displayed
function outsideFilterClick(e) {
  e = e || window.event;
  var srcElement = e.target || e.srcElement;
  while (srcElement.id != "langfilter" && srcElement.parentNode) {
    srcElement = srcElement.parentNode;
  }
  if (srcElement.id != "langfilter") {
    hideLangFilter();
  }
}

//-----------------------------------------------------------------------------
// showElement
//  shows an element by ID
function showElement(elementId) {
  var element = document.getElementById(elementId);
  element.style.visibility = "visible";
}

//-----------------------------------------------------------------------------
// hideElement
//  hides an element by ID
function hideElement(elementId) {
  var element = document.getElementById(elementId);
  element.style.visibility = "hidden";
}

// This func uses functions from hide_show.js
function highlightLinkBar( lang )
{
	//try
	{
		var lb = document.getElementById( "linkbar" );
		if( !lb )
			return;
		var urlpattern = location.pathname;
		if( urlpattern.substr( 0, lang.length ) == lang )
			urlpattern = urlpattern.substr( lang.length );
		var tr = getChildElementsByTagName( lb, "table" )[ 0 ];
		tr = getChildElementsByTagName( tr, "tbody" )[ 0 ];
		tr = getChildElementsByTagName( tr, "tr" )[ 0 ];
		var tds = getChildElementsByTagName( tr, "td" );
		var longestmatch = null;
		var longestlength = 0;
		for( var i = 0; i < tds.length; ++i )
		{
			var td = tds[ i ];
			var as = getChildElementsByTagName( td, "a" );
			if( as.length < 1 )
				continue;
			var a = as[ 0 ];
			var href = a.pathname;
			if( href.length > 0 && href[ 0 ] != "/" )
				href = "/" + href;
			if( href.length > 0 && href[ href.length - 1 ] == "/" )
				href = href.substr( 0, href.length - 1 );
			var j = href.indexOf("/", 1);
			var href2;
			if( j > -1 )
				href2 = href.substr( j );
			else
				href2 = href;
			// if( href.substr( 0, urlpattern.length ) == urlpattern || href2.substr( 0, urlpattern.length ) == urlpattern )
			if( urlpattern.substr( 0, href.length ) == href )
			{
				if( href.length > longestlength )
				{
					longestmatch = td;
					longestlength = href.length;
				}
			}
			else if( urlpattern.substr( 0, href2.length ) == href2 )
			{
				if( href2.length > longestlength )
				{
					longestmatch = td;
					longestlength = href2.length;
				}
			}
		}
		if( longestmatch )
			longestmatch.className += " hovered";
	}
	/*catch(e)
	{
		// Don't let any script errors get away.
	}
	*/
}

function addEvent( object, eventName, functionPtr )
{
    if( window.addEventListener )
        object.addEventListener( eventName, functionPtr, false );
    else if( window.attachEvent )
        object.attachEvent( "on" + eventName, functionPtr );
}

function deleteEvent( object, eventName, functionPtr )
{
    if( window.removeEventListener )
        object.removeEventListener( eventName, functionPtr, false );
    else if( window.detachEvent )
        object.detachEvent( "on" + eventName, functionPtr );
}

function getScreenRect( node )
{
	var rect = {};
	rect.width = node.offsetWidth;
    rect.height = node.offsetHeight;
    rect.left = 0;
    rect.top = 0;   

    while( node )
    {
        rect.left += node.offsetLeft;
        rect.top += node.offsetTop;
        if( node.offsetParent )
        {
			rect.left -= node.scrollLeft;
			rect.top -= node.scrollTop;
		}
        node = node.offsetParent;
    }
	rect.right = rect.left + rect.width;
	rect.bottom = rect.top + rect.height;

	return rect;
}