/******************************************************************

 BlackRock :: webcommon.js

 Author: tony.vieques@blackrock.com

 (c) Copyright 2010 BlackRock, Inc.

******************************************************************/


  /***************************************************
  ParseId
  ***************************************************/
  function parseID(o){
      var i;
      var cID;
      var oID = [];
      var cls = o.className.split(" ");

      for(i in cls){
        if(cls[i].length >3 && cls[i].substring(0,3)=="id_"){
          cID = cls[i];
          return cID;
        }
      }

      return null;
  };

/*******************************************************************************
 * Twisty
 ******************************************************************************/
function add_twisty(tObj) {

	var tID = $(tObj).data("id");
	var tsel = "autotwisty";
	var targ = "twisty-target";

	if (typeof tID != "undefined" && tID != null) {

		var targSel = "." + targ + "." + tID;
		var targObj = $(targSel);

		if (targObj.length > 0) {
			targObj.toggleClass("on");
			$(tObj).parent().toggleClass("on");

			// if target is on, all controls should be on too
			if (targObj.hasClass("on")) {
				$("." + tID).addClass("on");
			} else {
				$("." + tID).removeClass("on");
			}
		}
	} else {
		// error
	}

}

/*******************************************************************************
 * Modal
 ******************************************************************************/
function add_modal(mObj) {

	var cid = $(mObj).data("id");
	var contentID = ".modal-target." + cid;
	var mediaID = "." + cid + "_media";

	// disable flash
	var cObj = $(contentID);
	warn(cObj);

	// requires modal object
	cObj.modal({
		opacity : 80,
		minHeight : 450,
		minWidth : 550,
		maxWidth : 550,
		onClose : function() {
			// close Functions
			if (is_def(mObj.isModal)) {
				// trigger media end event on modal close
				// alert("closing");
				// mObj.unloadMedia();
			}
			$.modal.close();
		}
	});

	// requires corner object
	cObj.corner({
		useImages : true,
		width : 550,
		height : 450
	});

	return false;

}


  /***************************************************
  Player
  ***************************************************/
  function add_player(pObj){

    var $fp;
    var playerUnload;

    var cid = $(pObj).data("id");
    var contentID = ".modal-target."+cid;
    var mediaID   = "."+cid+"_media";

    //log(mediaID);

    var c;

    //@TODO > technically player shoud only have one element, so why use each?
    $(mediaID).each(function(){


        //grab image info from rel attr
        var relImg = !is_empty(this.rel) && this.rel.length > 0 ? this.rel : "/images/modules/gui/audio_def.jpg";
        var afterPlayTxt = "";
        var afterPlaySel = "."+cid+" ._afterplay";

        afterPlayTxt = $(afterPlaySel).html();

        bwCheckSel  = "."+cid+" ._bwcheck";
        bwCheck = $(bwCheckSel);


        //@TODO > href needs bulletproofing logic, what if href is null?
        var mediaSrc = this.href;
        //var mediaHash = this.hash;
        var mediaTitle = this.title;

        //log("this",this);

        //@TODO > generate playlist from list of items
        //process playlist and generate playlist array here
        var playlist = [ relImg, mediaSrc ];

        //general trackEvent class to forward event and clip object to $.Metrics
        trackEvent = function(ev,c){
              //alert("tracking event "+ev+" "+c.type);
      			  if(c.type!="image"){

      			    if(c.ev=="end" && c.isFinished){

      			    }else{
        			    c.isFlowPlayer = true;
        			    c.isFinished = true;
        			    c.ev=ev;
        			    c.id=cid;
        			    //c.name=mediaHash.substring(1);
        			    c.name=mediaTitle;

        			    if(is_def($m)){ $m.trackMediaEv(c); }
        				  //warn("tracking event "+ev+" "+c.type,mediaHash.mediaSrc);
      			    }

      				}
        }

        var ini = {

          clip:{

      			onStart:  function(){

      			  var c = this.getClip();
      			  if(is_def(afterPlayTxt)){ var p = this.getPlugin("afterPlay").fadeOut(0); }
      			  trackEvent("start",c);

      			},
      			onFinish: function(){
      			  var c = this.getClip();
      			  var p;

      			  if(is_def(afterPlayTxt)){

        			  if(c.type=="video"||c.type=="audio"){
        			    p = this.getPlugin("afterPlay");
        			    p.animate({opacity:1});
        			    c.animate({opacity:0.7});

        			  }else{

        			  }
        			}

      			  trackEvent("end", c);

      			},
      			onPause:  function(){ trackEvent("pause",this.getClip());},
      			onSeek:   function(){ trackEvent("seek" ,this.getClip());},
      			autoPlay: true,
      			cachebusting: true
          },
          canvas: {backgroundColor: "#84CBFA"},
          plugins: {
            controls: {
              url:"flowplayer.controls-tube-3.1.5.swf",
              backgroundColor: '#9BA3A8',
              backgroundGradient: 'high',
              buttonColor: '#000000',
              bufferColor: '#0d6ea5',
              bufferGradient: 'low',
              sliderGradient: 'none',
              timeBgColor: '#262626',
              timeColor: '#48a5d5',
              durationColor: '#0d6ea5',
              volumeSliderColor: '#0d6ea5',
              volumeSliderGradient: 'high',
              progressColor: '#48a5d5',
              buttonOverColor: '#6BE85F',
              sliderColor: '#75abc7',
              progressGradient: 'medium',
              tooltipTextColor: '#0d6ea5',
              tooltipColor: '#C9C9C9',
              height: 25
            },
            audio: {
              url: 'flowplayer.audio-3.1.2.swf'
            }

          },
          version:[9,115],
          bufferLength:3,
          fadeInSpeed:1000,
          onBeforeLoad: function(){ },
          onLoad: function(){ /* warn("fp loaded");*/ this.setVolume(100); },
          onUnload: function(){

                  trackEvent("end", this.getClip());
                  setTimeout(function(){
                    $fp = null;
                    pObj = null;
                  },100);

          },
          onFail:function(){},
          onError:function(){ alert("an error occurred"); return false;}

        };

        //alert(ini.plugins.controls.url);

        var bitrates = 0;

        /*
             // available bitrates and the corresponding files. We specify also the video width
             // here, so that the player does not use a too large file. It switches to a
             // file/stream with larger dimensions when going fullscreen if the available bandwidth permits.
             bitrates: [
               {
               	url: "mp4:vod/demo.flowplayer/bbb-400.mp4", width: 320, height: 180, bitrate: 400,
               	// this is the default bitrate, the playback kicks off with this and after that
               	// Quality Of Service monitoring adjusts to the most appropriate bitrate
               	isDefault: true
               },
              { url: "bbb-800.mp4", width: 480, bitrate: 800 },
              { url: "bbb-1200.mp4", width: 720, bitrate: 1200 },
              { url: "bbb-1600.mp4", width: 1080, bitrate: 1600 }
             ],

             urlResolvers: 'bwcheck',
             scaling: 'fit',

            // bandwidth check plugin
            bwcheck: {
               url: 'flowplayerbwcheck-3.1.3.swf',

               // this is the reference file that is download and used to calculate the bandwidth
               netConnectionUrl: 'http://releases.flowplayer.org/swf/flowplayer-3.2.4.swf',

               // this method is called when the bandwidth check is done
               onBwDone: function(info, bitrate) {
                  if(_bwcheck.length>0){
                     alert("bw check!");
                     _bwcheck.html("Your speed is: " +bitrate+ "<br />Video file served: bbb-" +
                     info.bitrate + ".mp4<br/>" +
                     "Video width: " + info.width);
                  }
               }

            }

         */

        var bwCheckObj = {}





        if(is_def(afterPlayTxt)){
            //SEE > http://flowplayer.org/plugins/flash/content.html

            var afterPlay ={
              url: 'flowplayer.content-3.1.0.swf',
              top: 180,
              width: 302,
              height:61,
              opacity:0,
              borderRadius: 5,
              backgroundColor: '#ffffff',
              html: '<p class="title">'+afterPlayTxt+'</p>',
              style: {
               'body': {
                  fontSize: '12',
                  fontFamily: 'Arial',
                  textAlign: 'center',
                  color: '#006bb4',
                  textAlign:'left',
                  paddingLeft:'15'
               },
               'a:hover': {
                  textDecoration:'underline'
               },
               onclick: function(){
                //@TODO > add metrics tracking here
               }
             }

           };

          //only include afterplay if it isnt null
          ini.plugins.afterPlay = afterPlay;
        }

        ini.playlist = playlist;



        var playerObj = this;



          add_modal(pObj);

          function load_fp(){
          	$fp = flowplayer(playerObj,"/thirdparty/flowplayer/flowplayer-3.1.5.swf",ini);
          	playerUnload = $fp.unload;
          	pObj.isModal = true;
            pObj.unloadMedia = playerUnload; //pass unload function ref to modal controls
            $fp.play(0);
          }


          if(isIE6){
            setTimeout(function(){
                //give ie6 time to draw the modal
                load_fp();
            },1000);
          }else{
            load_fp();
          }




    });

  }

  /***************************************************
   MegaMenu
  ***************************************************/
  function do_megamenu(){

       var nTarg;
       var nMenu;
       var nCtrl = $(".nav-ctrl");

       if((typeof isIE6!='undefined' && isIE6)){ $(".nav-target").bgiframe(); }


       nCtrl.each(function(){

          var nID = "id"+this.id;
          var nTargName = "."+nID+".nav-target";
          var _nMenu = $("#navmenu");
          var _nTarg = $(nTargName);
          var _nCtrl = $(this);
          var _nCtrlParent = _nCtrl.parent(); // li

           //c
           _nCtrl.hover(
                function(){
                    show(_nCtrlParent);
                    _nTarg.trigger("mouseenter");
                },
                function(){
                    hide(_nCtrlParent);
                    hide(_nTarg);
                    hide(_nMenu);
                }
           );


           //t
           _nTarg.hover(
              function(){
                show(_nCtrlParent);
                show($(this));
                show(_nMenu);
              },
              function(){
                _nCtrl.trigger("mouseleave");
              }
           );


           if(nID.indexOf(nCtrl.length)){

             if((typeof isIE6!='undefined' && isIE6)){
               //fix nav for ie6
               _nTarg.bgiframe();
               if(typeof pngClassNames!='undefined'){alphapng.fix(pngClassNames);}
             }

             show(_nMenu);
             show(_nTarg);
             hide(_nTarg);
             hide(_nMenu);
           }

	});

	/** For Quick ETF finder **/
	/**For home page keep the navigation open **/
	if(!isHomePage){
		var $qf = $('#qf'),
			$qfa = $("#qf-ajax", $qf),
			$qfhead = $('#qf-head'), 
			$leftnav = $('#leftnav'),
			$etfLiNav = $("#nav ul li.qetf-nav"); /*Navigation for ETF finder*/

		   //On mouse over open the etf finder
			$etfLiNav.mouseover(function(e){
				if (!$qfa.hasClass("ready")) {
					do_qf_load($qfa, jsQFTabSelectedByUser);
				}
				$qf.addClass('expand');
				$qfhead.addClass('expand');
				if(isLegacyPage){
					$leftnav.css({'marginTop':treeHeight+20+"px"});	
				}
       });
			//Close the etf finder on mouseout
			$etfLiNav.mouseout(function(e){
				$qf.removeClass('expand');
				$qfhead.removeClass('expand');
				if(isLegacyPage){
					$leftnav.css({'marginTop':"0px"});	
   }
			});
			/*This applies mostly for mobile when the user clicks the head to open/close*/
			$etfLiNav.click(function(e){
				$qf.toggleClass('expand');
				$qfhead.toggleClass('expand');
				if(isLegacyPage){
					 if($qf.hasClass('expand')){
						 $leftnav.css({'marginTop':treeHeight+20+"px"});
					 }else{
						 $leftnav.css({'marginTop':"0px"});
					 }
				}

			});
			//If we mouse over the ETF finder main div, keep the finder open
			$qf.mouseover(function(e){
				$qf.addClass('expand');
				$qfhead.addClass('expand');
				if(isLegacyPage){
					$leftnav.css({'marginTop':treeHeight+20+"px"});	
				}
			});
			
			
		
	}
	
   }

  //add blocker

  if(typeof ntptEventTag == "undefined" ){
      log("ntptEventTag missing or blocked"+typeof ntptEventTag);
      //function ntptEventTag(){ return; }
  }





      /***************************************************
      // QuickFinder Toggle
      ***************************************************/
      // purpose: sets up the whole QF solution.  adds event listeners for the Plus/Minus, and the tabs
      function do_qf_click(){
        //alert("loaded");

        var $qf = $('#qf');
        var $qfa = $("#qf-ajax",$qf);
		var $qfhead = $('#qf-head');

        //isExpanded is set by the server
        if(typeof isExpanded != "undefined" && isExpanded){
          $qf.addClass("expand");
          if(!$qfa.hasClass("ready")){  // need to load the ajax file since this is the expanced state
            do_qf_load($qfa,jsQFTabSelectedByUser);
          }
        } else{
            // alert("do load");
            if(!$qfa.hasClass("ready")){
              do_qf_load($qfa,jsQFTabSelectedByUser);
            }
        }

        do_qf_tabs(); // Regardless of whether Homepage or non-home page - invoke function that lays down event handlers for the two top tabs (under PLUS/MINUS Head).
                      // this is put here since there is now more click functionality like for the PLUS/MINUS Head (qf-head).
                      // prior to vi - this was not needed since the tabs didn't show in the collapsed state and didn't need the
                      // ability to load

      }

       function do_qf_load($qfa,currTabId){    // EBISHRNA-2018 fix. now takes current Tab clicked as optional arg.
        $qfa.load("/quickfinder.htm",
    	    function(){

            if (currTabId != 'undefined' && currTabId=='#qf2') { // EBISHRNA-2018 fix. User has clicked on tab2 which requires showing that tabs ajax content rather than default view inserted by ajax
                hide($(".qt")); // hide both ajax's tab content ( both ajax tab li's have class of .qt )
                show($('#tab-2'));     // show seond tab's ajax content.
              };
	      $('ul.L2.qfm, ul.L2-tall.qfm').siblings('a').append(
					'<span>&raquo;</span>');


              setTimeout(function() {

                do_qf_menu();  // builds out the cascade menus

                $qfa.show();
                $qfa.addClass("ready");

                /* Track Unica on demand (click).
                   We cannot call unica_page from ntpagetag.js because this attaches events
                   to all links on the page. */
                $(".qf-menu a").click(function(e){
                    // get the lpos value
                    var lpos = $(this).attr("name").split("&lpos=")[1];
                    // get the link text
                    //var linkTxt = escape($(this).text());
                    var linkTxt = encodeURIComponent($(this).text());

                    // Call unica
                    if(this.href.indexOf("#")>=0){
                      //this throws an error in unica if there is a # sign
                      e.preventDefault();
                      return false;

                    }else{
                      ntptEventTag("pv=0&ev=link&linkname="+lpos+":"+linkTxt);
                    }

                });

              }, 1);

         });
      }

      function do_set_expand(state){
        state = (state==true?1:0);
        $.get('/setstate.htm?qfx='+state, function(data) {
          //$('#result').html(data);
          //alert('Load was performed.');
        });
      }

      /***************************************************
      // QuickFinder Menu (replaces superfish)
      ***************************************************/
