$(function(){

     // build the home hero pagination
     buildHeroPagination();
     
     // start the home hero loop
     startHomeHeroLoop();

     // insert the print action in the page
     insertPrintAction();

     // insert the back link on tag-listing pages
     insertBackLink();

	// binds
	$('.news a').bind('click', clickHomeTab);
	$('.stock a').bind('click', clickHomeTab);
     $("#page-content table").not("#account_table").not(".no-style").find("tr").hover(hoverTableRowIn, hoverTableRowOut);

     // run the green connect form validation
     validateGreenConnect();

     // run the email DPL form validation
     validateEmailDPL();

     // setup the pay-agent-locator
     initPayAgentLocator();

     // setup the residential hvac contractor finder
     initHvacContractorFinder();
     
     // setup the project help page
     initProjectHelp();
     
     // set the focus if there is an input with the "first-focus" class
     setFirstFocus();
     
     // replace "captcha" with "spam protection" in the form error messages
     replaceCaptcha();
     
     // load the custom video player for the homepage
     loadCustomVideoPlayer();
});


// builds the homepage hero nav based on the pages in the DOM
function buildHeroPagination() {
     // for counting the pages
     var i = 1;

     // loop through each ".hero-page" in the DOM
     $(".home #hero .section1 .hero-page").each(function() {
          // get the title of this ".hero-page"
          var myTitle = $(this).find(".hero-title").text();
          
          // get the page number of this .hero-page
          var myId = $(this).attr("id").split("-")[1];

          // add a <li> to the .pagination
          $(".home #hero .section1 ol.pagination").append('<li><a title="' + myTitle + '" id="link-' + myId + '">' + myTitle + '</a></li>');

          // if this is the first item, we need to add the "on" class
          if (i==1) {
               $("#link-" + myId).parent().addClass("on");
          }
          
          // bind each link to the clickHeroPagination function
          $("#link-" + myId).bind("click", clickHeroPagination);
          $("#link-" + myId).bind("mousedown", mousedownHeroPagination);

          // increment i
          i++;
     });
     
     // if there's only 1
     if ($(".home #hero .pagination li").length > 1) {
          // show the pagination
          $(".home #hero .pagination").css("display", "block");
     } else {
          // remove the pagination
          $(".home #hero .pagination").remove();
     }
}

// shows the next hero image on the homepage
function showNextHomeHero() {
     // if there is a <li> after the <li> with a class of "on"
     if ($(".pagination .on").next().length) {
          // click the next one
          $(".pagination .on").next().find("a").click();
     } else {
          // otherwise, click the first one
          $(".pagination li").first().find("a").click();
     }
}


// starts the looping of the home hero section
function startHomeHeroLoop() {
     //if we're on the home page and we have a pagination
     if ($(".home .pagination").length) {
          // create a global interval to call "showNextHomeHero"
          window.heroInterval = setInterval(showNextHomeHero, 8000);
     }
}

// called when the user clicks the home hero pagination
function mousedownHeroPagination(e) {
     // stop the home hero looping
     clearInterval(window.heroInterval);

     // unbind the call to this function
     $(".pagination a").unbind("mousedown");
}

// called when the user clicks the pagination in the home hero section
function clickHeroPagination(e) {
     // count the number of <li>s in the home hero pagination
     var numPages = $(".home #hero .section1 .pagination li").length;

     // build the current page number based on the .pagination li with the "on" class
     var currPage = $(".home #hero .section1 .pagination li.on a").attr("id").split("-")[1];

     // build the next page number based on which a they clicked
     var nextPage = $(this).attr("id").split("-")[1];
     
     // if the next page isn't the current page
     if (nextPage != currPage) {
          // fade out the current page
          $(".home #hero .section1 #page-" + currPage).fadeOut("fast", function() {
               //once the current page is done fading out, fade the next one in
               $(".home #hero .section1 #page-" + nextPage).fadeIn("fast");
               
               // remove the "on" class from the current page
               $(".home #hero .section1 .pagination li a#link-" + currPage).parent().removeClass("on");

               // add the "on" class to the next page
               $(".home #hero .section1 .pagination li a#link-" + nextPage).parent().addClass("on");
          });
     }
}


