//reference variables
if (!window.siteTitle) {
  var refSiteTitle = "";   
} else {
  var refSiteTitle = siteTitle;
} 

var docTitle = document.title;
var currentURL = location.href;
if (currentURL.substring(currentURL.length-1) == "/")
{
  currentURL += "index.html"
}
var currentURI = currentURL.substring(currentURL.indexOf(".com/") + 4);

if (currentURI != "/index.html")
{
  document.title = refSiteTitle + " - " + docTitle;
}


var currentURL=new String(window.location);
var isIE=false;
jQuery.each(jQuery.browser, function(i, val) {
  if(i=="msie" && val==true)
  {
    isIE=true;
  }
});

jQuery.fn.log = function (msg) {
  if(!isIE)
  {
   // console.log("%s: %o", msg, this);
  }
  return this;
};
 
jQuery().ready(function(){

  //commented out code to put the site name in the top right of the masthead
  //jQuery("#mastHeadRightText").html(refSiteTitle);
    
  // add the site name to the title of the page (shown in the blue bar at the top)
  if(jQuery(".detailPageMiddleCol").length>0 && jQuery("title").length>0 && !jQuery(".noPageHeading").length>0)
  {
    var newTitle;
    newTitle=jQuery("title").html();
    jQuery(".detailPageMiddleCol").prepend("<h1>"+newTitle+"</h1>");
  }
  
  jQuery("#middle").prepend(jQuery("#rightCol"));
  
  //determine expanded state of left nav if applicable
  if(jQuery("#leftNav").length>0)
  {
    var foundOne=false;
    jQuery("#leftNav > ol > li").each(function(){
      if(!foundOne)
      {
        var baseURLArray=currentURL.split("/",7);
        if($("ol", this).length>0)
        {
          jQuery("ol > li > a", this).each(function(){
            var hrefArray=jQuery(this).attr("href").split("/",7);
            //djf - modified code for links not being fully qualified, added 2 to href length for checking
            if(baseURLArray.length == (hrefArray.length + 2))
            {
              var continueSearch=true;
              for (arrCtr=baseURLArray.length-1;arrCtr>2;arrCtr--)
              {
                //djf - modified code for links not being fully qualified, subtracted 2 from arrCtr to keep in sync
                if(baseURLArray[arrCtr]==hrefArray[arrCtr-2] && continueSearch)
                {
                  if(arrCtr==3)
                  {
                    //jQuery(this).log(baseURLArray[arrCtr] + " | " + hrefArray[arrCtr] + "\n\nfound match for : \n" + currentURL + "\n to be : \n" + jQuery(this).attr("href"));
                    jQuery(this).parent().addClass("selected");
                    jQuery(this).css("color","#0066cc");
                    foundOne=true;
                  }
                }
                else
                {
                  continueSearch=false;
                }
                
              }
            }
          });
        }
        else
        {
          var hrefArray=jQuery('a', this).attr("href").split("/",7);
          //djf - modified code for links not being fully qualified, added 2 to href length for checking
          if(baseURLArray.length == (hrefArray.length+2))
          {
            var continueSearch=true;
            for (arrCtr=baseURLArray.length-1;arrCtr>2;arrCtr--)
            {
              //djf - modified code for links not being fully qualified, subtracted 2 from arrCtr to keep in sync
              if(baseURLArray[arrCtr]==hrefArray[arrCtr-2] && continueSearch)
              {
                if(arrCtr==3)
                {
                  jQuery(this).addClass("selected");
                  jQuery('a', this).css("color","#FFFFFF");
                  foundOne=true;
                }
              }
              else
              {
                continueSearch=false;
              }
            }
          }
        }
        if(foundOne)
        {
          jQuery('ol', this).show();
          jQuery('div img', this).attr("src", "/images/navigation/leftNavSelectedArrow.gif");
          jQuery(this).css("background-color", "#A3A3A3");
          jQuery(this).css("color", "#FFFFFF");
        }
      }
    });
  }

  // show here else the video features text won't display
  jQuery("#rightCol, #middleCol, #bottom").show();

  jQuery(".feature").each(function(){
    if(jQuery('a', this).attr("href").indexOf("/video/")>-1)
    {
      jQuery(this).addClass("video");
      jQuery('a', this).hide();
      if(jQuery('.featureContent img', this).width()!=jQuery('.featureContent', this).width())
      {
        jQuery('.featureHeading, .featureSubHead', this).hide();
        setTimeout(resetVideoTextDivWidths, 1000);
      }
      jQuery('.featureHeading, .featureSubHead', this).width(jQuery('.featureContent', this).width());
    }
    else
    {
      jQuery('.featureContent', this).width(187);
    }
  });

	var now=new Date();
	var currYear=now.getFullYear();
  jQuery("#footerYear").html(currYear);

  //feature/promo borders
  /* features in the right hand side (including landingPageTopDiv) are not allowed to 
  have vertical lines (borders).  This is because the image is sized for 187 pixels
  which allows room for the 2 pixel border to the left of the image on the right side */
  jQuery("#landingPageTopDiv .featureVertBorder").remove();
  jQuery("#rightCol .featureVertBorder").remove();
  
  // left nav
  jQuery("#leftNav li li").bind("mouseenter",function(){
    jQuery('a', this).css("color", "#015FD3");
  }).bind("mouseleave",function(){
    if(jQuery(this).hasClass('selected'))
    {
      jQuery('a', this).css("color", "#0066cc");
    }
    else
    {
      jQuery('a', this).css("color", "#333333");
    }
  });

  jQuery("#leftNav > ol > li").bind("mouseenter",function(){
    if(jQuery('ol', this).length>0)
    {
      jQuery(this).css("background-color", "#A3A3A3");
      jQuery(this).css("color", "#FFFFFF");
    }
    else
    {
      jQuery(this).css("background-color", "#A3A3A3");
      jQuery('a', this).css("color", "#FFFFFF");
    }
  }).bind("mouseleave",function(){
    if(jQuery('ol', this).length>0)
    {
      if(!(jQuery('ol', this).css("display").indexOf("block")>-1))
      {
        jQuery(this).css("background-color", "#D9D9D9");
        jQuery(this).css("color", "#333333");
      }
    }
    else
    {
      if(jQuery(this).hasClass('selected'))
      {
        jQuery(this).css("background-color", "#A3A3A3");
        jQuery('a', this).css("color", "#FFFFFF");
      }
      else
      {
        jQuery(this).css("background-color", "#D9D9D9");
        jQuery(this).css("color", "#333333");
        jQuery('a', this).css("color", "#333333");
      }
    }
  });

  jQuery("#leftNav a").click(function(event){
    // based on testing, it appears that the "a" tag will fire successfully and then stop any processing for the click, which keeps the "li" click from happening
    //alert ("stopping 'a'");
    event.stopPropagation();
  });
  jQuery("#leftNav ol li ol li").click(function(event){
    //second level LeftNav link.  The event.stopPropagation(); keeps the leftNav open if the second level has been expanded.
    //alert ("second level li click");
    var newWindow = jQuery('a', this).attr("target");
    if (newWindow == "_blank") {
      window.open(jQuery('a', this).attr("href"));
    } else {
      window.location=jQuery('a', this).attr("href");
    }
    event.stopPropagation();
	});

  jQuery("#leftNav > ol li").click(function(event){
		if(jQuery('ol', this).length>0)
		{
			if(jQuery('ol', this).css("display")=="none")
			{
        jQuery("#leftNav ol ol").each(function(){
          if(jQuery(this).css("display")=="block")
          {
            jQuery(this).slideUp(300);
            jQuery('div img', jQuery(this).parent()).attr("src", "/images/navigation/leftNavNotSelectedArrow.gif");
            jQuery(this).parent().css("background-color", "#D9D9D9");
            jQuery(this).parent().css("color", "#333333");
          }
        })
        jQuery('ol', this).slideDown(300, function(){
            var borderTop=jQuery('li:eq(0)', this).css("border-top-width");
            borderTop=borderTop.substring(0,borderTop.indexOf("px"));
            var paddingTop=jQuery('li:eq(0)', this).css("padding-top");
            paddingTop=paddingTop.substring(0,paddingTop.indexOf("px"));
            var height=jQuery('li:eq(0)', this).height();
            var adjustedHeight=height*1+paddingTop*1+borderTop*1;
          jQuery(this).css("height", (adjustedHeight*(jQuery('li', this).length))+"px");
        });
        jQuery('div img', jQuery(this)).attr("src", "/images/navigation/leftNavSelectedArrow.gif");
        jQuery('a', this).css("color", "#333333");
      }
			else
			{
				jQuery('ol', this).slideUp(300);
        jQuery('div img', jQuery(this)).attr("src", "/images/navigation/leftNavNotSelectedArrow.gif");
			}
		}
		else
		{
      //first level LeftNav link.  The event.stopPropagation(); keeps the leftNav open if the second level has been expanded.
      //alert ("first level li click");
      var newWindow = jQuery('a', this).attr("target");
      if (newWindow == "_blank") {
        window.open(jQuery('a', this).attr("href"));
      } else {
        window.location=jQuery('a', this).attr("href");
      }
      event.stopPropagation();
		}
	});

  // features
  jQuery(".feature a, .investorHighlight a").click(function(e){
    e.stopPropagation();
  });
  jQuery(".feature, .investorHighlight").click(function(e){
    if(!jQuery(this).hasClass("video"))
    {
      if(jQuery('a', this).attr("target")=="_blank")
      {
        window.open(jQuery('a', this).attr("href"));
      }
      else
      {
        window.location=jQuery('a', this).attr("href");
      }
      e.stopPropagation();
    }
  });

  jQuery(".feature").mouseover(function(){
    jQuery(".promoLink a, .businessLandingPageSubNavText a", this).css("color", "#0066cc");
    jQuery(".promoLink", this).css("background", "url('/images/navigation/blueArrow.gif') no-repeat right 1px");
  });

  jQuery(".feature").mouseout(function(){
    jQuery(".promoLink a, .businessLandingPageSubNavText a", this).css("color", "#333333");
    jQuery(".promoLink", this).css("background", "url('/images/navigation/leftNavNotSelectedArrow.gif') no-repeat right 1px");
  });

  // investor highlights
  jQuery(".investorHighlight").click(function(event){
    window.location=jQuery('a', this).attr("href");
    event.stopPropagation();
  });

  jQuery(".investorHighlight").mouseover(function(){
    jQuery('a', this).css("color", "#0066cc");
  });

  jQuery(".investorHighlight").mouseout(function(){
    jQuery('a', this).css("color", "#333333");
  });

  //connections
  jQuery("#connectionsPrime").mouseover(function(){
    jQuery("a", this).css("color", "#0066cc");
    if(jQuery(this).hasClass("businessConnections"))
    {
      jQuery(".connectionsPrimeLink", this).css("background", "url('/images/navigation/blueArrow.gif') no-repeat 166px 3px #b2cc99");
    }
    if(jQuery(this).hasClass("residentialConnections"))
    {
      jQuery(".connectionsPrimeLink", this).css("background", "url('/images/navigation/blueArrow.gif') no-repeat 166px 3px #99CCe5");
    }
  });

  jQuery("#connectionsPrime").mouseout(function(){
    jQuery("a", this).css("color", "#333333");
    if(jQuery(this).hasClass("businessConnections"))
    {
      jQuery(".connectionsPrimeLink", this).css("background", "url('/images/navigation/leftNavNotSelectedArrow.gif') no-repeat 166px 3px #b2cc99");
    }
    if(jQuery(this).hasClass("residentialConnections"))
    {
      jQuery(".connectionsPrimeLink", this).css("background", "url('/images/navigation/leftNavNotSelectedArrow.gif') no-repeat 166px 3px #99CCe5");
    }
  });

  jQuery("#connectionsPrime").click(function(){
    window.location=jQuery('a', this).attr("href");
  });

  jQuery(".video").click(function(event){
    var veilFadeInOutSpeedMillis=800;
    jQuery("#middle").append("<div class='veil'></div>");
    jQuery(".veil").css("opacity", "0.6");
    jQuery(".veil").css("filter", "alpha(opacity=60)");
    jQuery(".veil").css("position", "absolute");
    jQuery(".veil").css("width", "756px");
    jQuery(".veil").css("height", jQuery("#middleCol").height());
    jQuery(".veil").css("left", jQuery("#middleCol").offset().left + "px");
    jQuery(".veil").css("top", jQuery("#middleCol").offset().top + "px");
    jQuery(".veil").fadeIn(veilFadeInOutSpeedMillis);
    var box=Boxy.load(jQuery('a', this).attr("href"), 
      {title: jQuery('.featureHeading', this).html(), draggable: false, afterShow: function(){positionVideo()}, afterHide: function(){
        jQuery(".veil").fadeOut(veilFadeInOutSpeedMillis, function(){jQuery(".boxy-wrapper").remove();jQuery(".veil").remove();});
      }
    });
  });

  jQuery(".featureRightVertLine").prepend("<div class='featureRightBorder'></div>");
  jQuery(".featureLeftVertLine").prepend("<div class='featureLeftBorder'></div>");

});

