var photoDelay = 3500; //seconds * 1000

jQuery(function(){
	jQuery("div.csw").prepend("<p class='loading'>Loading...<br /><img src='images/ajax-loader.gif' alt=''/ ></p>");
	jQuery("div.panel").hide();
	jQuery(window).bind("load", function() {
		jQuery("div#slider").codaSlider()
	});
	externalLinks();
});

var j = 0;
jQuery.fn.codaSlider = function(settings) {
	settings = jQuery.extend({
		easeFunc: "expoinout",
		easeTime: 750,
		toolTip: false
	}, settings);
	return this.each(function(){
		var container = jQuery(this);
		container.find("p.loading").remove();
		jQuery("div.panel").show();
		container.removeClass("csw").addClass("stripViewer");
		var panelWidth = container.find("div.panel").width();
		var panelCount = container.find("div.panel").size();
		var stripViewerWidth = panelWidth*panelCount;
		container.find("div.panelContainer").css("width", stripViewerWidth);
		var navWidth = panelCount * 28;
		var cPanel = 1;
		
		if (panelCount > 1) container.each(function(i) {
			
			jQuery(this).before("<div class='stripNav' id='stripNav'><ul><\/ul><\/div>");
			jQuery(this).find("div.panel").each(function(n) {
						jQuery("div#stripNav ul").append("<li class='tab" + (n+1) + "'><a href='#' rel='" + jQuery(this).attr("title") + "'>" + (n+1) + "<\/a><\/li>");												
			});
			
			jQuery("div#stripNav a").each(function(z) {
				navWidth += jQuery(this).parent().width();
				jQuery(this).bind("click", function() {
					
					clearTimeout(photoTimer);
					jQuery(this).addClass("current").parent().parent().find("a").not(jQuery(this)).removeClass("current"); // wow!
					var cnt = - (panelWidth*z);
					cPanel = z + 1;
					current = cPanel;
					jQuery(this).parent().parent().parent().next().find("div.panelContainer").animate({ left: cnt}, settings.easeTime, settings.easeFunc, function() {
						startTimer();
					});
					
					return false;
				});
			});
			
			jQuery("a.cross-link").click(function(){
				jQuery(this).parents().find(".stripNav ul li a:eq(" + jQuery(this).attr("rel") + ")").trigger('click');
			});	
			
			
			jQuery("div#stripNav" + j).css("width" , navWidth);
			
			showPhoto(1);
						
		});
		
		j++;
	});
};

var current;
var photoTimer = 0;

function startTimer() {
	
	clearTimeout(photoTimer);
	
	gallerySize = jQuery().find("div.panel").size();
	
	if(current < gallerySize)
		nextPhoto = current+1;
	else
		nextPhoto = 1;
	
	photoTimer = setTimeout("showPhoto(nextPhoto)", photoDelay);
	
}

function showPhoto(id) {
	jQuery().find(".stripNav ul li a:eq(" + (parseInt(id - 1)) + ")").trigger('click');
}

function externalLinks() {
		if (!document.getElementsByTagName) return;
		var anchors = document.getElementsByTagName("a");
		for (var i=0; i<anchors.length; i++) {
			var anchor = anchors[i];
			if (anchor.getAttribute("href") &&
				anchor.getAttribute("rel") == "external")
					anchor.target = "_blank";
		}
	}
