/**
 * JavaScript: Main JavaScript include
 *
 * @file              /javascript/webcommon.js
 * @author            chris.geheran@barclaysglobal.com / drew.ross@barclaysglobal.com
 * @revision          $Id$
 */

/*
 * Background Cache Control: This function helps the nav images from refreshing, which slows down
 *  the navigation speed in some browsers like ie6.
*/
try {
  document.execCommand("BackgroundImageCache", false, true);
} catch(err) {}
/* End BG Cache controller */

/*
 * @functions     pollScroll() and scroll()
 * @description   The below 2 functions are used to catch scrolling events and wait for the scrolling to complete
 *                to trigger the fix Menu functioned defined above. This is used to correct the location of the css
 *                3 tier navigation.
*/
  var scrollPos=0; var pollInt;
  window.onscroll=scroll;
  function pollScroll() {
    if (document.getElementById("leftNav")!=null)
        fixMenu(document.getElementById("leftNav"),"left");
  }
  function scroll() {
    clearTimeout(pollInt);
    pollInt = setTimeout("pollScroll()",500);
    scrollPos = document.body.scrollTop;
  }

/*
 * @function      fixMenu(ULNode,lnav)
 * @author        chris.geheran@barclaysglobal.com
 * @parameters    UL Element, string
 *
 * @description   This is run in the doOnload function of each page including the top and left navigation elements.
 *                The function runs through the menus to first make sure that the menus themselves will not run below
 *                the page break(for left nav only), and then executes a hover fix for ie6 that uses class names rather
 *                than hover to show/hide the tiered navigation.
*/
function fixMenu(ULNode,nav) {
  if (nav=="left") {
    var browserWindowHeight = document.documentElement.clientHeight+document.documentElement.scrollTop;
    var leftNavYpos = ULNode.offsetTop;
    var allUL = ULNode.getElementsByTagName("UL");

    for (k=0; k<allUL.length; k++) {
      ulHeight = allUL[k].offsetHeight;  //finds the height of the UL element

      //finding the y position of the UL element
      if (allUL[k].className=="level2") {
        ulYpos = allUL[k].offsetParent.offsetParent.offsetParent.offsetTop + allUL[k].offsetParent.offsetParent.offsetTop + allUL[k].offsetParent.offsetTop;
      } else {
        ulYpos = allUL[k].offsetParent.offsetTop;
      }

      ulExtendsTo = ulYpos+ulHeight+4;  //adds our height and y positions to find the bottom of the UL pop

      //reset the top location of the UL if it falls below the browser
      if (ulExtendsTo > browserWindowHeight) {
        allUL[k].style.top = (browserWindowHeight-ulExtendsTo)+"px";
        //alert("New top: "+allUL[k].style.top);
      } else {
        allUL[k].style.top = "-1px";
      }
    }
  }

  //ie6 fix. This fixes the issue ie6 has with using hover by setting mouse events to change class name
	if (document.all&&document.getElementById) {
		for (i=0; i<ULNode.childNodes.length; i++) {
			node = ULNode.childNodes[i];
			if (node.nodeName=="LI") {
				node.onmouseover 	= function() { this.className+=" over1"; }
			  node.onmouseout		= function() { this.className=this.className.replace(" over1",""); }
        if (node.lastChild.nodeName=="UL") {
					for (j=0; j<node.lastChild.childNodes.length; j++) {
						level2Node = node.lastChild.childNodes[j];
            if (level2Node.nodeName=="LI") {
              level2Node.onmouseover 	= function() { this.className+=" over2"; }
              level2Node.onmouseout		= function() { this.className=this.className.replace(" over2",""); }
              level2Node.background = "";
            } //end if
					} //end for j
				} //end if lastChild
			} //end if node LI
		} //end for i
	} //end browser check
} //end function

