// var FOO = {}; // Placeholder namespace (dev only)

var SPIL = {};     // SPI Lasers namespace
SPIL.f_index = ''; // The index of a filter link or its details_list correlate

// Strings to translate
SPIL.txt_sales_anon_closed = 'Find sales support for your country';
SPIL.txt_sales_anon_open   = 'Hide sales support search';
SPIL.txt_sales_closed      = 'View sales support';
SPIL.txt_sales_open        = 'Hide sales support';

// Initialise number of product ranges to test later
SPIL.ranges                = 0;

SPIL.question;

// Initialise variables for home page promos
SPIL.hwrapper;
SPIL.promo_urls;
SPIL.promo_titles;
SPIL.np; // Number of source banner promos
SPIL.ip; // Index of next promo to get
SPIL.next_promo;


$(document).ready(function() {
	$('html').removeClass('no-js');
	
	// Report screen resolution
	// report_res();

  // Local scroll settings 
  // IE7 falls over on FAQ page so make an exception
	if ( $('html').hasClass('ie') ) {
		if ( !$('.body').hasClass('faq') ) {
			init_localScroll();
		}
	}
	else {
		init_localScroll();
	}
	
	// Compact and hinted form handling
	form_hinted();

	// ColorBox
	$('a[rel="apps1"], .modal').colorbox({transition:'elastic', height:'85%'});
	
	$('.modal').colorbox({
		width:'60%', 
		height: '510px',
		href: function(){ return $(this).attr('href') + ' #modal';}
	});

	/* Disable non-functional links
	$('a[href="foo"]').click(FOO.stoplink);
	// Disable non-functional forms
	$('form[action="foo"]').submit(function() {
		alert('Form not functional!');
		return false;
	}); */
	
	// Home page promo handling 
	if ( $('.body').hasClass('home') ) {
		SPIL.home_promo_setup();
	}

	// Items filtering
	if ($('.sub_banner .details_list').length) {
		SPIL.filter_details_list();
	}
	SPIL.country_filter();
	
	// Unbind localScroll for carousel_go links 
	$('.carousel_go a').unbind('click');
		
	// Banner image placement
	SPIL.banner_img();
	SPIL.app_img();

	// Category filters
	SPIL.panel_filter_list();
	$('.main .filter a').click(SPIL.category_filter);
	$('.faq .toc a').click(SPIL.category_filter);
	
	// Carousels
	SPIL.carousel();
	
	// Add skip links to sections
	SPIL.add_skip();
	
	// Fix table headers
	// TABLE.fix_header('table');
	
	// Create links in compare table cells with td content
	SPIL.compare_links();
	
	// Sales team handling
	$('.sub_banner #sales').hide();
	$('#options .sales a').click(SPIL.toggle_sales);
	
	// Sliders for FAQ and others
	$('.main .details_list .summary').attr('title','Show details').wrapInner('<a href="#" />');
	$( '.details .answer, ' ).hide();
	$('.faq .details_list').css('min-height',$('.faq .details_list').height());
	$('.details_list .summary a').click(SPIL.toggle_answer);

	// In-page sales link handling
	if ( !$('html').hasClass('ie') ) {
		$('a[href="#sales"]').unbind('click').click(function() {
			if ( $('#sales:visible').length ) {
				$.scrollTo('#options',400);
			}
			else {
				$.scrollTo('#options',400,{onAfter:function(){
					setTimeout('SPIL.open_sales()',200);
				} });
			}
		});
	}
	
	// Scroll follow
	// $('.toc .related').addClass('ofl');
	if ( $('.body').hasClass('applications') ) {
		if ( $('.body').hasClass('onym') && $('.main .entry-content').length ) {
			scroll_follow();
		}
	}
	else {
		if ( $('.toc').length ) {
			scroll_follow();
		}
	}
	
	// Print 
	$('#options .print a').click(function() {
		if ( !$('#sales').is(':visible') ) {
			var $prompt = $('#options .sales a');
			var $txt = $prompt.find('span');
			var $sales = $('.sub_banner #sales');
			
			$prompt.addClass('open');
			if ($prompt.hasClass('anon')) {
				$txt.text(SPIL.txt_sales_anon_open);
			}
			else {
				$txt.text(SPIL.txt_sales_open);
			}
			
			$sales.slideDown(function() {
				window.print();
			});
		}
		else {
			window.print();
		}
		return false;
	});
	
	// IE7 specific help with checkmarks
	if ( $('html').hasClass('ie7') ) {
		SPIL.compare_checkmark();
	}	
  
	// Row classing for search results
	SPIL.row_class();
	
});