var etfMenuLength = {};
var treeHeight,L0_UL_WIDTH = 190 /*188+2border*/ ;

function setETFDimensions(menuItems){
	var $qfbd = $('#qf-bd'),
		$leftnav = $('#leftnav');
			/*Provide margin which is the same height as the QuickETF finder
			 * so that the Contact Us module on the home page is visible
			 * Note: ETF finder is absolutely positioned and the Contact Us module goes underneath it 
			 * if not provided with the right margin
			 */
		treeHeight = menuItems*32+(1*30);
			
			if(isHomePage || isLegacyPage){
				$leftnav.css({'marginTop':treeHeight+20+"px"});				
			}
		
}


	
      function do_qf_menu(){

        var qfm = $(".qfm li");
	var $qftabsel = $('ul.qf-tab li.on a').attr('href');
	var currentUL = $("ul.qf-menu", $qftabsel);
	var $leftnav = $('#leftnav');
	var $etfLiNav = $("#nav ul li.qetf-nav");
	 var mainUL = $('.qf-menu');
	// var qfm = $(".L0  > li");
	  var $qfbd = $('#qf-bd');
	  var $qf = $('#qf'),
		$qfhead = $('#qf-head');

        qfm.hover(
          function(){
              show($(this));
              show($(this).next('ul'));

          },
          function(){
              hide($(this));
              hide($(this).next('ul'));
          }
        );


	
	//When the page loads, get the tab that is selected and the number of children
	//This is used to calculate the treeheight
	if(!etfMenuLength[$qftabsel]){
		etfMenuLength[$qftabsel] = currentUL.children().length;
      }
	treeHeight= etfMenuLength[$qftabsel] * 32 + (1*30);

	 if(isHomePage){
			$leftnav.css({'marginTop':treeHeight+20+"px"});
	 }
	 if(isLegacyPage && typeof isExpanded != "undefined" && isExpanded){
			 $leftnav.css({'marginTop':treeHeight+20+"px"});
	 }
		 
	 $qfbd.mouseleave(
		function(e){
			e.stopPropagation();
			if(!isHomePage){
				$qfhead.removeClass('expand');
				$qf.removeClass('expand');
			}
			/*Legacy pages are for /broker_dealer/restricted or about_ishares/ */
			if(isLegacyPage){
				$leftnav.css({'marginTop':"0px"});
			}
		}
	 );
	//When we leave the main div of etf finder, close the etf finder
	if(!isHomePage){
		$('#qf').bind('mouseleave',
				function(e){
					e.stopPropagation();
					$qfhead.removeClass('expand');
					$qf.removeClass('expand');
				}
			);
	}
		
}

      /***************************************************
      // QuickFinder Tabs (replaces jq ui tabs)
      ***************************************************/
      // vi-lite: added clickability for the two tabs - to give them same func. as click for PLUS/MINUS
      // re: default display state now give user ability to click tabs to open/collapse the QF.
      function do_qf_tabs(){

			
        $("#qf1,#qf2").click(function(e) {
			var $qfbd = $('#qf-bd');		 
          var $qf = $('#qf');
          var $qfa = $("#qf-ajax",$qf);

          e.preventDefault(); // the tabs have a hrefs within. So prevent those from firing

          var $qftabs = $("#qf1,#qf2");
          hide($qftabs); // remove 'on' class from both
          show($(this)); // turns on the "on" class for the clicked id - which gives the tab the white bg "on" state

          // Special case for tabs only (e.g. Plus/Minus does expand/contract tabs always). User has clicked a Tab - so not toggling. Only expanding if it isn't expanded yet.
          var currentTabId = $(this).attr("id");  // e.g.  qf2
          currentTabId ='#' + currentTabId;

          if (! $qf.hasClass("expand") ) { // only if qf does NOT have class expanded should it be expanded
            $qf.addClass("expand");
            var hasExp = $qf.hasClass("expand");
          }

          if(!$qfa.hasClass("ready")){  // like Plus/Minus - same needs for Tab clicks.
             do_qf_load($qfa,currentTabId);   // load ajax menu. EBISHRNA-2018 fix: Pass in the tab user clicked so we can display that tab's ajax content
          }

          // MUST wait some time for above to finish executing before manipulating DOM elements (that aren't there until above completes).
          setTimeout(
            function(){  // special case: User may have clicked the 2nd Tab
              var _ref = $("a",currentTabId).attr('href');  // e.g. "#tab-2"  Note: $("a", this) is selector pattern to override context of the pattern "a" - so context is now within "this" rather than whole dom
              var _tab = $(_ref); // this is the tab content we want to show

              hide($(".qt")); // hide both tabs content ( both tab li's have class of .qt )
              show(_tab);     // show the current tab's content
				
				var currentUL = $("ul.qf-menu", _tab);
				
				//Set the height of each tabs, _ref = "#tab1" or "#tab2"
				if(!etfMenuLength[_ref]){
					etfMenuLength[_ref] = currentUL.children().length;
				}
				
				setETFDimensions(etfMenuLength[_ref]);
				
				//Once you show the tab, calculate the height of the current tab and set the background height
				//Width will always remain the same
				
				
            },100);



          //  begin EBISHRNA-2313 QF session state fix
          // call ajax and pass param as follows. We actually aren't interested in the response.
          // other than glad it succeeded which would mean that most likely the setting of the
          // global var was successful.
          // in this case we are sending a payload to homepage so jsp global var can be set.
          //  IF user clicked tab 1 -  ajax URL: home.htm?QFTabSelectedByUser=1
          //  IF user clicked tab 2 -  ajax URL: home.htm?QFTabSelectedByUser=2
          // before calling ajax get a number for what tab was clicked.  send 1 if they clicked qf1 and 2 if clicked qf2
          var tabUserClicked;
          if (currentTabId == '#qf1') {
            tabUserClicked = "1";
          }
          else { tabUserClicked = "2"; };

			
          $.ajax({
           url: '/home.htm?QFTabSelectedByUser='+tabUserClicked,
            success: function(data) {
              $('.result').html(data);
              // alert('Load was performed. Set global jsp var for QFTabSelectedByUser to: '+tabUserClicked);
            }
        });
			
          //  end EBISHRNA-2313 QF session state fix


        });

      }
      //end do quickfinder