function clickHomeTab(e) {
     // prevent the refresh from firing
     e.preventDefault();

     // get my name based on my id
     var myName = $(this).attr("id").split("-")[0];
     
     // fade out all the tab-areas
     $(".tab-area:visible").fadeOut("fast", function() {
          $(".tab-nav-item").removeClass("current");
          $(".tab-area").removeClass("on");
          
          // $("#" + myName + "-tab").hide();
          $("#" + myName + "-tab").addClass("current");

          $("#" + myName + "-articles").hide();
          $("#" + myName + "-articles").addClass("on");
          
          // $("#" + myName + "-tab").fadeIn("fast");
          $("#" + myName + "-articles").slideDown("fast");
     });
}


// called when the user hovers a table row in the #page-content
function hoverTableRowIn(e) {
     window.tableCellBG = $(this).find("td").css("background-color");
     window.tableCellCol = $(this).find("td").css("color");

     $(this).find("td").css("background-color", "#ddd");
     $(this).find("td").css("color", "#000");
}

// called when the user unhovers a table row in the #page-content
function hoverTableRowOut(e) {
//     $(this).find("td").attr("style", "");
     $(this).find("td").css("background-color", window.tableCellBG);
     $(this).find("td").css("color", window.tableCellCol);
}


// inserts the "print this page" action
function insertPrintAction() {
     // if the action links are present
     if (($(".action-links").length) && ($(".no-print").length == 0)) {
          // append the print link to the end
          $(".action-links").first().find("ul").append('<li><a id="print-page" title="Print" class="print" href="#">Print</a></li>');

          // bind the click of this link
          $("#print-page").bind("click", printPage);
     }
}


// print the page
function printPage(e) {
     window.print();
}

// insert a link to go back on the tag-listing pages
function insertBackLink() {
     // if the holder is there
     if ($(".js-back").length) {
          // stick the link in
          $(".js-back").append('<a href="#" title="go back">Go Back</a>');
          
          // bind the click of this link
          $(".js-back a").bind("click", goBack);
     }
}

// go back in history
function goBack(e) {
     // prevent the refresh from firing
     e.preventDefault();
     
     // go back in the history
     history.back();
}


//
function blurGreenPricingBlocks(e) {
     var numBlocks = parseInt($("#green_pricing_blocks").val());

     $("span#block-error").remove();
     
     if ((numBlocks) && (numBlocks >= 2)) {
          $("#green_pricing_blocks").val(numBlocks);
     } else {
          $("#green_pricing_blocks").val("2");
          $("#green_pricing_calculation").after('<span id="block-error" class="first error">The minimum value for this field is 2.</span>')
     }
     
     $("#green_pricing_calculation").val("$" + parseInt($("#green_pricing_blocks").val()).toFixed(2));
}


// 
function validateGreenConnect() {
     // if this page has the green connect form on it...
     if ($("#green-connect-form").length) {
          // bind the blur of the #green_pricing_blocks input
          $("#green_pricing_blocks").bind("blur", blurGreenPricingBlocks);
     }
}


//
function blurVerify(e) {
     var idRoot = $(this).attr("id").split("_")[0];
     var val1 = $("#" + idRoot + "_verify1").val();
     var val2 = $("#" + idRoot + "_verify2").val();
     
     $("#" + idRoot + "_verify1").css("background-color", "#fff");
     $("#" + idRoot + "_verify2").css("background-color", "#fff");
     
     // if ((val1 != "") && (val2 != "")) {
          if (val1 != val2) {
               $("#" + idRoot + "_verify1").css("background-color", "#fcc");
               $("#" + idRoot + "_verify2").css("background-color", "#fcc");
          }
     // }
}


//
function validateEmailDPL() {
     // if this page has the email dpl form on it...
     if ($("#email-dpl-form").length) {
          // bind the blur of any "verify"
          $("#email-dpl-form .verify").bind("blur", blurVerify);
     }
}


// clears the input filter on the pay-agent-locator
function clickClearFilter(e) {
     // clear the input
     $("input.filter-input").val("");

     // trigger the keyup event
     keyupFilter();

     // put focus back on the input
     $("input.filter-input").focus();
}


// runs when the keyboard key is released on the 
function keyupFilter(e) {
     var theValue = $("input.filter-input").val().toUpperCase();
     
     if (theValue.length > 0) {
          $("#assets #clear-filter").fadeIn("slow");
     } else {
          $("#assets #clear-filter").fadeOut("slow");
     }
     
     // hide all the assets
     $("#assets .asset").hide();

     // loop through each asset, show all the ones that match
     $("#assets .asset").each(function() {
          if ($(this).find(".search-text").text().toUpperCase().indexOf(theValue) > -1) {
               $(this).show();
          }
     });
     
     // hide all the asset titles
     $("#assets .asset-title").hide();
     
     // loop throuh the asset-titles, show all the ones that have visible assets
     $("#assets .asset-title").each(function() {
          if ($("." + $(this).attr("title") + ":visible").length > 0) {
               $(this).show();
          }
     });
     
     // calculate the number of visible assets, update the results string
     $("#results").text("showing " + $(".asset:visible").length + " result(s)");
}


