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;
};
 
var cookieName = "zipcodeCheck";
var cookieData = new Array();
var cookieZip = "";
var cookieTerritory = "";
var cookieParms = "";
var cookieFound = false;
var territoryPath = "";

checkCookie();

jQuery().ready(function(){

  // special code for development only
  jQuery("#resetZip").click(function(event){
    clearCookie(cookieName);
    location.reload(true);
  });


  // if cookie was found, put the zipcode in the bodyZipCode span area (if it's on the page)
  if (cookieFound) 
  {
    jQuery("#bodyZipCode").html(cookieZip);
  }
    
  // hide content if it's not supposed to be visible
  // 0,1  HotWaterTank      (Product / Service)       
  // 1,2  ApplianceRepair   (Appliance Repair) 
  // 2,3  Plumbing          (Plumbing Protection) 
  // 3,4  DuctCleaning      (Product / Service)
  // 4,5  Gas Line Protect  (Product / Service)
  
  // hot water tank
  if (cookieParms.substring(0,1) == "n")
  {
    jQuery("#tblHWT").remove();
    if (jQuery("#divHWT").size() > 0)
    {
      jQuery("#divHWT").remove();
      jQuery("#leftCol").remove();
      jQuery("#rightCol").remove();
      jQuery("#divNotAvailable").show();
    }
  }
    
  // appliance repair services
  if (cookieParms.substring(1,2) == "n")  
  {
    jQuery("#tblARS").remove();
    if (jQuery("#divARS").size() > 0)
    {
      jQuery("#divARS").remove();
      jQuery("#leftCol").remove();
      jQuery("#rightCol").remove();
      jQuery("#divNotAvailable").show();
    }
  }
  
  // plumbing protection services
  if (cookieParms.substring(2,3) == "n")
  {
    jQuery("#tblPPP").remove();
    if (jQuery("#divPPP").size() > 0)
    {
      jQuery("#divPPP").remove();
      jQuery("#leftCol").remove();
      jQuery("#rightCol").remove();
      jQuery("#divNotAvailable").show();
    }
  }
  
  // Duct Cleaning
  if (cookieParms.substring(3,4) == "n")
  {
    jQuery("#tblDuct").remove();
    if (jQuery("#divDuct").size() > 0)
    {
      jQuery("#divDuct").remove();
      jQuery("#leftCol").remove();
      jQuery("#rightCol").remove();
      jQuery("#divNotAvailable").show();
    }
  }
  
  // Gas Line Protection
  if (cookieParms.substring(4,5) == "n")
  {
    jQuery("#tblGasLine").remove();
    if (jQuery("#divGasLine").size() > 0)
    {
      jQuery("#divGasLine").remove();
      jQuery("#leftCol").remove();
      jQuery("#rightCol").remove();
      jQuery("#divNotAvailable").show();
    }
  }
  
  // products / services
  if ((cookieParms.substring(0,1) == "n") && (cookieParms.substring(3,4) == "n") && (cookieParms.substring(4,5) == "n"))
  {
    if (jQuery("#divProdServices").size() > 0)
    {
      jQuery("#divProdServices").remove();
      jQuery("#leftCol").remove();
      jQuery("#rightCol").remove();
      jQuery("#divNotAvailable").show();
    }
  }

  // stripe the data table, if there is one on the page
  stripeTable(jQuery("#whatsAvailable"));
  

  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>");
  }
  
  //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);
    }
  });
  
  // add video class to homeFeature if pointing to /video/ directory
  jQuery(".homeFeature").each(function(){
    if(jQuery('a', this).attr("href").indexOf("/video/")>-1)
    {
      jQuery(this).addClass("video");
    }
  });    

	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, .homeFeatureBox a").click(function(e){
    e.stopPropagation();
  });
  jQuery(".feature, .homeFeatureBox").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();
    }
  });

  // mouse over of features
  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");
  });

  // mouse over of homeFeatures
  jQuery(".homeFeatureBox").mouseover(function(){
    jQuery(this).addClass("homeFeatureHover");
    jQuery("#homeFeatureArrow", this).attr("src","/images/navigation/blueArrow.gif");
  });

  jQuery(".homeFeatureBox").mouseout(function(){
    jQuery(this).removeClass("homeFeatureHover");
    jQuery("#homeFeatureArrow", this).attr("src","/images/navigation/leftNavNotSelectedArrow.gif");
  });

  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, .homeFeatureHeading', 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>");

  /*  set table to have a colored top row, then alternating gray/white rows */
  jQuery("table.zebra").each(function(){
    //console.log(jQuery(this));
    jQuery(this).addClass("color");
    jQuery("tr:even", this).addClass("white");
    jQuery("tr:odd", this).addClass("gray");
    jQuery("tr:first", this).addClass("color").removeClass("white");
    jQuery("tr:first td", this).each(function(){
      jQuery("td", this).addClass("white");
    });
  });

});

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,passedCookieParms){
  jQuery.cookie(passedCookieName, zipcode+"|"+serviceterritory+"|"+passedCookieParms, { path: "/" });
}

function checkCookie() {
  //alert ("cookieName=" + cookieName);
  if (readCookie(cookieName))
  {
    cookieData = readCookie(cookieName);
    cookieZip  = cookieData[0];
    cookieTerritory = cookieData[1];
    cookieParms = cookieData[2];
    cookieFound = true;  
  }
}

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
  });
}

// used to stripe the table rows
function stripeTable(table) {
  jQuery("tr:odd", table).addClass("gray").removeClass("white");
  jQuery("tr:even", table).addClass("white").removeClass("gray");
}