var blk = {
		ishares: {}
};
$(document)
		.ready(
				function() {
                    blk.ishares.btInfoIcons();
					blk.ishares.enhanceForMobile();
					blk.ishares.removeUnsupportedFlash();
					blk.ishares.ping();
					blk.ishares.dataEvent();
					blk.ishares.popupWin();
					$("#wrapper").removeClass("nojs");
					do_megamenu();

					/***********************************************************
					 * Misc
					 **********************************************************/
					/*
					 * function do_show(){ $(".autoshow").fadeIn("slow"); }
					 * do_show();
					 */



  /***************************************************
  Twisty
  ***************************************************/
  $(".autotwisty").click(function(){
      add_twisty(this);
      return false;
   });

  $(".autotwisty").each(function(){
     var i = parseID(this);
     $(this).data("id",i);
  });




  $(".automedia").live('click', function(e) {


      e.preventDefault();
      if ($m) {
        $m.trackLink(this);
      }
      add_player(this);
      return false;
   });

  $(".automedia").each(function(){
     var i = parseID(this);
     $(this).data("id",i);
     //log("id stored >",$(this).data("id"));
  });





  $(".automodal").click(function(e){
      e.preventDefault();
      add_modal(this,true);
      return false;
   });

  $(".automodal").each(function(){
     var i = parseID(this);
     $(this).data("id",i);
     //log("id stored >",$(this).data("id"));
  });


  // *** Email a friend links - for each anchor that has class 'email-page-popup' - create an onclick listener for that link
  $('.email-page-popup').click(function(e) {
    e.preventDefault();
    var pageUri = escape(window.document.location.pathname);
    named_popup($(this).attr('href')+'?path='+pageUri,500,375,"Email a friend","y");
    return false;  // so that user's current page doesn't also go to the href they clicked
  });



  /***************************************************
   Tabs
  ***************************************************/

  if($(".panel-tabs .tabs-hd li").length > 0){
    var $tabs = $(".panel-tabs .tabs-hd li");
    $tabs.click(function(e){
      e.preventDefault();
      hide($tabs);
      show($(this));
      var ref = $("a",this).attr('href');
      var panels = $(".tab-panel");
      var panel = $(".tab-panel" + ref);
      hide(panels);
      show(panel);
      $.Metrics.trackLink($("a", this)); // fires the Unica event for the underlying (child) link
      return false;
    });
  }


  /***************************************************
  Masthead's Site For: selector  - redone for Inst phase II.
  ***************************************************/

  // User clicks Site For: link and Investor type selector panel appears. Replaces Beauty Tip used prior to Inst Phase II for this.
  // Note: Didn't use .toggle because of special case where user can click the X in the site-for-panel to hide the panel. And
  // that puts #site-for-usertype toggle out of whack by one click. So rather will just use .click and test display setting to see what the click should do.
  $("#site-for-usertype").click  (function() {
    // test if site-for-panel css has display: none - if it is then it means it's hidden. So show it via slide down.
    if (	$("#site-for-panel").css("display") == 'none') {
      $('#site-for-panel').slideDown('slow', function() {
            // Animation complete.
      });
    }
    else  {// must be "display: block so hide it via slide up.
      $('#site-for-panel').slideUp('slow', function() {
          // Animation complete.
      });
    }
  });

  // User clicks the Site For panel's X button... so hide it via slide up.
  $("#site-for-panel #close-button").click (function() {
    $('#site-for-panel').slideUp('slow', function() {
        // Animation complete.
      });
  });

  // make the mouse when on the Site For panel's X button change into a "hand" - so user knows it it an actionable click
  $('#site-for-panel #close-button').hover(function() {
    $(this).addClass('mouse-pointer');
    }, function() {
       $(this).removeClass('mouse-pointer');
  });

  // INST phase II - fresh visitor treatment
  if (isCookiedForInvestorType == false) {  // then user is fresh visitor to the site. Force them to FP and show the windowshade.

    var switchUserToFP = ajaxSwitchInvestorType('FP');  // forcing to FP. Fix for EBISHRNA-2018 5.04.2011 jj

    var bt_timer_newuser = setTimeout(function() {    // show the window shade where they can choose another investor type if desired.
      $('#site-for-panel').slideDown('slow', function() {
        // Animation complete.
      });
    }, 3000)

    var bt_timer_newuser2 = setTimeout(function() {   // roll up the window shade.
      $('#site-for-panel').slideUp('slow', function() {
          // Animation complete.
        });
      }, 10000)


  } // end fresh visitor treatment

  /**
   * This function forces an investor type to a given type (e.g. FP) by making use of the switch.htm solution already on the site
    * in this case it's an ajax call to it.
    *
    * Input:  targetInvestorType  - the investor type to switch the user to - eg. FP  or INDIV or INST.
   */
  function ajaxSwitchInvestorType(targetInvestorType) {
    $.ajax({
          url: "/misc/switch.htm?investorType="+targetInvestorType,
          success: function(){
            isCookiedForInvestorType = true; // set this to true since success means there should now be a cookie.
            $('#site-for-container').addClass("investortype_set_via_ajax"); // purely as a way to see easily if this switch worked (use firebug). Class is not used by anything.
          }
    });
  }

  //QUICKFINDER
  //placed on bottom to delay call, do_qf_click  isnt defined in cases where QF is disabled

    setTimeout("do_qf_click()", 1);

});