function init_localScroll() {	  
  $.localScroll({
    event:'click', //on which event to react
    axis:'y',
    duration:500,
    offset:-30,
    hash:true,
		stop:true      //avoid queuing animations
  });
}


function form_hinted() {	  
  $('.hinted input.text, .hinted textarea').each(function() {
			var $hint;
			if ($(this).attr('title').length) {
				$hint = $(this).attr('title');
			}
			else {
				$hint = $(this).prev('label').text();
			}

			$(this)
				.val($hint)
				.data('default', $(this).val())
				.addClass('inactive')
				.focus(function() {
					$(this).removeClass('inactive').next('.help').fadeIn('fast');
					if($(this).val() == $(this).data('default') || '') {
						$(this).val('');
					}
				})
				.blur(function() {
					$(this).next('.help').fadeOut('fast');
					var default_val = $(this).data('default');
					if($(this).val() == '') {
						$(this).addClass('inactive');
						$(this).val($(this).data('default'));
					}
				});
  });
}


//Appends controls to .banner and .sub_banner
SPIL.filter_details_list = function() {

/* Goes to work on details_list in .sub_banner with following structure
.details_list
  h2
  .line // as many copies of line and its children as desired
    .firstUnit
      h3
    .lastUnit
    	p
*/
	
	// Set up visibility of the first details_list item
	$('.sub_banner .details_list .line').hide();
	$('.sub_banner .details_list .line:first').addClass('active').show();
	
	// Create some empty elements to append to
	var $filter = $('<div class="filter"></div>');
	var $list = $('<ul></ul>');

	// Append the heading if present
	var $h2 = $('.sub_banner h2');
	if ($h2.length) {
		var $h2wrap = $('<li class="arrow_wrap"></li>').append($h2).append('<b></b>');
		$list.append($h2wrap);
	}

	// Loop through the headings in details_list to create a new control list
	// Correlate each item in the list with a class
	$('.sub_banner .details_list h3').each(function(i) {
		_h3 = $(this);
		$(this).parents('.line').addClass('f' + i);
		$list.append($('<a href="#"></a>')
			.addClass('f' + i)
			.html(_h3.text())
		);
  });
  $list.find('a').wrap('<li class="h2" />');
	$filter.append($list);
  
  // Add the result to .banner and make the first filter list item active
	$('.banner .max').append($filter);
	$('.banner .filter .f0').parent().addClass('active');
  
  // Style the arrow head on the right hand end of the h2 
  $bborder = Math.round( ($('.banner .filter h2').height()+6) / 2 );

  $('.banner .filter b').css({
		'border': $bborder + 'px solid transparent', 
		'border-left': '16px solid #000'
	});

	// Set up event handlers
	$('.banner .filter a').click(SPIL.show_details_item);
	
	// Create a next button and event handler 
	$('.sub_banner .details_list').append('<div class="next"><a href="#" title="View next benefit">Next</a></div>');
	$('.sub_banner .details_list .next a').click(SPIL.next_details_item);
	
}

SPIL.show_details_item = function() {
	// Capture banner filter click event 
	var _banner_filter_e = $(this);
	
	if (_banner_filter_e.parent().hasClass('active')) {
		// If the item clicked is active do nothing
		return false;
	}
	else {
		
		// If a filter link was clicked
		if (_banner_filter_e.parent().hasClass('h2')) {
			// Get the class of the filter link to use below
			SPIL.f_index = _banner_filter_e.attr('class');
		}
		
		// Tidy up which filter list item is now active
		$('.banner .filter .active').removeClass('active');
		$('.banner .filter .' + SPIL.f_index).parent().addClass('active');
		
		// Hide the active details_item and show the one for the filter link that was clicked
		$('.sub_banner .details_list .active').removeClass('active').fadeOut('fast',function() {
			$('.sub_banner .details_list .' + SPIL.f_index).fadeIn('fast').addClass('active');
		});
	}
	
	return false;
}