function resetVideoTextDivWidths()
{
  if(jQuery('.featureContent img', this).width()!=jQuery('.featureContent', this).width())
  {
    setTimeout(resetVideoTextDivWidths, 1000);
  }
  else
  {
    jQuery(".feature").each(function(){
      if(jQuery('a', this).attr("href").indexOf("/video/")>-1)
      {
        jQuery('.featureHeading, .featureSubHead', this).show();
        jQuery('.featureHeading, .featureSubHead', this).width(jQuery('.featureContent', this).width());
      }
    });
  }
}

function resetColumnHeights()
{
/*  removed  */
}

//top Navigation Tab functions
// set State for Tabs / buttons  (three states are Up, Over, Down)
function changeTab(section,state){
  var testSource = document.getElementById(section).src;
  if (testSource.indexOf("btnDown") < 0) {
    document.getElementById(section).src = "/images/navigation/" + section + "_btn" + state + ".jpg";
  }
}

function changeButton(section,state){
  if(section.indexOf('@')>-1)
  {
    document.getElementById(section).src = "/images/buttons/" + section.substring(0,section.indexOf('@')) + state + ".jpg";
  }
  else
  {
    document.getElementById(section).src = "/images/buttons/" + section + state + ".jpg";
  }
}

var disappeardelay=500;
function delayHideSubMenu(){
 delayhide=setTimeout("hideSubMenu()",disappeardelay)
};