/**
 * === TPM ===
 */
$(document).ready(function() {
    tpmEntryLaunch();
    tpmUnicaEvents();
});

/**
 * === TPM ===
 */
	function tpmEntryLaunch() {
        if( $(".tpm-entry-launch").size()>0 ){
             $(".tpm-entry-launch form").submit(function(){
                ntptEventTag("pv=0&ev=link&linkname=Submit Data&lpos=TPM:Data submission button");
             })
        }
    }

    function tpmUnicaEvents() {
        if( $(".samplePortfolioImg").size()>0 ){
             $(".samplePortfolioImg").click(function(){
                ntptEventTag('ev=link&linkname=' + escape('Right Nav: Sample Portfolio: Image'));
             })
        }
        if( $(".samplePortfolioView").size()>0 ){
             $(".samplePortfolioView").click(function(){
                 ntptEventTag('ev=link&linkname=' + escape('Right Nav: Sample Portfolio: View'));
             })
        }
        if( $(".tpm-overview .popupWin").size()>0 ){
             $(".tpm-overview .popupWin").click(function(){
                ntptEventTag('ev=link&linkname=' + escape('Page Body: Find a Portfolio: View'));
             })
        }
        if( $(".tpm-sample .popupWin.popup").size()>0 ){
             $(".tpm-sample .popupWin.popup").click(function(){
                ntptEventTag('ev=link&linkname=' + escape('Right Nav: See all Portfolios: View'));
             })
        }
    }