/*
 * @functions     openWindow
 * @description   Uses javascript to pop open a window
 *
*/
function openSpecial(name,ticker) {
  //defining parameters hashed by name to control window parameters
  //this helps solve issues of redundance in declaring page parameters and using seperate functions
  //to open each window
    params = {
              view_chart:{
                 url:"http://www.barclays.wallst.com/barclays/ishares/research/summary/summary.asp?symbol="+ticker,
                 params:"location=0,status=1,scrollbars=1,width=815,height=720"
              },
              quotes_chart:{
                 url:"http://www.barclays.wallst.com/barclays/ishares/research/summary/landing.asp?pt=false",
                 params:"location=0,status=1,scrollbars=1,width=815,height=720"
              },
              email_a_friend:{
                 url:"/misc/emailafriend.htm",
                 params:"toolbar=no,scrollbars=no,resizable=yes,width=420,height=580"
              },
              voting_search: {
                 url:"http://vds.issproxy.com/SearchPage.php?CustomerID=228?pt",
                 params:"toolbar=no,scrollbars=no,resizable=yes,width=800,height=720"
              },
              options_available: {
                 url:"/product_info/fund/options_available.htm",
                 params:"toolbar=no,scrollbars=yes,resizable=yes,width=560,height=600"
              }
    };
    window.open(params[name]['url'], name, params[name]['params']);
}

function submitInvestorType(investor_type_cd) {
  document.getElementById('investorType').value = investor_type_cd;
  document.getElementById('investor_form').submit();
}

/*
 * @functions     linksChange
 * @description   Uses javascript to show a hidden div as a dropdown menu.
 *                For link-cluster-e content (homepage right links)
 *
*/
function linksChange(aRef) {
  var dropdiv = aRef.parentNode.parentNode;
  if (dropdiv.className.indexOf("showlinks") == -1) {
    var allSubMenus = dropdiv.parentNode.getElementsByTagName("div");
    for (i=0; i<allSubMenus.length; i++) {
      if (allSubMenus[i].className.indexOf("showlinks") != -1) {
        allSubMenus[i].className = allSubMenus[i].className.substring(0,allSubMenus[i].className.indexOf(" "));
        dropdiv.className += " showlinks";
        break;
      }
    }
    dropdiv.className += " showlinks";
  } else {
    dropdiv.className = dropdiv.className.substring(0,dropdiv.className.indexOf(" "));
  }
}

/*
 * @functions     findParent(node)
 * @description   Recursive retrieval of parent node in twisty with "showlinks" classname.
 * $author        gehechr
 *
*/
function findParent(node) {
  if (node.className.indexOf("showlinks")==-1){
    return closeParent(node.parentNode);
  } else {
    return node;
  }
}

/*
 * @functions     closeParent(node)
 * @description   Closes twisty parent.
 * $author        nassmic
 *
*/
function closeParent(node){
  var element = findParent(node);
  if(element != null){
    element.className = element.className.replace('showlinks', 'showmenu');
  }
}

/*
 * @functions     changeTwisty
 * @description   Twisty text show/hide
 * $author        gehechr
 *
*/
var oldTwisty=null;
function changeTwisty(node, keepOld) {

  /* Internal function to find the right node to manage */
  function findTwistyContainer(node) {
    if (node.className!='twisty' && (node.className.indexOf("show_twisty") == -1)) {
      return findTwistyContainer(node.parentNode);
    } else {
      return node;
    }
  }
  var nodeObject = findTwistyContainer(node.parentNode);
  if (!keepOld) {
    if (oldTwisty!=null && oldTwisty!=nodeObject) {
      if (oldTwisty.className.indexOf(" show_twisty")!=-1) {
        oldTwisty.className = oldTwisty.className.substr(0,oldTwisty.className.indexOf(" show_twisty"));
      }
    }
  }
  if (nodeObject.className.indexOf("show_twisty")!=-1) {
    nodeObject.className = nodeObject.className.substr(0,nodeObject.className.indexOf(" show_twisty"));
  } else {
    nodeObject.className += " show_twisty";
    if (!keepOld)
      oldTwisty = nodeObject;
  }
}

/*
 * Get rid of this (used on homepage, change over to window.open)
*/
function newWin(n,wn,w,h,t,l,s) { new_window=window.open(n, wn, 'toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars='+s+',resizable=0,width='+w+',height=' + h + ((t)?',screenX='+t+',top='+t:'') + ((l)?',screenY='+l+',left='+l:'')); if (new_window.opener==null) { new_window.opener=self; } if (window.focus) new_window.focus(); }

