$(document).ready(function() {
	prepare_image_slider();
	prepare_links();
	prepare_brands();
});


function prepare_image_slider() {
	$('#slider').cycle({
		fx: 'fade' // choose your transition type, ex: fade, scrollUp, shuffle, etc...
	});
}


function prepare_links() {
	$('a[rel="external"]').click(function() {
		window.open($(this).attr('href'), 'externalWindow');
	
  	return false;
	});
	
	
	// order matters for priority
	// add pdf icon to left of pdf links and open in a new window
	$('a[href$=".pdf"]').filter(function(){var t = $(this).text(); return t && $.trim(t) != "";}).addClass("icon_pdf").click(function() {
	    window.open($(this).attr('href'), 'pdfWindow');
	
	    return false;
	});
	
	// add external icon to any link that are not on this domain and open in a new window
 	$('a[href^="http://"], a[href^="https://"]').filter(function(){var link = $(this); return !(/https?:\/\/(www\.)?stickheadusa\./).test(link.attr('href')) && link.attr('class').indexOf('icon') == -1 && $(this).attr('rel').indexOf('external') == -1;}).addClass("icon_external").click(function() {
	    window.open($(this).attr('href'), 'externalWindow');
	
	    return false;
	});
}

function prepare_brands() {
	var slider = $('#brands');
	
	if (slider.length != 1) {
		return false;
	}
	
	// get the list
	ul = $('#brands ul');
	
		//wrap the ul in div.view
	ul.wrap('<div class="view" />');
	
		// add styles to the view
	$('#brands .view').css({'height' : '10.8em', 'margin' : '0 auto', 'overflow' : 'hidden', 'padding' : '0', 'position' : 'relative', 'width' : '850px'});
	
	// width of the visible portion of the list
	var view_width = $('#brands .view').width();
	
	// total width of list
	var max_pos = 0;
	ul.children().each(function() {
		// add up all the <li>s to get the width
		max_pos += $(this).outerWidth(true);
	});
	
	// if the width of the list is less that the view width, don't need the controls
	if (max_pos < view_width) {
		return false;
	}
	
	// add necessary styles to the ul
	ul.css('white-space', 'nowrap');
	
	// add controls
	$('#brands .view').before('<span class="control" id="left"></span>').after('<span class="control active" id="right" /></span>');
	
	// starting position
	var pos = 0;
	
	$('#left').click(function() {
		if ($(this).hasClass('active')) {
			pos = pos - view_width;
			update_controls(pos, max_pos, view_width);
			ul.animate({'right' : pos}, 500);
		}
	});
	
	$('#right').click(function() {
		if ($(this).hasClass('active')) {
			pos = pos + view_width;
			update_controls(pos, max_pos, view_width);
			ul.animate({'right' : pos}, 500);
		}
	});
}

function update_controls(pos, max_pos, view_width) {
	var right = $('#right');
	var left = $('#left');

	// hide or show the left button
	if (pos == 0) {
		left.removeClass('active');
	} else {
		left.addClass('active');
	}
	
	// hide or show the right button
	if (pos + view_width >= max_pos) {
		right.removeClass('active');
	} else {
		right.addClass('active');
	}
}