/*******************************************************************************
 * //Unescape Function
 ******************************************************************************/
String.prototype.EntityDecode = function() {
	var t = document.createElement('div');
	t.innerHTML = this;
	return t.firstChild.nodeValue;
}
/*******************************************************************************
 * Flash Dectection
 ******************************************************************************/
blk.ishares.removeUnsupportedFlash = function () {
	if (!swfobject.hasFlashPlayerVersion("9.0.18")) {

		$.each($('span.arbitration-span h4 a span'), function(key, value) {
			// Exploring ETFs
			if( $(this).text() === "Exploring ETFs" ){
				$('span.arbitration-span h4 a span:contains("Exploring ETFs")').parents('span.arbitration-span').remove();
			}
			// ETF Basics
			else if( $(this).text() === "ETF Basics" ){
				$('span.arbitration-span h4 a span:contains("ETF Basics")').parents('span.arbitration-span').remove();
			}
			// Index Comparison Tool
			else if( $(this).text() === "Index Comparison Tool" ){
				$('span.arbitration-span h4 a span:contains("Index Comparison Tool")').parents('span.arbitration-span').remove();
			}
			// FI Portfolio Builder Tool Launcher
			else if( $(this).text() === "Fixed Income Portfolio Builder Tool" ){
				$('span.arbitration-span h4 a span:contains("Fixed Income Portfolio Builder Tool")').parents('span.arbitration-span').remove();
			}
			// FI ETF Investing Guide Launcher
			else if( $(this).text() === "Exploring ETFs: Fixed Income ETFs Investing" ){
				$('span.arbitration-span h4 a span:contains("Exploring ETFs: Fixed Income ETFs Investing")').parents('span.arbitration-span').remove();
			}
			// FI ETF Investing Guide Launcher
			else if( $(this).text() === "Exploring ETFs: Cash Equitization Strategies" ){
				$('span.arbitration-span h4 a span:contains("Exploring ETFs: Cash Equitization Strategies")').parents('span.arbitration-span').remove();
			}
			// Cash Equitization Launcher
			else if( $(this).text() === "Exploring ETFs: Cash Equitization Strategies" ){
				$('span.arbitration-span h4 a span:contains("Exploring ETFs: Cash Equitization Strategies")').parents('span.arbitration-span').remove();
			}
			// Dividends Structure Launcher
			else if( $(this).text() === "Exploring ETFs: Dividends Structure" ){
				$('span.arbitration-span h4 a span:contains("Exploring ETFs: Dividends Structure")').parents('span.arbitration-span').remove();
			}
			// Completion Strategies Launcher
			else if( $(this).text() === "Exploring ETFs: Portfolio Completion Strategies" ){
				$('span.arbitration-span h4 a span:contains("Exploring ETFs: Portfolio Completion Strategies")').parents('span.arbitration-span').remove();
			}
			// Blending Indexing & Active Strategies
			else if( $(this).text() === "Exploring ETFs: Blending Indexing & Active Strategies" ){
				$('span.arbitration-span h4 a span:contains("Exploring ETFs: Blending Indexing & Active Strategies")').parents('span.arbitration-span').remove();
			}
			// Asset Allocation
			else if( $(this).text() === "Exploring ETFs: Asset Allocation" ){
				$('span.arbitration-span h4 a span:contains("Exploring ETFs: Asset Allocation")').parents('span.arbitration-span').remove();
			}
		});
		$.each($('span.arbitration-span h4 a'), function(key, value) {
			// 5 Factors Selecting an ETF
			if( $(this).text() === "Why iShares: Selecting an ETF" ){
				$('span.arbitration-span h4 a:contains("Why iShares: Selecting an ETF")').parents('span.arbitration-span').remove();
			}
			// Compare All Funds - Total Performance Page
			else if( $(this).text() === "Compare All Funds" ){
				$('span.arbitration-span h4 a:contains("Compare All Funds")').parents('span.arbitration-span').remove();
			}
			// Take the total performance challenge
			else if( $(this).text() === "Take the Total Performance Challenge(SM)" ){
				$('span.arbitration-span h4 a:contains("Take the Total Performance Challenge(SM)")').parents('span.arbitration-span').remove();
			}
			// Why iShares: Sectors & Subsectors
			else if( $(this).text() === "Why iShares: Sectors & Subsectors" ){
				$('span.arbitration-span h4 a:contains("Why iShares: Sectors & Subsectors")').parents('span.arbitration-span').remove();
			}
		});
		// Exploring ETFs LINK ONLY
		$.each($('span.arbitration-span div.relres ul li a span'), function(key, value) {
			// Exploring ETFs
			if( $(this).text() === "Exploring ETFs" ){
				if( $('span.arbitration-span div.relres ul li a span').length < 2){
					$('span.arbitration-span div.relres ul li a span').parents('span.arbitration-span').remove();
				} else {
					$('span.arbitration-span div.relres ul li a span').parents('li:first-child').remove();
				}
			}
		});
		// Common Tools
		$('#task_100003110').remove();
		// Total Performance Page
		$('#flashpocket').remove();
		// Tools -> Common Tasks -> Play a demo
		$('.tools_landing .jqModal').remove();
		// Flash video for WFA advisors from all ETF pages
		$('#wfa #flashContentBrowser').remove();
		// Why Envision Movie link for WFA
		$('#wfa #sidebar li.module div h2#whyEnvision').parents('li.module').remove();

		$.each($('.about_pages #right_column .subhead'), function(key, value) {
			// Contact Us About Right Module
			if( $(this).text() === "About iShares" ){
				$.each($(this).next(), function(key, value) {
					if( $(this).text().indexOf('Learn more') != -1 ){
						$(this).remove();
					}
				});
				$(this).remove();
			}
		});
	}
}

