// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

// variable to detect flash player
var hasFlash = true;
var saveMoneyNow = false;

// configuration variables for share functionality
var addthis_config = {
	services_compact: 'email, facebook, twitter',
	services_exclude: 'print'
};

// function to change pop-up header when user is on smart savings calculator results page
function setSaveNowHeader() {
	$('#request_more_info_header').attr('src','/images/h2_save_money_now.gif');
	$('#request_more_info_header').attr('height','31');
	$('#request_more_info_header').attr('width','347');
};

// Homepage functions
function resetDefaultHomePage() {
	$("#homeowner").unbind();
	$("#business").unbind();
	$("#architect").unbind();
	$("#play_flash_intro").unbind();
	$("#button_nav").attr('style','display: none');
	$("#play_intro").animate({ opacity: 0 }, 0);
	$("#headline2a").animate({ opacity: 0 }, 0);
	$("#headline2b").animate({ opacity: 0 }, 0);
	$("#content_container").fadeOut("0ms", showDefaultHomePage);
};

function hideFlashHomePage() {	
	$("#homePageDefault").fadeIn("800ms");
	$("#homePageFlash").fadeOut("800ms");
};

function transitionFlashToDefault() {
	resetDefaultHomePage();
	hideFlashHomePage();
}

function showHowItWorks() {
	flashembed("howItWorks", {
				src: "/images/flash/howItWorks.swf", 
				wmode: "opaque",
				cachebusting: true, 
				w3c: true,
				version: [10, 0],
				onFail: function() { hasFlash = false; }
			});
	if (hasFlash == true) {		
		// if user has flash, show flash movie
		$("#howItWorksDefault").fadeOut("500ms");
		$("#howItWorks").fadeIn("500ms");
	}
	else {
		// else hide flash movie and show default page
		$("#howItWorksDefault").fadeIn("500ms");
		$("#howItWorks").fadeOut("500ms");
	}
};

function showFlashHomePage() {
	flashembed("homePageFlash", {
				src: "/images/flash/homeAnimation.swf", 
				cachebusting: true, 
				w3c: true,
				version: [10, 0],
				onFail: function() { hasFlash = false; }
			}, 
			{
				wmode: "transparent"
			});
	if (hasFlash == true) {		
		// if user has flash, show flash movie
		$("#homePageDefault").fadeOut("500ms");
		$("#homePageFlash").fadeIn("500ms");
	}
	else {
		// else hide flash movie and show default page
		transitionFlashToDefault();
	}
};

// play homepage flash intro again if user clicks on "play intro" link
function playFlashMovie() {
	if (hasFlash == true) {showFlashHomePage();}
};

function bindHomepageEvents() {
	// add listeners to expand menus
	$("#homeowner").bind("mouseenter", function(e) {expandHomeMenu("homeowner")});
	$("#business").bind("mouseenter", function(e) {expandHomeMenu("business")});
	$("#architect").bind("mouseenter", function(e) {expandHomeMenu("architect")});
	
	// add listeners to close menus
	$("#homeowner").bind("mouseleave", function(e) {closeHomeMenu("homeowner")});
	$("#business").bind("mouseleave", function(e) {closeHomeMenu("business")});
	$("#architect").bind("mouseleave", function(e) {closeHomeMenu("architect")});
	
	// add listener to the play intro button
	$("#play_flash_intro").bind("click", playFlashMovie);
};

function showDefaultHomePage() {
	// fade in drop-down menus and messaging
	$("#content_container").fadeIn("1500ms", animateHeadline2a);
};

function fadeInPlayButton() {
	bindHomepageEvents();
	$("#play_intro").animate({ opacity: 1 }, 300, "linear");
};

function fadeInButtonContainer() {
	setTimeout('$("#button_nav").fadeIn("2000ms", fadeInPlayButton);', 1000);
};

function animateHeadline2b() {
	$("#headline2b").animate({ opacity: 1 }, 300, "linear", fadeInButtonContainer);
};

function fadeOutHeadline2a() {
	setTimeout('$("#headline2a").animate({ opacity: 0 }, 300, "linear", animateHeadline2b);', 2300);
};

function animateHeadline2a() {
	setTimeout('$("#headline2a").animate({ opacity: 1 }, 300, "linear", fadeOutHeadline2a);', 1300);
};

function Get_Cookie( check_name ) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f

	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );
		
		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
		
		// if the extracted name matches passed check_name
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found )
	{
		return null;
	}
};

function Set_Cookie( name, value, expires, path, domain, secure ) {
	// set time, it's in milliseconds
	var today = new Date();
	today.setTime( today.getTime() );
	/*
		if the expires variable is set, make the correct
		expires time, the current script below will set
		it for x number of days, to make it for hours,
		delete * 24, for minutes, delete * 60 * 24
	*/
	if ( expires )
	{
	expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires) );

	document.cookie = name + "=" +escape( value ) +
	( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
	( ( path ) ? ";path=" + path : "" ) +
	( ( domain ) ? ";domain=" + domain : "" ) +
	( ( secure ) ? ";secure" : "" );
};

function Delete_Cookie( name, path, domain ) {
	if ( Get_Cookie( name ) ) document.cookie = name + "=" +
	( ( path ) ? ";path=" + path : "") +
	( ( domain ) ? ";domain=" + domain : "" ) +
	";expires=Thu, 01-Jan-1970 00:00:01 GMT";
};

function checkForCookie() {
	// if user has already seen move, just show default page
	// this function is called from the flash movie
	if (Get_Cookie( 'saw_intro' ) === 'yes') {
		hideFlashHomePage();
		showDefaultHomePage();
	}
	else {
		showFlashHomePage();
		Set_Cookie( 'saw_intro', 'yes', '', '/', '', '' );		
	}
};