/*
 * @functions     learnCalendar Object
 * @description   Manage Learn Calendar
 *
*/
function LearnCalendar() {
  this.prevButtonDiv = document.getElementById("prevmonth");
  this.nextButtonDiv = document.getElementById("nextmonth");
  this.calendarImage = document.getElementById("calendarimage");
  this.current = 0;
  this.calendar = new Array();
}

LearnCalendar.prototype.addCalendar = function(imgName) {
  this.calendar[this.calendar.length] = imgName;
}

LearnCalendar.prototype.hasNext = function() {
  return ((this.current+1) < this.calendar.length);
}

LearnCalendar.prototype.hasPrev = function() {
  return (this.current>0);
}

LearnCalendar.prototype.next = function() {
  this.current++;
  this.calendarImage.src = "/content/images/learn/"+this.calendar[this.current];
  this.prevButtonDiv.style.visibility = "visible";

  if (!this.hasNext()) {
    this.nextButtonDiv.style.visibility = "hidden";
  }
}

LearnCalendar.prototype.prev = function() {
  this.current--;
  this.calendarImage.src = "/content/images/learn/"+this.calendar[this.current];
  this.nextButtonDiv.style.visibility = "visible";

  if (!this.hasPrev()) {
    this.prevButtonDiv.style.visibility = "hidden";
  }
}

/*
 * @functions     showCalendarTip
 * @description   Tip show/hide
 *
*/
function calendarTip(node) {
  function closeOtherTips() {
    var tipTable = document.getElementById('calendarToolTipTable');
    var divElements = tipTable.getElementsByTagName('div');

    for (var i=0; i<divElements.length; i++) {
      if (divElements[i].className.indexOf('showcaltip') != -1) {
        divElements[i].className = divElements[i].className.substr(0,divElements[i].className.indexOf(" showcaltip"));
      }
    }
  }

  function findTipSwitch(node) {
    if (node.className.indexOf('event_description') == -1) {
      return findTipSwitch(node.parentNode);
    } else {
      return node;
    }
  }
  var nodeObject = findTipSwitch(node);

  if (nodeObject.className.indexOf('showcaltip') == -1) {
    closeOtherTips();
    nodeObject.className += " showcaltip";
  } else {
    nodeObject.className = nodeObject.className.substr(0,nodeObject.className.indexOf(" showcaltip"));
  }
}

/* pulled from ishares.com */
function goldRefresh() {
  document.getElementById('spotprice').innerHTML = '<a href="http://www.thebulliondesk.com"><img border="0" width="73" height="58" alt="" src="http://www.thebulliondesk.com/freecharts/freeprice.aspx?id=77535717-72e1-4735-b18f-f0271f7422c5" /></a>';
}

function silverRefresh() {
  document.getElementById('spotprice').innerHTML = '<a href="http://www.thebulliondesk.com"><img border="0" width="67" height="58" alt="" src="http://www.thebulliondesk.com/freecharts/freeprice.aspx?id=7d61191e-b11d-4013-a2ae-37a49a610e8d" /></a>';
}

function redirectOutput(myForm) {
	var sWidth = (screen.width) ? screen.width : 0;
	if (sWidth > 1000){  // if the screen res is higher than 800x600 then open the large auditorium
		aWidth = 1014;
		aHeight = 678;
	}
	else{
		aWidth = 790;
		aHeight = 510;
	}
  var w = window.open("about:blank","Popup_Window","status=0,toolbar=0,location=0,menubar=0,directories=0,scrollbars=yes,height=" + aHeight + ",width=" + aWidth);
  myForm.target = 'Popup_Window';
  return true;
}

function makePretty(tId, cNm) {
  var tbl = document.getElementById(tId);
  var rows = tbl.getElementsByTagName("tr");
  var highlight,noHighlight;

  for (i=0; i<rows.length; i++) {
    var currentClass = rows[i].className;

    //clear out any pre-existing highlight classes (class assumed to be last in class Defs)
    noHighlight = currentClass.substr(0,currentClass.indexOf(cNm));
    highlight = noHighlight + " " + cNm;

    rows[i].className = (i % 2==0) ? highlight : noHighlight;
  }
}