/*******************************************************************************
 * Beauty Tips Scripts //moved here from product_info.js because used everywhere.
 *******************************************************************************/
blk.ishares.btInfoIcons = function () {
    $('.pi-info-icon').mouseover(function() {
        $(this).attr('title',"<div class='title'>"+$(this).attr('alt')+"</div>"+$(this).attr('title'));
        $(this).bt({
        offsetParent:$('body#blk'),     // setting offset to higher level container to fix ie6 beauty tip issue where bt was displaying underneath Top Nav Menu
        positions:['top','right'],
        spikeLength:8,
        spikeGirth:12,
        windowMargin:20,
        strokeStyle:"#60e7f9",
        strokeWidth:1,
        fill:'#ecfaff',
        cornerRadius:3,
        width:230,
        cssClass:'pi-info-tip'});
      $(this).btOn();
    })
    .mouseout(function() {
      $(this).btOff();
    });
}

blk.ishares.ping = function () {
    $('[ping]').click(function(e) {
        ntptEventTag($(this).attr('ping'));
    });
}

blk.ishares.dataEvent = function () {
    $('[data-event]').click(function() {
        var dataEvent = $(this).attr('data-event') + '&';
        var dataLabel = $(this).attr('data-label').replace('&','%26');
        ntptEventTag(dataEvent + "&" + dataLabel);
        if (dataEvent.indexOf('filedownload') != -1) {
            ntptEventTag(dataEvent.replace('filedownload','link') + dataLabel);
        }
    });
}