SPIL.next_details_item = function() {
	// Get the index of the current details_item 
	var classes = $('.sub_banner .details_list .active').attr('class');
	var f_pos = classes.indexOf('f'); // A regex for fX where X is a digit would be more robust here!
	var i = classes.charAt(f_pos + 1);
	// coerce i to a number
	i  = i*1;
	
	// Set the index of the next item and show it
	var h = 1;
	
	// Check if the first item is a non functional h2
	if ( $('.banner .filter li:first').hasClass('arrow_wrap') ) {h = 2;}
	
	if (i < ($('.banner .filter li').length - h)) {
		SPIL.f_index = 'f' + (i+1);
	}
	else {
		SPIL.f_index = 'f0';
	}
	SPIL.show_details_item();
	
	return false;
}


SPIL.banner_img = function() {
	$photo = $('.banner .photo');
	$src = $photo.attr('src');
	if ( !('#header_wrapper').length ) {
		$('.banner .max').wrapInner('<div class="banner_img" />');
	}
	else {
		$('#header_wrapper').wrapInner('<div class="banner_img" />');
	}
	if ( $('.range').length ) {
		$('.banner_img').css('background','transparent url("' + $src + '") no-repeat 98.5% 100%');
	}
	else {
		$('.banner_img').css('background','transparent url("' + $src + '") no-repeat 44% 100%');
	}
	
	$photo.addClass('ofl');
}

SPIL.app_img = function() {
	$appimg = $('.banner .appimg img');
	$src = $appimg.attr('src');
	$('#header_wrapper').wrapInner('<div class="banner_appimg" />');

	if ( $('.banner .compact').length || $('.banner .green').length ) {
		$('.banner_appimg').css('background','transparent url("' + $src + '") no-repeat 67% 100%');
	}
	else {
		$('.banner_appimg').css('background','transparent url("' + $src + '") no-repeat 76% 0');
	}
	$appimg.addClass('ofl');
}


// Build a list of filter links from non-OOCSS classes present in a results set
SPIL.panel_filter_list = function() {
	$('.panel .results').each(function() {
		var _results = $(this);
		
		// Let's only do this if the results set is preceded by a filter heading
		if ( _results.prev('.filter').length ) {

			// Get the companion filter heading for _results
			var $filter = _results.prev('.filter');
			// A container for the list we'll be creating
			var $list =[];
			// A list of class names to ignore
			var $exclude = ['unit','size1of2','size1of3','size1of4','size1of5','size1of6','lastUnit'];
			
			// Get the classes assigned to each unit as an array
			_results.find('.unit').each(function() {
				var $classes = $(this).attr('class').split(' ');
	
				// Check each class to see if it needs to be added to the list
				jQuery.each($classes, function(i) {
					var $class = $classes[i];
					if ( jQuery.inArray($class, $exclude) == -1  ) {
						$list.push($class);
						$exclude.push($class);
					}
				});
			});
			
			// Remove duplicates from $list and sort it
			$list = jQuery.unique($list).sort();
			
			// Setup containers to work with
			var $contents = $('<div class="contents" />').html('<div class="prompt">Show:</div>');
			var $ul = $('<ul />').html('<li><a class="all active" href="#" title="No filter">All</a></li>');
			
			// Create a list item for each item in $list
			jQuery.each($list, function(i) {
				var $option = $list[i];
				var $li = $('<li />')
					.html('<a href="#" />');
				
				$li.find('a').attr('class',$option).text($option);
				$li.appendTo($ul);
			});
			
			// Add our new elements to the page
			$ul.appendTo($contents);
			$contents.appendTo($filter);
		}
		
	});
}