function clearHideSubMenu(){
  if (typeof delayhide!="undefined")
  clearTimeout(delayhide)
};

function hideSubMenu(){
  jQuery("#subArea").animate({height: "0px", marginLeft: "567px", top:"48px", width: "0px"}, 500);
  changeButton('allSitesArea','Up');
};

function show(item) {
  document.getElementById(item).style.display = "block";
}

function hide(item) {
  document.getElementById(item).style.display = "none";
}

function toggle(item) {
  if (document.getElementById(item).style.display == "block") {
    document.getElementById(item).style.display = "none";
    if (item == "subList") {
      changeButton('allSitesArea','Up');
    }
  } else {
    document.getElementById(item).style.display = "block";
    if (item == "subList") {
      changeButton('allSitesArea','Down');
    }
  }
}

function toggleSubList() {
  if(jQuery("#subArea").height()=="0")
  {
    setSubListHeight();
    document.getElementById("subArea").style.left = (document.getElementById("mainCenteringWrapper").offsetLeft + jQuery("#subArea").width() + 189) + "px";
    // move to top and left position calculations
    var leftPosition = (document.getElementById("mainCenteringWrapper").offsetLeft + 189) + "px";
    var topPosition = "1px";
    jQuery("#subArea").animate({height: "145px", marginLeft: "0px", top:"0px", width: "567px"}, 500);
  }
  else
  {
    hideSubMenu()
  }
}