blk.ishares.popupWin = function () {
    $('.popupWin').click(function(e) {
            var winHeight;
            var left = (screen.width/2)-($(this).attr("data-width")/2);
            if ($(this).attr("data-height")) {
                winHeight = $(this).attr("data-height");
            } else {
                winHeight = window.screen.availHeight * .85;
            }
            window.open(
                $(this).attr('href'),
                'popupWin',
                'status=0,' +
                'toolbar=0,' +
                'location=0,' +
                'menubar=0,' +
                'resizable=1,' +
                'scrollbars=1,' +
                'height=' + winHeight + ',' +
                'width=' + $(this).attr("data-width") + ',' +
                'left=' + left
            );
            e.preventDefault();
    });
}

/*******************************************************************************
 * MOBILE Scripts
 *******************************************************************************/
blk.ishares.enhanceForMobile = function () {
	if ( document.body.className.indexOf('mobile') > 0 ) {
		/* Remove hover state on megamenu */
		$('#navmenu .mega-menu ul.mega-list ul.col-items li a').hover( function () {
			var location = $(this).attr('href');
			window.location = location;
		});
	}
}

// Note: Below added during SPIN project but useful beyond that.
// jquery extension to easily get request parameter name value pairs w/out hassle of parsing.  http://jquery-howto.blogspot.com/2009/09/get-url-parameters-values-with-jquery.html
// usage:
//   Get object of URL parameters would be this (without comments of course):
//   var allVars = $.getUrlVars();
//   Getting URL var by its name - the name of the parameter
//   var byName = $.getUrlVar('name');
//  example: if url was this: http://us.ishares.com/misc/faq.htm?id=q1&name=john
//           var allVars = $.getUrlVars() would return {"id"  : "q1", "name" : "john" }
//           var byName = $.getUrlVars('name') would return {"john" }
$.extend({
  getUrlVars: function(){  // Reads a page's GET URL variables and return them as an associative array.
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
      hash = hashes[i].split('=');
      vars.push(hash[0]);
      vars[hash[0]] = hash[1];
    }
    return vars;
  },
  getUrlVar: function(name){
    return $.getUrlVars()[name];
  }
});


/*******************************************************************************
 * // Legacy
 ******************************************************************************/


  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://"+WSOD_URL+"/ishares/qc/old_us/research/summary/summary.asp?symbol="+ticker,
                   params:"location=0,status=1,scrollbars=1,width=815,height=720"
                },
                quotes_chart:{
                   url:"http://"+WSOD_URL+"/ishares/qc/old_us/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']);
  }