// Filters sets of .results according to a filter class
SPIL.category_filter = function() {

	// If the filter link clicked is active do nothing
	if ($(this).hasClass('active')) {
		return false;
	}
	else {
				
		// If the link clicked is not 'All' get its class
		var $show;
		if ($(this).hasClass('all')) {
			$show = '';
		}
		else {
			$show = '.' + $(this).attr('class');
		}
		
		// There could be more than one filter block on the page
		// So let's constrain ourselves to the relevant one (only one per section assumed)
		var $section;
		if ( $('.body').hasClass('faq') ) {
			$('.toc .active').removeClass('active').attr('title','');

			// Hide all the questions and answers
			$('.details_list .details').hide();

			// Show only the relevant ones
			var $results = $('.details_list ' + $show);
			$results.fadeIn(400);

			// If there is only one question, show the answer: needs work!
			/*
			if ($results.length = 1) {
				if ( !$results.hasClass('open') ) {
					SPIL.question = $results.find('.summary a');
					SPIL.toggle_answer();
				}
			}
			*/
		}
		else {
			$section = $(this).parents('.section');
			$($section + '.filter .active').removeClass('active').attr('title','');
			// Hide all the results then show only the relevant ones
			$($section + '.results .unit').hide();
			$($section + '.results div' + $show).fadeIn(400);
		}
		
		$(this).addClass('active').attr('title','Now showing');

		
		return false;
	}
}


// Adds carousels
SPIL.carousel = function() {
  // jCarousel Lite oocss
  $('.carousel').wrap('<div class="carousel_wrapper" />');
  
	$('.carousel_wrapper').each(function() {
		
		// Check to see if the carousel should auto run
		var $autorun = null;
		if ( $(this).find('.carousel').hasClass('autorun') ) {
			$autorun = 5000;
		}
		
		// Check if there are go buttons 
		var $goto = null;
		if ( $('.carousel_go').length ) {
			$goto = [];
			$('.carousel_go a').each(function(i) {
				$goto[i] = '.carousel_go .' + $(this).attr('class');
			});
		}
		
		// Get the first .unit so we can check its OOCSS width
			// NB: expects all .units to be the same width!
		var $first_unit = $(this).find('.unit:first');
		var $nv; // number we're going to make visible at a time
		
		if ( $first_unit.hasClass('size1of2') ) {
			$nv = 2;
		}
		else if ( $first_unit.hasClass('size1of3') ) {
			$nv = 3;
		}
		else if ( $first_unit.hasClass('size1of4') ) {
			$nv = 4;
		}
		else if ( $first_unit.hasClass('size1of6') ) {
			$nv = 6;
		}
		else {
			$nv = null; // Don't run the carousel!
		}
		
		if ($nv != null) {
		
			var $controls = $('<div class="controls" />');
			var $next = $('<a href="#" class="next">Next</a>');
			$controls.append($next);
			
			if ( !$(this).parents('.ranges').length ) {
				$next.before('<a href="#" class="prev">Previous</a>');
			}
			else {
				SPIL.ranges = $('.ranges .unit').length;
			}
			
			$(this).find('.carousel').before($controls);
			
			$(this).jCarouselLite({
				btnNext: '.next',
				btnPrev: '.prev', 
				btnGo: $goto,
				visible: $nv,
				speed: 400,
				auto: $autorun
			});
			
			if (SPIL.ranges != 0) {SPIL.next_ranges();}
		}
	});
}


// Sets next range text on ranges carousel 
SPIL.next_ranges = function() {
	$('.ranges .unit').each(function(i) {
		var $unit_left = $(this).offset().left;
	});
}