function setSubListHeight() {
  jQuery("#subList").height(Math.max(document.getElementById("affiliatesBox").offsetHeight, document.getElementById("specialInterestBox").offsetHeight));
}

function positionVideo() {
  jQuery(".boxy-wrapper").hide();
  var leftOffset=0;
  if(jQuery("#rightCol").length>0)
  {
    leftOffset=(jQuery("#middleCol").offset().left+jQuery("#middleCol").width()/2+jQuery("#rightCol").width()/2)-((jQuery(".boxy-wrapper").width())/2);
  }
  else
  {
    leftOffset=jQuery("#middleCol").offset().left+(jQuery("#middleCol").width()/2)-((jQuery(".boxy-wrapper").width())/2);
  }
  var topOffset=jQuery("#middleCol").offset().top+20;
  jQuery(".boxy-wrapper").css("left", leftOffset+"px");
  jQuery(".boxy-wrapper").css("top", topOffset+"px");
  jQuery(".boxy-wrapper").fadeIn(500);
}

function readCookie(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 c.substring(nameEQ.length,c.length);
	}
	return null;
}

//  function used by the FAQ, didn't rename it because would require a template change as well.
function toggleItem(question, answer) {
  if (document.getElementById(answer).style.display == "none") {
    document.getElementById(answer).style.display = "block";
  } else {
    document.getElementById(answer).style.display = "none";
  }
  
  if (document.getElementById(question).getElementsByTagName("span")[0].innerHTML == "+&nbsp;&nbsp;") {
    document.getElementById(question).getElementsByTagName("span")[0].innerHTML = "-&nbsp;&nbsp;";
  } else {
    document.getElementById(question).getElementsByTagName("span")[0].innerHTML = "+&nbsp;&nbsp;";
  }
  
  resetColumnHeights();

}