function irc_popup(page) {
  ircWindow=this.open(page,"IRCWindow","toolbar=no,scrollbars=yes,resizable=yes,height=810,width=840");
  ircWindow.focus();
}
function etf_popup(page) {
  etfWindow=this.open(page,"ETFWindow","toolbar=no,scrollbars=yes,resizable=yes,height=550,width=816");
  etfWindow.focus();
}
function splash_inv_type_defs(page){
  popupWindow=this.open(page,"Investor_Categories","toolbar=no,scrollbars=no,resizable=yes,height=430,width=270");
  popupWindow.focus();
}

function quotes_popup(page){
  quotesWindow=this.open(page,"Quotes_and_Charts","toolbar=no,resizable=yes,scrollbars=yes,height=720,width=816");
  quotesWindow.focus();
}
function indextracker_popup(page){
  indextrackerWindow=this.open(page,"Index_Tracker","status=yes,toolbar=no,scrollbars=yes,resizable=yes,height=776,width=805"); /* 550,width=816*/
  indextrackerWindow.focus();
}
function named_tool_popup(page, height, width, name) {
  startWindow=this.open(page,name,"toolbar=no,scrollbars=yes,resizable=yes,height="+height+",width="+width);
  startWindow.focus();
}
function tool_popup(page) {
  startWindow=this.open(page,"CtrlWindow","toolbar=no,scrollbars=yes,resizable=yes,height=700,width=820");
  startWindow.focus();
}
function sizeable_tool_popup(page, height, width) {
  startWindow=this.open(page,"CtrlWindow","toolbar=no,scrollbars=yes,resizable=yes,height="+height+",width="+width);
  startWindow.focus();
}
function how_tool_popup(page){
  startWindow=this.open(page,"CtrlWindow","toolbar=no,scrollbars=yes,resizable=yes,height=670,width=970");
  startWindow.focus();
}
function tell_popup(page){
  startWindow=this.open(page,"Tell_Us_Your_Story","toolbar=no,scrollbars=yes,resizable=yes,height=766,width=488");
  startWindow.focus();
}

function privacy_popup(page){
  privacyWindow=this.open(page,"Privacy_Policy","toolbar=no,resizable=yes,scrollbars=yes,height=700,width=740");
  privacyWindow.focus();
}



/*
 * @functions     bubbleOn bubbleOff
 * @description   Bubble layer functions for home page
 *
*/

currBubble = '';

function bubbleOn(bubbleName) {
  if (currBubble == bubbleName) {
    bubbleOff(currBubble);
  }
  document.getElementById(bubbleName).style.visibility = 'visible';
  currBubble = bubbleName;
}

function bubbleOff(bubbleName) {
  document.getElementById(bubbleName).style.visibility = 'hidden';
}      

        
function swapImg(n) { 
  if (n != currPage) { 
    document.getElementById('num_' + currPage).src = '/images/betterworld/num_' + currPage + '_off.gif'; 
  } 
  document.title.src = '/images/betterworld/page' + n + '_label.gif';   
  document.getElementById('num_' + n).src = '/images/betterworld/num_' + n + '_on.gif';   
} 

function swapImgOff(n) { 
  if (n != currPage) { 
    document.getElementById('num_' + currPage).src = '/images/betterworld/num_' + currPage + '_on.gif'; 
  }   
  document.title.src = '/images/betterworld/page' + currPage + '_label.gif';   
  document.getElementById('num_' + n).src = '/images/betterworld/num_' + n + '_off.gif';   
}   


/* $(document).ready(function(){
		$('#header-panel').hide();
		$('#clickme').click(function(){
		$('#header-panel').show();

		})
		$('#close-button').click(function(){
		$('#header-panel').hide();
		})
	});
*/