// Fix table headers
/* 
var TABLE = {};

TABLE.fix_header = function(table) {
  $(table).each(function() {
    var $table = $(this);
    
    // Let's only do this if the table has a thead that contains th cells only!
    if ( $table.find('thead').length ) {
    	if ( !$table.find('thead td').length ) {

				// We're in business, let's crack on…
				var $thead = $table.find('thead');
				var $tfoot = $table.find('tfoot').height();
				var $ths = $thead.find('th');
				
				$table.data('top', $thead.offset().top);
				$table.data('left', $thead.offset().left);
				$table.data('bottom', $table.data('top') + $table.height() - $thead.height() - $tfoot);
				$faux = $('thead .faux').length;
		
				if ($faux > 0) {
					// The window has been resized so just set the width of .faux
					$ths.each(function(i){
						_th = $(this);      
						_faux = _th.find('.faux');
						$width = _th.width() + 12; // Because padding is 6px
						_faux.width($width);
					});
				}
				else {
					$ths.each(function(i){
						var _th = $(this);      
						_th.wrapInner('<span />').wrapInner('<span class="faux" />');
						var _faux = _th.find('.faux');
		
						var $width = _th.width();
						_th.width($width);
		
						var $left = _th.offset().left;
						_th.css({left: $left});
		
						_faux.attr('scope',_th.attr('scope')).width($width);
					});
				}
				
				$(window).scroll(function() {
					if ($table.data('top') < $(document).scrollTop() && $(document).scrollTop() < $table.data('bottom')) {
						$thead.addClass('fixed');
						$('.legend').addClass('fixed').css('left',$table.data('left')-10);
					} 
					else {
						$thead.removeClass('fixed');
						$('.legend').removeClass('fixed').css('left','auto');
					}
				});

    	}
    }    
  });
}


$(window).resize(function() {
	TABLE.fix_header('table');
});
*/


SPIL.toggle_sales = function() {
  var $prompt = $('#options .sales a');
  var $txt = $prompt.find('span');
  var $sales = $('.sub_banner #sales');
  
  if ($prompt.hasClass('open')) {
  	$sales.slideUp();
  	$prompt.removeClass('open');
  	if ($prompt.hasClass('anon')) {
  		$txt.text(SPIL.txt_sales_anon_closed);
  	}
  	else {
  		$txt.text(SPIL.txt_sales_closed);
  	}
  }
  else {
  	$sales.slideDown();
  	$prompt.addClass('open');
  	if ($prompt.hasClass('anon')) {
  		$txt.text(SPIL.txt_sales_anon_open);
  	}
  	else {
  		$txt.text(SPIL.txt_sales_open);
  	}
	}  
  return false;
}

SPIL.open_sales = function() {
  var $prompt = $('#options .sales a');
  var $txt = $prompt.find('span');
  var $sales = $('.sub_banner #sales');
  
  if (!$prompt.hasClass('open')) {
  	$sales.slideDown();
  	$prompt.addClass('open');
  	if ($prompt.hasClass('anon')) {
  		$txt.text(SPIL.txt_sales_anon_open);
  	}
  	else {
  		$txt.text(SPIL.txt_sales_open);
  	}
	}  
  return false;
}





// Append product series links to compare table cells
SPIL.compare_links = function() {
	var $links = new Array();
	var $titles = new Array();
	
  $('.compare thead th a').each(function(i){
  	$(this).parents('th').addClass('linked');
  	// Create a title attribute for the link
  	$(this).attr('title','View ' + $(this).text() + ' datasheet');
  	
		// Store the destination of the link
  	$links[i] = $(this).attr('href');
		// Store the title attribute
  	$titles[i] = $(this).attr('title');
  });
  
  // For each compare table row
  $('.compare tbody tr').each(function(){
    var $tr = $(this);
    var $tds = $tr.find('td');
  	
  	$tds.each(function(i){
  		// Check the cell isn't empty
			if ( $(this).text().length ) {
				_td = $(this);
				_td.wrapInner('<a href="" />').addClass('linked'); 
				_td.find('a')
					.attr('href',$links[i])
					.attr('title',$titles[i])
			}
		});
  });
}

// Replace compare checkmarks ems with images for IE7
SPIL.compare_checkmark = function() {
	$('.compare .optimal').replaceWith('<img src="/img/checkmark-optimal.png" alt="Optimal">');
	$('.compare .good').replaceWith('<img src="/img/checkmark-good.png" alt="Good">');
	
	// Sort out a hover function!		
}


