// CHECK FOR NEW WINDOW LINKS
function getNewWindowLinks() {
	$("a.non-html, a.off-site, a[rel='external']").live('click', function(e) {
		var event;
		if (!e) {
			 event = window.event;
		}	
		else { 
			event = e;
		}
		if (event.shiftKey || event.altKey || event.ctrlKey || event.metaKey) {			
			return true;
		}
		else {				
			var newWindow = window.open(this.getAttribute('href'), '', 'width=780, height=500, scrollbars=yes, resizable=yes, toolbar=yes, location=yes, directories=no, menubar=yes, copyhistory=no');
			if (newWindow) {
			    try {
			        if (newWindow.focus()) {
				        newWindow.focus();
				    }
			    }
			    catch(err) {		        
			        return false;		        
			    }	
			return false;
			}
		return true;
		}
	});
}

// LOOK FOR TABLES AND CREATE ALTERNATE ROWS
// Requires jQuery
// This auto adjusts alternate rows as new rows are added
function createAlternateRows() {
	$("td:odd").addClass("alt");
}
// LOOK FOR UNORDERED LISTS TO CREATED COLUMNAR LISTS
function createColumnarLists() {
	$("ul.columnar li:odd").addClass("column1");
	$("ul.columnar li:even").addClass("column2");
	$.each($("ul.columnar li"), function() {		
		if ($(this).text() == "") {
			$(this).addClass("none");
		}
	});
	$("ul.columnar + *").addClass("end");
}


// LOOK FOR CLOAKED LINKS AND MAKE THEM CLICKABLE
// Hopefully this will help hide e-mail addresses from spam spiders
function createMailtoLinks() {
	// Check that the browser is DOM compliant
	if (document.getElementById && document.createElement && document.appendChild) {			
		var email; // E-mail address
		var mailto; // The mailto hyperlink
		var cloak; // The mailto span element
		var spans = document.getElementsByTagName('span'); // Array of span elements
		for (var i = 0; i < spans.length; i++) {
			cloak = spans[i];
			// Find all span elements with a class name of "cloak"
			if (/\bcloak\b/.test(cloak.className)) {				
				email = cloak.innerHTML;
				cloak.innerHTML = "";
				mailto = document.createElement('a');															
				mailto.href = 'mailto:' + email;
				mailto.innerHTML = email;
				cloak.appendChild(mailto);			
			}
		}	
	}
}

// SET FOCUS ON PAGES WITH USER FORMS
// Requires jQuery
// Look for inputs tags with the class name of "first"
function goToFirstInput() {		
	$("input.first").focus();
}

// LIGHTBOX
// Requires jQuery
function initLightbox() {
	$('a.lightbox').lightBox();
}

// JAVASCRIPT CHECK
// Requires jQuery
// Show elements that require JavaScript
function scriptCheck() {
	$(".req-js").removeClass();
}

// ADD CLASSES v3.0
// Requires jQuery
function addClasses() {
	// Add classes to different types of links to control behavior
	$("a[href^='http://'],a[href^='https://'],a[target='_blank']").addClass("off-site");
	$("a[href$='.pdf'],a[href$='.jpg'],a[href$='.gif'],a[href$='.png'],a[href$='.sflb'],a[href$='doc'],a[href$='docx'],a[href$='xls'],a[href$='xlsx']").addClass("non-html");
	$("a[href$='.pdf']").addClass("pdf");
	$("a[href$='.doc'],a[href$='.docx']").addClass("ms-word");
	$("a[href$='.xls'],a[href$='.xlsx']").addClass("ms-excel");
	// Build selector for current host check
	var currentDomainSelector = "a[href*='" + window.location.host + "']";
	// Exclude certain links from updated behavior
	$(currentDomainSelector).removeClass("off-site");
	$("a[rel*=lightbox],a[class*=lightbox]").removeClass("non-html");
	$("a[rel*=lightbox],a[class*=lightbox]").removeClass("off-site");	
}

/**
 * Save data to a cookie
 * All cookies set with this function will last for the length of the session
 *
 * @param str name - Cookie name
 * @param str data - Data to store in the cookie
 * @return bool
 */
function setCookie(name, data){
  if( typeof(data) !== 'undefined' && typeof(data) !== 'undefined' ){
    document.cookie = name + "=" + data + "; expires=; path=/";
    return true;
  }
    return false;
}