/*  Printer Friendly functions */
function setPrinterFriendly() {
  jQuery("#top").hide();
  jQuery("#leftCol").hide();
  jQuery("#rightCol").hide();
  jQuery("#bottom").hide();
  jQuery("#printerFriendly").hide();
  jQuery("#webView").show();
}

function setNormal() {
  jQuery("#top").show();
  jQuery("#leftCol").show();
  jQuery("#rightCol").show();
  jQuery("#bottom").show();
  jQuery("#printerFriendly").show();
  jQuery("#webView").hide();
}

function addCommas(nStr) {
  nStr += '';
  x = nStr.split('.');
  x1 = x[0];
  x2 = x.length > 1 ? '.' + x[1] : '';
  var rgx = /(\d+)(\d{3})/;
  while (rgx.test(x1)) {
    x1 = x1.replace(rgx, '$1' + ',' + '$2');
  }
  return x1 + x2;
}  

function getArgs(){
   var args = new Object();
   var query = location.search.substring(1);
   var pairs = query.split("&");
   for (var i=0; i<pairs.length; i++){
      var pos = pairs[i].indexOf('=');
	  if (pos == -1) continue;
	  var argname = pairs[i].substring(0,pos);
	  var value=pairs[i].substring(pos+1);
	  args[argname]=unescape(value);
   }
   return args;
}

// used to show Boxy page
function showBoxy(boxyTitle,pagePathFile) {
  var tempBox = Boxy.load(pagePathFile, {
    title: boxyTitle, 
    draggable: false, 
    modal: true
  });
}

