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(){
    
  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);
            if(baseURLArray.length == hrefArray.length)
            {
              var continueSearch=true;
              for (arrCtr=baseURLArray.length-1;arrCtr>2;arrCtr--)
              {
                if(baseURLArray[arrCtr]==hrefArray[arrCtr] && 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","#51739b");
                    foundOne=true;
                  }
                }
                else
                {
                  continueSearch=false;
                }
              }
            }
          });
        }
        else
        {
          var hrefArray=jQuery('a', this).attr("href").split("/",7);
          if(baseURLArray.length == hrefArray.length)
          {
            var continueSearch=true;
            for (arrCtr=baseURLArray.length-1;arrCtr>2;arrCtr--)
            {
              if(baseURLArray[arrCtr]==hrefArray[arrCtr] && 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", dteenergySitePrefix+"/images/navigation/leftNavSelectedArrow.gif");
          jQuery(this).css("background-color", "#51739b");
          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
  //set greenbacks background to green with white letters
  $("#leftNav ol li").each(function () {
    if (jQuery('a', this).attr('href').indexOf("greenback") > 0)
    {
      //alert ("Found it " + jQuery('a', this).attr('href') );
      /* commented out per Dani/Tony 9/24/09
      if(!jQuery(this).hasClass('selected'))
      {
        jQuery(this).css("background-color", "#669933");
        jQuery(this).css("color", "#ffffff");
        jQuery('a', this).css("color", "#ffffff");
      }
      */
    }
  });

  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", "#51739b");
      jQuery(this).css("color", "#FFFFFF");
    }
    else
    {
      jQuery(this).css("background-color", "#51739b");
      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", "#b2cbef");
        jQuery(this).css("color", "#333333");
      }
    }
    else
    {
      if(jQuery(this).hasClass('selected'))
      {
        jQuery(this).css("background-color", "#51739b");
        jQuery('a', this).css("color", "#FFFFFF");
      }
      else
      {
        /* commented out per Dani / Tony  9/24/09
        if (jQuery('a', this).attr('href').indexOf("greenback") > 0)
        {
          //alert ("Found GreenBacks " + jQuery('a', this).attr('href') );
          jQuery(this).css("background-color", "#669933");
          jQuery(this).css("color", "#ffffff");
          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(this).css("background-color", "#b2cbef");
        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", dteenergySitePrefix+"/images/navigation/leftNavNotSelectedArrow.gif");
            jQuery(this).parent().css("background-color", "#b2cbef");
            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", dteenergySitePrefix+"/images/navigation/leftNavSelectedArrow.gif");
        jQuery('a', this).css("color", "#333333");
      }
			else
			{
				jQuery('ol', this).slideUp(300);
        jQuery('div img', jQuery(this)).attr("src", dteenergySitePrefix+"/images/navigation/leftNavNotSelectedArrow.gif");
        jQuery(this).parent().css("background-color", "#b2cbef");
			}
		}
		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").click(function(e){
    e.stopPropagation();
  });
  jQuery(".feature").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 checkElement = document.getElementById(section);
  if (checkElement)
  {
    var testSource = checkElement.src;
    if (testSource.indexOf("btnDown") < 0) {
      document.getElementById(section).src = hppSitePrefix+"/images/navigation/" + section + "_btn" + state + ".jpg";
    }
  }
}

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

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";
  }
}

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);
}

//setcookie
function setCookie(passedCookieName,zipcode,serviceterritory,hotwatertank){
  jQuery.cookie(passedCookieName, zipcode+"|"+serviceterritory+"|"+hotwatertank, { path: "/" });
}

function readCookie(passedCookieName){
  if (jQuery.cookie(passedCookieName)!= null) 
  {
    var cookieInfo = jQuery.cookie(passedCookieName).split("|");
    if (cookieInfo[0].length > 0) 
    {
      return cookieInfo;
    }
    else
    {
      return null;
    }
  }
  else
  {
    return null;
  }
}

function clearCookie (passedCookieName) {
  var date = new Date();
  date.setTime(date.getTime() - 10000);
  jQuery.cookie(passedCookieName, null, { path: '/', expires: date });
}

//  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;
}

//function used by Appliance Protection Plans page to swap the house images on rollover
function SwapImage(sImgID, sImageName) {
  //alert("Switch " + sImgID + " to " + sImageName);
  document.getElementById(sImgID).setAttribute("src", "/images/" + sImageName);
}

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