// Add skip links to sections
SPIL.add_skip = function() {
	// Create a placeholder we can append to
	var $skip = $('<div class="skip"></div>');
	
	$('.main .section').each(function(){
		_section = $(this);

		// Check the section has an id we can link to and a subheading
		if (_section.attr('id').length && (_section.find('h2').length > 0) ) {

			// Check if section is below the fold
			if ( _section.offset().top > $(window).height() ) {

				// Append a link to our placeholder
				$link = $('<a href=""></a>')
					.attr('href','#' + _section.attr('id'))
					.text(_section.find('h2:first').text());
				$skip.append($link);
			}
		}
	});
	
	// Delimit the list
	if ($skip.text().length > 0) {
		var $count = $skip.find('a').length
		
		if ($count > 1) {
			$skip.find('a:last').before(' or ');
		}
		
		if ($count > 2) {
			var $n = $count - 1
			$skip.find('a:lt(' + $n + ')').before('<span class="delim">, </span>');
		}

		// Remove the first delimiter
		$skip.find('.delim:first').remove();
		// Prepend skip text
		$skip.find('a:first').before('Skip to ');
		
		// Insert the placeholder
		$('#options ul').before($skip);
		
		init_localScroll();
	}

}



/* Scroll Follow adapted from Cognition blog by Happy Cog: 
http://cognition.happycog.com */
function scroll_follow() {
		
	// Get #toc, #related and .main heights
	var $toc_height = $('#toc').height();
	var $rel_height = 0;
	
	if ( $('#related').length ) {
		$rel_height = $('#related').height();
	}
	var $col_height = $rel_height;
	
	// We'll work with which ever column is taller
	if ($toc_height > $rel_height) {
		$col_height = $toc_height;
	}

	var $main_height = $('.main').height();
	
	// Let's only do this if main is taller than col_height
	if ($main_height > $col_height) {

		// element position
		var $top = $('.main .entry-content').offset().top - 15;
			
		// footer position
		var $footerpos = $('.foot').offset().top;
	
	
		$(window).scroll(function (event) {
			// what the y position of the scroll is
			var $y = $(this).scrollTop();
		
			// Are we ready to start following?
			if ($y >= $top) {
				// if so, add the fixed class
				$('.sf').addClass('fixed');
			} 
			else {
				// otherwise remove it
				$('.sf').removeClass('fixed');
				$('#toc').removeClass('anchored');
			}
			
			// Let's check how close the footer is to the element:
	
			var $elpos = $('.sf').offset().top;
			
			if ($footerpos-$elpos < $col_height) { 
				if($('.sf').hasClass('fixed')) {
					$('.sf').removeClass('fixed');
					$('#toc').addClass('anchored');
				}
			}
			if ($footerpos-$elpos >= $col_height) { 
				if($('#toc').hasClass('anchored')) {
					$('#toc').removeClass('anchored');
					$('.sf').addClass('fixed');
				}
			}
		});
	}
}


// FAQ answers 
SPIL.toggle_answer = function() {
	SPIL.question = $(this);
	var $detail = SPIL.question.parents('.details');
	if ( !$detail.hasClass('open') ) {
		$detail
			.addClass('open')
			.find('.answer').slideDown()
			.prev('.summary').attr('title','Hide details');
	}
	else {
		$detail
			.removeClass('open')
			.find('.answer').slideUp()
			.prev('.summary').attr('title','Show details');
	}
	return false;
}

// Country filter for team and distributors
SPIL.country_filter = function() {
	var $select = $('.form_elem .country');
	
	$select.change(function() {
		var $country = $select.val();
		
		// Clear all active units
		var $units = $('.results .unit');
		$units.removeClass('active focus global');
		
		$('input.countries').each(function() {
			// Convert the value of each hidden field to an array
			var $territories = $(this).val().split(',');
			
			// If the hidden field value contains $country make it active
			if ( $.inArray('Global', $territories) != -1 ) {
				$(this).parents('.unit').addClass('active global');	
			}
			if ( $.inArray($country, $territories) != -1 ) {
				$(this).parents('.unit').addClass('active focus').removeClass('global');	
			}
		});
		
		if ($country != '') {
		
			if ($country == 'All') {
				$units.hide();
				$units.fadeIn(400);
			}
			else {
				$units.hide();
				$('.results .active').fadeIn(400);
			}
		}
		else {
			$units.hide();
			$units.fadeIn(400);
		}
	});
}