$(document).ready(function() {
    $("a.ishares_tooltip").bind('mouseover', function() {

        var tooltip = $("#" + $(this).attr("name"));
        $(this).parent().after(tooltip);
        $("div.tab_content_left-channel").css({ "z-index": "0" });
        $("div.tab_content_summary").css({ "z-index": "10" });
        $("div.tab_content_resources").css({ "z-index": "5000" });
        if (tooltip.hasClass("not-visible")) {
            tooltip.removeClass("not-visible").addClass("is-visible");
        }
        var tPos = $(this).position();
        var tWidth = $(this).width();
        var mPos = tooltip.position();
        var mWidth = tooltip.width();
        var mHeight = tooltip.height();

        if ($(this).hasClass("fp-registered")) {
            tooltip.css({ "left": (tPos.left - mWidth + 5) + "px", "top": (tPos.top + 80 - mHeight / 2) + "px" });
            
            $("a").bind('mouseleave', function() {
                //alert($(this).parent().next());
                if ($(this).parent().next().hasClass("is-visible")) {
                    $(this).parent().next().removeClass("is-visible").addClass("not-visible");
                }
            });        
        }
        else {
            tooltip.css({ "left": (tPos.left - mWidth + 5) + "px", "top": (tPos.top + 28 - mHeight / 2) + "px" });
        }

        return false;
    });

    $("a.ishares_tooltip2").bind('mouseover', function() {
        var tooltip;
        if ($(this).hasClass("fp-registered")) {
            tooltip = $("#fpVideoRegistered");
            $("a").bind('mouseleave', function() {
                //alert($(this).parent().next());
                if ($(this).parent().next().hasClass("is-visible")) {
                    $(this).parent().next().removeClass("is-visible").addClass("not-visible");
                }
            });            
        }
        else {
            tooltip = $("#fpVideoTooltip");
        }

        $(this).parent().after(tooltip);

        var tPos = $(this).position();
        var tWidth = $(this).width();
        var mPos = tooltip.position();
        var mWidth = tooltip.width();
        var mHeight = tooltip.height();
        if ($(this).hasClass("fp-registered")) {
            tooltip.css({ "left": (tPos.left + tWidth + 60) + "px", "top": (tPos.top + 90 - mHeight / 2) + "px" });
        }
        else {
            tooltip.css({ "left": (tPos.left + tWidth + 60) + "px", "top": (tPos.top + 28 - mHeight / 2) + "px" });
        }

        if (tooltip.hasClass("not-visible")) {
            tooltip.removeClass("not-visible").addClass("is-visible");
        }
        return false;

    });

    $("a.ishares_tooltip3").bind('mouseover', function() {
        var tooltip;
        if ($(this).hasClass("fp-registered")) {
            tooltip = $("#fpVideoRegistered");
            $("a").bind('mouseleave', function() {
                //alert($(this).parent().next());
                if ($(this).parent().next().hasClass("is-visible")) {
                    $(this).parent().next().removeClass("is-visible").addClass("not-visible");
                }
            });
            
        }
        else {
            tooltip = $("#fpVideoTooltip");
        }
        $(this).parent().after(tooltip);
        $("div.tab_content_left-channel").css({ "z-index": "5000" });

        var tPos = $(this).position();
        var tWidth = $(this).width();
        var mPos = tooltip.position();
        var mWidth = tooltip.width();
        var mHeight = tooltip.height();

        if (tooltip.hasClass("fp-registered")) {
            tooltip.css({ "left": (tPos.left + mWidth / 2 + 20) + "px", "top": (91 - mHeight / 2) + "px" });
        }
        else {
            tooltip.css({ "left": (tPos.left + mWidth / 2 + 20) + "px", "top": (150 - mHeight / 2) + "px" });
        }

        if (tooltip.hasClass("not-visible")) {
            tooltip.removeClass("not-visible").addClass("is-visible");
        }
        return false;
    });

    $(".hidden_tooltip").bind('mouseleave', function() {
        if ($(this).hasClass("is-visible")) {
            $(this).removeClass("is-visible").addClass("not-visible");
        }
    });
});  



$(document).ready(function(){
  $("a.clickregtips_tooltip").bind('mouseover', function() {  
    
    if ($("#" + $(this).attr("name")).hasClass("not-visible")) {
    	$("#" + $(this).attr("name")).removeClass("not-visible").addClass("is-visible");
    }

	
    
    return false;
  });
  
  $("a.clickregtips_tooltip").bind('mouseleave', function() {  
    if ($("#" + $(this).attr("name")).hasClass("is-visible")) {
    	$("#" + $(this).attr("name")).removeClass("is-visible").addClass("not-visible");
    }
  });  
});  