/**
 * Retrieve saved cookies
 *
 * @param str name
 * @return mixed - Stored cookie data on success, false on failure
 * @link http://www.quirksmode.org/js/cookies.html
 */
function getCookie(name){
  if( typeof(name) !== 'undefined' ){
    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 false;
  }
	return false;
}

/**
 * Retrieve the value for a given key in the HTTP query string
 *
 * @param key - The desired key
 * @return str (on success), false (if the given key doesn't exist)
 */
function parseHttpGet(key){
  key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+key+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec(window.location.href);
  return ( results != null ? results[1] : false );
}

/* Hide placeholder wrapper elements (with .not-empty) if they don't contain content */
function hideEmptyNodes(){  
  $('.not-empty').each(function(i,e){
    if( !$(e).html().trim() ){
      $(e).hide();
    }
  });
  return true;
}

/* Hide .bt-promotions if all three buckets are empty */
function hidePromotions(){
  var show = false;
  $('.bt-promotions').each(function(){
    $(this).children('.col').each(function(i,e){
      if( $(e).html().trim() !== '' ){
        show = true;
      }
    });
    if( !show ){
      $(this).hide();
    }
  });
}

/* Wrap videos and their h2s in <div class="video-element" /> */
function wrapVideos(){
  $('#video_container h2').each(function() {
    $(this).add($(this).nextUntil('h2')).wrapAll('<div id="' + this.id + '" class="video-element accordion" />');
    $(this).addClass('accordion-trigger').attr('id', '');
  });
  $('#video_container .video-element').each(function(){
    $(this).children(':not(h2)').wrapAll('<div class="video-inner collapsible" />');
  });
  return true;
}

/* Wrap .date-blocks > .date elements with semantic spans for month and day */
function dateBlockFormat(){
  $('.date-blocks .date, .article-meta .article-date').each(function(){
    var d = $(this).html().trim().split(' ', 2);
    if( d.length === 2 ){
      $(this).html('<span class="month">' + d[0] + '</span><span class="day">' + d[1] + '</span>');
    }
  });
  return true;
}

/* Equal-height columns on the homepage buckets */
function equalizeBuckets(){
  if( $('.buckets').length > 0 ){
    var b, h;
    
    $('.buckets').each(function(){
      b = $(this);
      h = 0;
      b.children('.col').each(function(){
        if( $(this).height() > h ){
          h = $(this).height();
        }
      });
      b.children('.col').height(h + 'px');
    });
  }
  return true;
}

/* Content accordions */
function accordion(){
  var f = ':first';
  var setHash = true;
  
  var c = getCookie('accordionState');
  if( c && parseInt(c, 10) > 0 ){
    f = ':eq(' + c + ')';
    setHash = false;
    setCookie('accordionState', 0);
  }
  f = ( window.location.hash != '' && $(window.location.hash).length > 0 && setHash ? window.location.hash : f ); // open by default
  
  $('.accordion:not(' + f + ') .collapsible').hide().addClass('accordion-closed');
  $('.accordion:not(' + f + ') .accordion-trigger').addClass('accordion-closed');
  $('.accordion' + f).children('.accordion-trigger, .collapsible').slideDown(300).addClass('accordion-open');
  
  // Add status indicators
  $('.accordion-trigger').each(function(){
    $(this).append('<span class="ind">&nbsp;</span>');
  });
  
  $('.accordion .accordion-trigger').hover(function(){
    $(this).addClass('hover');
  }, function(){
    $(this).removeClass('hover');
  });
  
  $('.accordion .accordion-trigger').click(function(){
    var t = $(this);
    if( $(this).siblings('.collapsible').hasClass('accordion-open') ){
      t.removeClass('accordion-open').addClass('accordion-closed');
      $(this).siblings('.collapsible').slideUp(300, function(){
        $(this).removeClass('accordion-open').addClass('accordion-closed');  
      });
    } else {
      t.removeClass('accordion-closed').addClass('accordion-open');
      $(this).siblings('.collapsible').slideDown(300, function(){
        $(this).removeClass('accordion-closed').addClass('accordion-open');
      });
    }
  });
  if( f !== ':first' && setHash ){
    window.location.hash = f;
  }
  $('.accordion .collapsible a').live('click', function(){
    var i = $($(this).parents('.accordion')).index('.accordion');
    setCookie('accordionState', i);
    return true;
  });
}