// initialize the pay agent locator JS
function initPayAgentLocator() {
     // if this is the payment-options page
     if ($("#zip-image-link").length) {
          // hide the image link
          $("#zip-image-link").hide();

          // show the form
          $(".zip-searcher").show();
     }
     
     // if this page has the pay-agent-locator
     if ($("#assets.pay-agent").length) {
          // add the filter markup to the DOM (inside #asset-filters)
          $("#asset-filters").append('<fieldset class="w-1"><p class="w-1 first"><label for="zip" class="w-13">Enter Zip or City:</label><input type="text" id="zip" name="zip" class="w-14 filter-input" /><span id="clear-filter">clear</span><span id="results"></span></p></fieldset>');
          
          // bind the keypresses on the zip code input
          $("input.filter-input").bind("keyup", keyupFilter);
          $("#clear-filter").bind("click", clickClearFilter);

          // check for URL variable "zip", populate input with it
          var urlVar = parseInt(window.location.href.split("?zip=")[1]);
          if (urlVar) {
               $("input.filter-input").val(urlVar);
          }

          // run the filter
          keyupFilter();
          
          // focus on the input
          $("input.filter-input").focus();
     }
}


//
function initHvacContractorFinder() {
     if (($("#assets.find-contractors").length) || ($("#assets.find-contractors-tune-up").length)) {
          $("#asset-filters").append('<fieldset class="w-1"><p class="w-1 first"><label for="county" class="w-13">Enter County:</label><input type="text" id="county" name="county" class="w-14 filter-input" tabindex="0" /><span id="clear-filter">clear</span><span id="results"></span></p></fieldset>');
          
          $("input#county").bind("keyup", keyupFilter);
          $("#clear-filter").bind("click", clickClearFilter);

          // check for URL variable "county", populate input with it
          var urlVar = window.location.href.split("?county=")[1];
          if (urlVar) {
               $("input.filter-input").val(urlVar);
          }
          
          // run the filter
          keyupFilter();
          
          // focus on the input
          $("input.filter-input").focus();
     }
}


//
function clickProjectHelpCheckbox(e) {
     $("#assets .asset").hide();

     var classList = ".asset";
     $("#asset-filters .check-project-help").each(function() {
          if ($(this).attr("checked")) {
               classList += "." + $(this).val();
          }
     });
     
     $(classList).show();
     
     // calculate the number of visible assets, update the results string
     $("#results").text("showing " + $(".asset:visible").length + " result(s)");
}

//
function initProjectHelp() {
     if ($("#assets.project-help").length) {
          $("#assets.project-help #asset-filters").show();
          
          $("#asset-filters .check-project-help").bind("click", clickProjectHelpCheckbox);

          clickProjectHelpCheckbox();
     }
}

// if there is an element with the "first-focus" class on the page, focus on it
function setFirstFocus () {
     if ($(".first-focus").length) {
          $(".first-focus").first().focus();
     }
}

function replaceCaptcha () {
     if ($(".user-message li").length) {
          $(".user-message li").each(function() {
               if ($(this).text().indexOf("captcha") > -1) {
                    $(this).text($(this).text().replace("captcha", "spam protection"));
               }
          });
     }
}


// load the custom video player
function loadCustomVideoPlayer() {
     // if there's a video
     if ($(".youtube-video").length) {

          // loop through each instance of the "youtube-video" class
          $(".youtube-video").each(function() {
               
               var videoWidth = 270;
               if ($("body.subpage").length) {
                    videoWidth = 540;
               }
               
               // parse the youtube id out of the 
               // var videoID = $(this).find("object").attr("id");
               var videoID = $(this).find("object param[name='movie']").attr("value").replace(/^.+\/v\/(.+)$/i, "$1");

               // call the youTubeEmbed function to do the embed
               $(this).youTubeEmbed({
                    video          : 'http://www.youtube.com/watch?v=' + videoID,
                    width          : videoWidth,         // Height is calculated automatically
                    progressBar    : true         // Show the progress bar
               });
          });
     }
}



// updateIFrame function from Thomson Reuters
//  handles dynamic height of iframes
function updateIFrame(height) {
  var iframe = document.getElementById('IRframe');
  iframe.setAttribute('height',height);
}

