/******************************************************************

 BlackRock :: webcommon.js
 
 Author: tony.vieques@blackrock.com

 (c) Copyright 2010 BlackRock, Inc.

******************************************************************/



  if(typeof useQuickFinder != "undefined" && useQuickFinder){


      /***************************************************
      // QuickFinder Toggle
      ***************************************************/
      function do_qf_click(){
        //alert("loaded");

        var $qf = $('#qf');
        var $qfa = $("#qf-ajax",$qf);

        //isExpanded is set by the server
        if(typeof isExpanded != "undefined" && isExpanded){
          $qf.addClass("expand");
          if(!$qfa.hasClass("ready")){
           do_qf_load($qfa);
          }

          if(!isHomePage){
            //toggle qf expand/contract
            $("#qf-head").click(function() {

              $qf.toggleClass("expand");
              var hasExp = $qf.hasClass("expand");

            });

          }

        } else if(!isHomePage){
          //toggle qf expand/contract
          $("#qf-head").click(function() {

            $qf.toggleClass("expand");
            var hasExp = $qf.hasClass("expand");
            //do_set_expand(hasExp);

            if(!$qfa.hasClass("ready")){
             do_qf_load($qfa);
            }

          });
         }else{
            //alert("do load");
            if(!$qfa.hasClass("ready")){
             do_qf_load($qfa);
            }
         }
      }

      function do_qf_load($qfa){
        $qfa.load("/quickfinder.htm",
    	    function(){
              setTimeout(function() {

                do_qf_menu();
                do_qf_tabs();
                $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());
                    // Call unica
                    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)
      ***************************************************/
      function do_qf_menu(){
        var q = {};
        q.curr = null;
        q.prev = null;

        $(".qfm li").hover(
          function(){
              show($(this));
              show($(this).next('ul'));
          },
          function(){
              hide($(this));
              hide($(this).next('ul'));
          }
        );
      }

      /***************************************************
      // QuickFinder Tabs (replaces jq ui tabs)
      ***************************************************/
      function do_qf_tabs(){
        var $qftabs = $(".qf-tab li");
         $qftabs.click(function(e){
            e.preventDefault();
            hide($qftabs);
            show($(this));
            var _ref = $("a",this).attr('href');
            var _tab_r = "#qf-tabs "+_ref;
            _tab_r = "#"+_tab_r.split("#")[2];
            var _tab = $(_tab_r);
            hide($(".qt"));
            show(_tab);
            return false;
         });
      }
      //end do quickfinder


    }

    /***************************************************
    SNR Preview
    ***************************************************/
    /* Site Nav Redux preview link function */
    /* expose this outside of the $document.ready function */
    function snrPreview(){
      $("#snr-preview-window").modal({ // opens the Simple Modal Window
        opacity:0,
        focus:false,
        overlayCss: {backgroundColor:"#ffffff"},
        containerCss: {height:"553px",width:"828px"} // required to prevent conflicting sizing with WFA simple modal usage
       });
      $(".modalCloseImg").hide();
    };




$(document).ready(function() {


  /***************************************************
   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=="id_nav5"){

             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);
           }



       });
   }
  do_megamenu();

  /***************************************************
  Misc
  ***************************************************/
   function do_show(){
   		  $(".autoshow").fadeIn("slow");
   }
   do_show();

  /***************************************************
  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
       }

   }
  /***************************************************
  Twisty
  ***************************************************/
  $(".autotwisty").click(function(){
      add_twisty(this);
      return false;
   });

  $(".autotwisty").each(function(){
     var i = parseID(this);
     $(this).data("id",i);
  });

  /***************************************************
  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 = "";


        afterPlayTxt = $(cid+" ._afterplay").html();
        //warn("afterplay >",afterPlayTxt );
        //alert(afterPlayTxt);

        //@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
          },
          canvas: {backgroundColor: "#84CBFA"},
          plugins: {
             controls: {
                url:"/thirdparty/flowplayer/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
             }
          },
          version:[9,115],
          bufferLength:3,
          fadeInSpeed:1000,
          onBeforeLoad: function(){ },
          onLoad: function(){ warn("fp loaded"); this.setVolume(100); },
          onUnload: function(){ trackEvent("end", this.getClip()); },
          onFail:function(){},
          onError:function(){}

        };

        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;

      	$fp = flowplayer(this,"/thirdparty/flowplayer/flowplayer-3.1.5.swf",ini);
      	playerUnload = $fp.unload;
      	pObj.isModal = true;
        pObj.unloadMedia = playerUnload; //pass unload function ref to modal controls
        add_modal(pObj);
        $fp.play(0);

    });

  }

  $(".automedia").click(function(e){
      e.preventDefault();
      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"));
  });

  /***************************************************************************************************
  Beauty Tips
  ***************************************************************************************************/
  // Creates Beauty Tips for the site
  // There are 5 variants as follows:
  // 1 Requires FP Registration (You can only view the content assoc. w/ this icon if you are REG'd FP) - CG did this, others copy it's pattern.
  // 2 Requires Registration (You can only view content (assoc w/ text blurb "reguires reg" if you REG'd - either FP or Indiv.  Lower barrier to entry)
  // 3 Site For User Type   This is an information Tooltip as you mouse over Site For: text in Global page header
  //   There are two display variation (only text differs - FP or Indiv text) for this - Site For FP's tooltip and Site For Indiv's - matches what user mousesover in header
  // 4 Fund Tile  - If user hovers over a Fund Tile (e.g. Related Funds table in layout C page) then this shows same info as the "Fund In Focus sidebar module
  // 5 Resource  - If user hovers over a Resource link (e.g. a resource's link in Related Resource module) then the resouces desc shows in the bt.

  // *** Requires FP Registration Beauty Tip ***
    function do_bt(){
    var bt_timer;

    $('.premium-content-tooltip').bt({
      /*trigger:['hoverIntent'],*/
      postShow:function(box) {
        $(box).mouseleave(function() {
          $(this).hide();
        });
        $(box).mouseover(function() {
          clearTimeout(bt_timer);
        });

        $(this).mouseleave(function() {
          bt_timer = setTimeout(function() {
            $(box).hide();
          }, 500) // 500 gives a smooth transition without overlaying, or looking "jumpy" when mousing over multiple tips
        })
      },
      hideTip: function(box, callback) {    // this function must be here or the timeOut doesn't work.
        //alert(callback);
      },
      offsetParent:$('.main_back,body#blk'),     // setting offset to higher level container to fix ie6 beauty tip issue where bt was displaying underneath Top Nav Menu
      contentSelector:$('#static-premium-content'),
      positions:['top','left'],
      spikeLength:8,
      spikeGirth:12,
      windowMargin:20,
      strokeStyle:"#60e7f9",
      strokeWidth:1,
      fill:'#ecfaff',
      cornerRadius:3,
      padding:0,
      width:210,
      cssClass:'interactive-info-tip',
      closeWhenOthersOpen:true
    });

  // *** Requires Registration Beauty Tip ***
  $('.registration-required-tooltip').each(function() {
    var bt_timer;

    $(this).bt({
      /*trigger:['hoverIntent'],*/
      postShow:function(box) {
        $(box).mouseleave(function() {
          $(this).hide();
        });

        $(box).mouseover(function() {
          clearTimeout(bt_timer);
        });

        $(this).mouseleave(function() {
          bt_timer = setTimeout(function() {
            $(box).hide();
          }, 500) // 500 gives a smooth transition without overlaying, or looking "jumpy" when mousing over multiple tips
        })
      },
      hideTip: function(box, callback) {    // this function must be here or the timeOut doesn't work.
        //alert(callback);
      },
      offsetParent:$('.main_back,body#blk'),     // setting offset to higher level container to fix ie6 beauty tip issue where bt was displaying underneath Top Nav Menu
      contentSelector:$('.static-registration-required-content'),
      positions:['top','left'],
      spikeLength:8,
      spikeGirth:12,
      windowMargin:20,
      strokeStyle:"#60e7f9",
      strokeWidth:1,
      fill:'#ecfaff',
      cornerRadius:3,
      padding:0,
      width:210,
      cssClass:'interactive-info-tip',
      closeWhenOthersOpen:true});
  });

  // *** Site For User Type  Beauty Tip ***
  $('.site-for-usertype-content-tooltip').each(function() {
    var bt_timer;

    $(this).bt({
      /*trigger:['hoverIntent'],*/
      postShow:function(box) {
        $(box).mouseleave(function() {
          $(this).hide();
        });

        $(box).mouseover(function() {
          clearTimeout(bt_timer);
          $(this).show();
        });

        $(this).mouseleave(function() {
          bt_timer = setTimeout(function() {
            $(box).hide();
          }, 500) // 500 gives a smooth transition without overlaying, or looking "jumpy" when mousing over multiple tips
        })
      },
      hideTip: function(box, callback) {    // this function must be here or the timeOut doesn't work.
        //alert(callback);
      },
      offsetParent:$('.main_back,body#blk'),     // setting offset to higher level container to fix ie6 beauty tip issue where bt was displaying underneath Top Nav Menu
      contentSelector:$('#static-sitefor-content'),
      positions:['bottom'],
      spikeLength:8,
      spikeGirth:12,
      windowMargin:20,
      strokeStyle:"#60e7f9",
      strokeWidth:1,
      fill:'#ecfaff',
      cornerRadius:3,
      padding:0,
      width:210,
      cssClass:'interactive-info-tip',
      closeWhenOthersOpen:true
    });
  });

  // *** Fund Tile Beauty Tip ***
  $('.fundtile-content-tooltip').each(function() {
    var bt_timer;

    $(this).bt({
      postShow:function(box) {
        $(box).mouseleave(function() {
          $(this).hide();
        });
        $(box).mouseover(function() {
          clearTimeout(bt_timer);
        });

        $(this).mouseleave(function() {
          bt_timer = setTimeout(function() {
            $(box).hide();
          }, 100) // 100 gives a smooth transition without overlaying, or looking "jumpy" when mousing over multiple tips
        })
      },
      hideTip: function(box, callback) {    // this function must be here or the timeOut doesn't work.
        //alert(callback);
      },
      offsetParent:$('.main_back,body#blk'),     // setting offset to higher level container to fix ie6 beauty tip issue where bt was displaying underneath Top Nav Menu
      contentSelector:"$(this).children('.static-fundtile-content')", // content lives in child div
      positions:['left','top'],
      spikeLength:8,
      spikeGirth:12,
      windowMargin:20,
      strokeStyle:"#60e7f9",
      strokeWidth:1,
      fill:'#ecfaff',
      cornerRadius:3,
      padding:0,
      width:250, // set to 250 to accommodate pdf links
      cssClass:'interactive-info-tip',
      closeWhenOthersOpen:true});
  });

  // *** Resource Beauty Tip - to show desc of related resource when user mouses over title ***
  $('.resource-content-tooltip').mouseover(function() {
    var bt_timer;
    $(this).bt({
      postShow:function(box) {
        $(this).mouseout(function() {
            $(box).hide();
        })
      },
      hideTip: function(box, callback) {    // this function must be here or the timeOut doesn't work.
        //alert(callback);
      },
      offsetParent:$('.main_back,body#blk'),     // setting offset to higher level container to fix ie6 beauty tip issue where bt was displaying underneath Top Nav Menu
      contentSelector:"$(this).attr('title')",  // Get content from this span's title - where the resource desc. is parked
      positions:['top'],
      triggers:['none'],
      spikeLength:8,
      spikeGirth:12,
      windowMargin:20,
      strokeStyle:"#60e7f9",
      strokeWidth:1,
      fill:'#ecfaff',
      cornerRadius:3,
      padding:10,
      width:210,
      cssClass:'interactive-info-tip',
      closeWhenOthersOpen:true});
    $(this).btOn(); // Since this is a mouseover event, explicitly turn on the BeautyTip
  })
  .mouseout(function() {
    $(this).btOff();
  });
  }

   do_bt();
  /***************************************************************************************************
  End Beauty Tips
  ***************************************************************************************************/



  // *** 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() {
    named_popup(this.href,500,375,"Email a friend","y");
    return false;  // so that user's current page doesn't also go to the href they clicked
  });



  /***************************************************
   HomePage Tabs
  ***************************************************/

  //isHomePage is set by the server
  if(typeof isHomePage != "undefined" && isHomePage){

    // open the first panel
    //show($("#tab-panel-1"));

    var $hptabs = $(".hp .hd li");
     $hptabs.click(function(e){
        e.preventDefault();
        hide($hptabs);
        show($(this));
        var _ref = $("a",this).attr('href');
        var _panels = $(".tab-panel");
        var _panel =$(".tab-panel"+_ref);
        hide(_panels);
        show(_panel);
        return false;
     });
  }


  /***************************************************
  SNR Preview
  ***************************************************/
  /* Site Nav Redux preview link content */
  var snrContent = $('#simplified-navigation-main').html();  // grabs html for the main content area
  $(".snr-main-content").html(snrContent);  // populates the main content area with html
  $(".snr-preview-nav-item").hover(function(){  //main navigation function
    var currentId = $(this).attr("id");  // gets the id from the clicked nav item
    $(".snr-preview-nav-item").removeClass("active"); // resets all nav item backgrounds
    $(".snr-preview-nav-item").addClass("non-active");  // resets all nav item backgrounds
    $(this).addClass("active"); // adds active class to selected nav
    snrContent = $('#' + currentId + '-main').html();  // grabs html for the main content area specific to selected nav
    $(".snr-main-content").html(snrContent);   //populates the main content area with html specific to selected nav
  },function(){/* leave the 'mouseout' function blank */});

  //placed on bottom to delay call, do_qf_click  isnt defined in cases where QF is disabled
  if(typeof useQuickFinder != "undefined" && useQuickFinder){
    setTimeout("do_qf_click()", 1);
  }

});




  /***************************************************
  // 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']);
  }