/* Clean up the Super Navigation menu */
function adjustSupernav(){
  	var intItems;
  	var objItem;
  	var strItems = "";
  	var strHtml;
  	// Remove overview nav items
	$('#super_nav .sub-nav ul.nav > li:first-child').remove();
	// Loop through all supernav containers
  	$.each($("div.sub-nav"), function () {
      // Check to see how many nav items exist
      intItems = $(this).find("ul.nav li").length;
	  if (intItems < 1) {
          // If no nav items, check to see if this is the blog or PAFOF supernav
		  var strHref = $(this).prev("a").attr("href").toLowerCase();
		  if (strHref.indexOf("blog.aspx") > -1) {
		  	  // If this is the blog supernav, identify it as such
              $(this).addClass("blog");
              $(this).find("ul.nav").addClass("sf-postListing date-blocks");			  
          }
		  else if (strHref.indexOf("putafaceonfun.com") > -1) {
		  	  // If this is the PAFOF supernav, identify it as such
              $(this).addClass("pafof");
			  strHtml = "<ul class='nav'>" + $(this).find("div.promo ul").html() + "</ul>";
			  $(this).find("div.promo ul").remove();			  
			  $(this).append(strHtml);
          }
          else {
              // If this is not the blog supernav, note it as having no nav items
              $(this).addClass("no-nav");
          }
      }
      else if (intItems > 5) {	  	
          // If more than 5 nav items, split them into 2 columns
		  strItems = "";
          for (i = 6; i <= intItems - 1; i++) {
              objItem = $(this).find("ul.nav li").eq(i);
              strItems = strItems + "<li>" + objItem.html() + "</li>";
              objItem.hide();
          }
          $(this).find("ul.nav").after("<ul class='nav'>" + strItems + "</ul>");
          $(this).find("div.promo").addClass("small");
      }
  });
  // Get blog posts
  var strPosts = $("#ctl00_Blog_uc_BlogPostsFooter_ctl00_ctl00_uc_pnlBlogPostsFooter ul").html();
  if (strPosts != null) {
      $("div.sub-nav ul.sf-postListing.date-blocks").append(strPosts);
  }
}

/* Hide pagination beyond x items */
function trimPagination(n){
  if( typeof(n) !== 'undefined' && $('.pagination').length > 0 ){
    n = parseInt(n, 10);
    $('.pagination li:eq(' + (2+n) + ')').nextUntil('li.hellip').hide();
  }
  return true;
}

/* Turn the blog category list into a select item */
function blogCategoryList(){
  if( $('.blog-categories').length > 0 ){
    $('.blog-categories').hide();
    var s = '';
    var c = 'BlogCatID';
    var a = parseHttpGet(c);
    $('.blog-categories li').each(function(){
      var l = $(this).children('a').attr('href').match(c + '=(.+)');
      if( l[1] ){
        s += '<option value="' + l[1] + '" title="' + $(this).children('a').attr('href') + '"' + ( l[1] === a ? ' selected="selected"' : '' ) + '>' + $(this).children('a').html() + '</option>';
      }
    });
    
    if( s !== null ){
      $('.blog-categories').html('<select name="' + c + '"><option value="" title="/Blog.aspx">Filter by category&hellip;</option>' + s + '</select>');
      $('.blog-categories').fadeIn(200);
      $('select[name="' + c + '"]').bind('change', function(){
        window.location = $(this).children('option:selected').attr('title');
      });
      return true;
    }
  }
  return false;
}

// Clear form text fields on focus and restore text on blur
function clearMePrevious() {	
	var clearMePrevious = '';
	$.each($('.clearMeFocus'), function () {
	    $(this).attr('title', $(this).val());			
	});
	$('.clearMeFocus').focus(function () {
		 if ($(this).val() == $(this).attr('title')) {
	        clearMePrevious = $(this).val();
	        $(this).val('');
	    }
	});
	$('.clearMeFocus').blur(function () {
	    if ($(this).val() == '') {
	        $(this).val(clearMePrevious);				
	    }
	});
}

// SET COOKIE
function setCookie(cookieName,cookieValue,expireDays) {  
   var expireDate = new Date();
   expireDate.setDate(expireDate.getDate() + expireDays);
   var cookieValue = escape(cookieValue) + ((expireDays == null) ? "" : "; expires=" + expireDate.toUTCString());
   document.cookie = cookieName + "=" + cookieValue;   
 }