// Initial home page banner promo
SPIL.home_promo_setup = function() {
	/* A small promo may or may not be present in .banner so create a wrapper 
	element we can append to without having to worry about the DOM inside .banner */
	$('.banner .header').wrap('<div id="header_wrapper" />');
	SPIL.hwrapper = $('#header_wrapper');
	
	// Get the available promo urls and titles
	SPIL.promo_urls = $('.home .promo_urls').val().split(',');
	SPIL.promo_titles = $('.home .promo_titles').val().split(',');
	// Check how many of them there are
	SPIL.np = SPIL.promo_urls.length;
	
	// As long as at least one banner promo exists
	if (SPIL.np > 0) {
	
		// Randomise which one to get first
		SPIL.ip = Math.floor(Math.random()*SPIL.np);
		
		SPIL.home_promo_load();
		
		// As long as there is more than one banner promo
		if (SPIL.np > 1) {
			// Create a next link
			var $next = $('<div class="next" />');
			$next.html('<span class="prompt">Next product: </span>');
			SPIL.next_promo = $('<a href="#" />');
			$next.append(SPIL.next_promo);
			$('.banner .max').append($next);
			
			// Update i
			if (SPIL.ip+1 < SPIL.np) {
				SPIL.ip++;
			}
			else {
				SPIL.ip = 0;
			}
		
			// Setup link text and click handler
			SPIL.next_promo
				.text(SPIL.promo_titles[SPIL.ip])
				.click(SPIL.home_promo_next);
		}
	}
}



// Get next home page banner promo
SPIL.home_promo_next = function() {
	
	SPIL.home_promo_load();

	// Update i
	if (SPIL.ip+1 < SPIL.np) {
		SPIL.ip++;
	}
	else {
		SPIL.ip = 0;
	}
		
	// Update link text 
	SPIL.next_promo.text(SPIL.promo_titles[SPIL.ip]);
	
	return false;
}


// Load home page banner promo
SPIL.home_promo_load = function() {
	// Set up a loading spinner
	var $spinner = '<div class="spinner" alt="loading…" />';
	
	// Store the existing header contents in case something goes wrong
	var $default = $('.banner .header').html();
	
	// We only want to insert the header from the target file
	var $header = SPIL.promo_urls[SPIL.ip] + ' .header';
	
	SPIL.hwrapper.html($spinner).load($header, function(response, status, xhr) {
		if (status == "success") {
			$(this).hide();
			SPIL.banner_img();
			SPIL.app_img();
			SPIL.hwrapper.fadeIn('slow');
		}
		if (status == "error") {
			// Restore the default header
			SPIL.hwrapper.html($default);
		}
	});
}

// Row classing on search results 
SPIL.row_class = function() {
	$('.search_reslts li:odd, .search_results li:odd').addClass('odd');
	$('.search_reslts li:even, .search_results li:even').addClass('even');
}

/* Stuff for prototyping only 

function report_res() {
	var $resize_1024;
	var $optimal = '<li>The design for this page is currently optimal for browser views of 1280 pixels wide or more. </li>';
	var $refresh = '<li>If you resize your browser or drag it to another screen, refresh this page to update this info. </li>';
	if (screen.width > 1024 && screen.height > 768) {
		$resize_1024 = '<li><a href="#">Click here to resize your browser window to 1024 x 768 pixels</a></li>';
	}
  var $res = $('<div id="res" />')
		.html('<h4>Info about your screen</h4><ul>' + $optimal + '<li>Your screen resolution is ' + screen.width + ' x ' + screen.height + ' pixels. </li>' + '<li>Your browser’s current viewable area is ' + $(window).width() + ' x ' + $(window).height() + ' pixels. </li>' + $refresh + $resize_1024 + '</ul>');
  $('#dev_only').append($res);
  $('#res a').click(resize);
}

function resize() {
	resizeTo(1024,768);
	return false;
}

// Placeholder link handling
FOO.stoplink = function() {
	if ( !$(this).parents('.filter').length ) {
		alert('Just a dummy link!');
		return false;
	}
} */