// function to get mouse position relative to div#elementId
function rPosition(elementID, mouseX, mouseY) {
  var offset = $('#'+elementID).offset();
  var x = mouseX - offset.left;
  var y = mouseY - offset.top;

  return {'x': x, 'y': y};
}

// get id of menu to be shown/hidden
function getMenuId(id) {
	var menuId = "undefined"
	switch(id) {
		case "homeowner":
			menuId = "#m1";
			break;
		case "business":
			menuId = "#m2"
			break;
		case "architect":
			menuId = "#m3"
			break;
		default:
			break;
	}
	return menuId;
};

function expandHomeMenu(id) {
	var menuContainerId = "#" + id;
	var menuId = getMenuId(id);
	
	// get height of menu -- dynamic so users can add/delete items
	var menuHeight = $(menuId + " > ul").height() + 5;
	
	// needed to close other menus when user expands selected menu
	for (var i=1; i<=3; i++) {
		var otherMenuId = "#m" + i;
		if (otherMenuId !== id) {
			$(otherMenuId).animate({ height: "0px" }, 500 );
		}
	}
	
	// expand selected menu if it's closed (somehow prevents bubbling)
	if ($(menuId).height() == "0") {
		$(menuId).animate({ height: menuHeight }, 500 );
	}
	
};

function closeHomeMenu(id) {
	var menuContainerId = "#" + id;
	var menuId = getMenuId(id);
	
	// hide selected menu
	$(menuId).animate({ height: "0px" }, 500 );
};

// Smart calculator functions
function toggleCalculatorTabContent(e) {
	if (this.id == "calculatorResults_1") {
		$("#calculatorResults_2").removeClass("selected");
		$("#tabContent_2").hide();
		$("#tabContent_1").fadeIn("500ms");
		$(this).addClass("selected");
		animateSavingsResults(newBillHeight);
	}
	else {
		$("#calculatorResults_1").removeClass("selected");
		$("#tabContent_1").hide();
		$("#tabContent_2").fadeIn("500ms");
		$(this).addClass("selected");
		animateFootprintResults(newFootprintHeight,newFootprintMargin);
	}
};

function animateFootprintResults(newFootprintHeight, newFootprintLeftMargin) {
	var circleHeight = "144px"
	var circleWidth =  "144px"
	var greenCircleWidth = newFootprintHeight
	var greenCircleHeight = newFootprintHeight
	var greenCircleMargin = newFootprintLeftMargin
	
	$("#orangeCircleContainer").css({'height' : circleHeight, 'width' : circleHeight, 'left' : '0px'});
	$("#greenCircleContainer").css({'height' : greenCircleHeight, 'width' : greenCircleWidth, 'margin-left' : newFootprintLeftMargin});
	$("#orangeCircle").animate({ height: circleHeight, width: circleWidth }, 1000, 'swing', fadeInFootprintNumbers);
	$("#greenCircle").animate({ height: greenCircleHeight, width: greenCircleWidth }, 1000, 'swing');
};

function animateSavingsResults(newBarHeight) {
	var oldBillBarHeight = "142px"
	var newBillBarHeight = newBarHeight;
	$("#oldBillBarContainer").animate({ height: oldBillBarHeight}, 1000, 'swing', fadeInSavingsNumbers);
	$("#newBillBarContainer").animate({ height: newBillBarHeight }, 1000, 'swing');
};

function fadeInFootprintNumbers() {
  $("#oldFootprintNumber").fadeIn();
  $("#newFootprintNumber").fadeIn();
};

function fadeInSavingsNumbers() {
  $("#oldBillNumber").fadeIn();
  $("#newBillNumber").fadeIn();
};

function printPage() {
	window.print()
};

function showRequestInfo() {
	$("#overlay").overlay({api: true}).load();
};

function goToCalculator() {
	window.location.pathname = "/categories/home-owner/calculations/new"
};

function setupCleanPowerGuideRollover() {
  $('img.clean_power_guide').mouseover(function() {
    $('img.clean_power_guide').attr('src', '/images/clean_power_guide_rollover.gif')
  })
  $('img.clean_power_guide').mouseout(function() {
    $('img.clean_power_guide').attr('src', '/images/clean_power_guide.gif')
  })
}

// faq page functions
function setupFAQ() {
  $('#faq dd').addClass('hidden');
  $('#faq dt').click(function() {
    if ($(this).next('dd').hasClass('hidden')) {
      $(this).next('dd').removeClass('hidden');
      $(this).css("background-image","url(/images/faq_arrow_down.jpg)");
    }
    else {
      $(this).next('dd').addClass("hidden");
      $(this).css("background-image","url(/images/faq_arrow_right.jpg)");
    }
  });
};

// page init function	
function init() {
	// set listeners
	if ($("#homePageFlash").length == 1) {
		checkForCookie();
	}
	$("#calculatorResults_1").live("click", toggleCalculatorTabContent);
	$("#calculatorResults_2").live("click", toggleCalculatorTabContent);
	$(".print").live("click", printPage);
  
  $('a[rel]').overlay({
    onBeforeLoad: function() { 
      var wrap = this.getContent().find(".contentWrap");  // grab wrapper element inside content 
		wrap.load(this.getTrigger().attr("href"));  // load the page specified in the trigger 
    }
  });

 	setupCleanPowerGuideRollover();
	setupFAQ();
};

$(document).ready(init);

// Contact page listener for when the industry field is selected to "Other"
function loadLeadIndustryObserver(){
	$('#lead_industry').change(function(e){
	    if($('#lead_industry').val() == "Other") { 
			$('#lead_industry_free_type').attr("style", "display:inline;");	
			$('#lead_industry').remove(); 
		}
	 });
}