// ON-READY EVENTS
// Requires jQuery
$(function() {
	scriptCheck();
	addClasses();	
	clearMePrevious();
  	adjustSupernav();
	getNewWindowLinks();
	goToFirstInput();
	createAlternateRows();
	if ($.browser.msie && $.browser.version=="6.0") {
		// Used browser detection and pulled from png.js file due to IE 6 bug
		correctPNG();
	}	
});

$(document).ready(function(){
  
  hideEmptyNodes();
  hidePromotions();
  equalizeBuckets();
  Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
  /* Instantiate our placeholder plugin */
  if( $.fn.placeholder ){
    $('input, textarea').placeholder();
  }
  
  /* Make the super-nav operate a little better */
  if( $.hoverIntent ){
    $('#super_nav > li').hoverIntent(function(){
    	$(this).addClass('hover');
    }, function(){
      $(this).removeClass('hover');
    });
  } else { // In case Sitefinity fails to load hoverintent
    $('#super_nav > li').hover(function(){
    	$(this).addClass('hover');
    }, function(){
      $(this).removeClass('hover');
    });
  }
  
  /* Sub-headline transformations */
  $('.box h1 + p').addClass('sub-headline');
  
  /* Fix z-index bug with subnav menu */
  $('.subnav .RadMenu').css('z-index', '0');
  
  /* Search results header */
  if( $('.search-result-header').length > 0 ){
    $('.search-wrap').before( $('.search-result-header') );
  }
  
  /* Hide .headline content when we're not on page one of the blog list */
  if( $('.primary .box.blog-loop').length > 0 ){
    var pg = parseHttpGet('Page');
    if( pg && pg > 1 ){
      $('.box.blog-loop .headline').hide();
    }
  }
  
  /* Add .cap to ribbon links for the left border */
  //$('a.ribbon-link').prepend('<span class="cap">&nbsp;</span>');
  
  /* Add a loading indicator to location searches */
  $('#aspnetForm').submit(function(){
    var t = $(':focus');
    var i = '<img src="/bt-include/img/ind/ajax-loader.gif" alt="Loading&hellip;" class="loading" />';
    
    if( $(t).hasClass('zipcode-search') ){
      $(t).after(i);
    } else {
      $('.zipcode-search').each(function(){
        if( $(this).val() !== '' ){
          $(this).after(i);
          return true;
        }
      });
    }
    return true;
  });
  
  /* Copy back link on blog articles and put them below archives in subnav area on single pages */
  if( $('.primary .sf_singlePost.article').length > 0 ){
    $('.subnav .sf-postListing').after( $('.primary .sf_singlePost.article > .sf_back:first') );
    $('.primary .sf_singlePost.article > .sf_back:first').remove();
  }
  
  /* Move the back link on blog loop pages */
  if( $('.subnav #backLink').length > 0 ){
    $('.subnav').append( $('.subnav #backLink') );
  }
  
  /* Prep the FAQ page for accordionization */
  if( $('.primary .sf_expandedList').length > 0 ){
    $('.primary .sf_expandedList li').addClass('accordion');
    $('.primary .sf_expandedList .sf_listItemTitle').addClass('accordion-trigger');
    $('.primary .sf_expandedList .sf_listItemBody').addClass('collapsible');
  }
  
  /* Add .framed to lightbox-gallery images */
  $('.lightbox-gallery img').addClass('framed');
  
  wrapVideos();
  dateBlockFormat();
  blogCategoryList();
  accordion();
  trimPagination(7);
  
  /* Lightbox */
  if ( jQuery.fn.lightBox ) {    
     $('a[rel*="lightbox"], a.lightbox').lightBox({
       overlayBgColor: '#1a0a21',
     	imageLoading: '/bt-include/img/lightbox/bt-loading.gif',
     	imageBtnClose: '/bt-include/img/lightbox/bt-close.png',
     	imageBtnPrev: '/bt-include/img/lightbox/bt-prev.png',
     	imageBtnNext: '/bt-include/img/lightbox/bt-next.png',
     	imageBlank: '/bt-include/img/lightbox/blank.gif'
     });	 
  }
});

function EndRequestHandler() {
    $("div.gallery input[type=checkbox]:checked").parent().addClass("selected");
    $("div.gallery input[type=checkbox]").live('change', function () {
        if ($(this).is(":checked")) {
            $(this).parent().addClass("selected");
        }
        else {
            $(this).parent().removeClass("selected");
        }
    });
}

