//Step Carousel Viewer: By Dynamic Drive, at http://www.dynamicdrive.com
//** Created: March 19th, 08'
//** Aug 16th, 08'- Updated to v 1.4:
	//1) Adds ability to set speed/duration of panelsm animation (in milliseconds)
	//2) Adds persistence support, so the last viewed panelsm is recalled when viewer returns within same browser session
	//3) Adds ability to specify whether panelsms should stop at the very last and first panelsm, or wrap around and start all over again
	//4) Adds option to specify two navigational image links positioned to the left and right of the Carousel Viewer to move the panelsms back and forth

//** Aug 27th, 08'- Nav buttons (if enabled) also repositions themselves now if window is resized

//** Sept 23rd, 08'- Updated to v 1.6:
	//1) Carousel now stops at the very last visible panelsm, instead of the last panelsm itself. In other words, no more white space at the end.
	//2) Adds ability for Carousel to auto rotate dictated by the new parameter: autostep: {enable:true, moveby:1, pause:3000}
	//2i) During Auto Rotate, Carousel pauses onMouseover, resumes onMouseout. Clicking Carousel halts auto rotate.

//** Oct 22nd, 08'- Updated to v 1.6.1, which fixes functions stepBy() and stepTo() not stopping auto stepping of Carousel when called.

var stepcarouselsm={
	ajaxloadingmsg: '<div style="margin: 1em; font-weight: bold"><img src="ajaxloadr.gif" style="vertical-align: middle" /> Fetching Content. Please wait...</div>', //customize HTML to show while fetching Ajax content
	defaultbuttonsfade: 0.4, //Fade degree for disabled nav buttons (0=completely transparent, 1=completely opaque)
	configholder: {},

	getCSSValue:function(val){ //Returns either 0 (if val contains 'auto') or val as an integer
		return (val=="auto")? 0 : parseInt(val)
	},

	getremotepanelsms:function($, config){ //function to fetch external page containing the panelsm DIVs
		config.$bestsm.html(this.ajaxloadingmsg)
		$.ajax({
			url: config.contenttype[1], //path to external content
			async: true,
			error:function(ajaxrequest){
				config.$bestsm.html('Error fetching content.<br />Server Response: '+ajaxrequest.responseText)
			},
			success:function(content){
				config.$bestsm.html(content)
				config.$panelsms=config.$gallery.find('.'+config.panelsmclass)
				stepcarouselsm.alignpanelsms($, config)
			}
		})
	},

	getoffset:function(what, offsettype){
		return (what.offsetParent)? what[offsettype]+this.getoffset(what.offsetParent, offsettype) : what[offsettype]
	},

	getCookie:function(Name){ 
		var re=new RegExp(Name+"=[^;]+", "i"); //construct RE to search for target name/value pair
		if (document.cookie.match(re)) //if cookie found
			return document.cookie.match(re)[0].split("=")[1] //return its value
		return null
	},

	setCookie:function(name, value){
		document.cookie = name+"="+value
	},

	fadebuttons:function(config, currentpanelsm){
		config.$leftnavbutton.fadeTo('fast', currentpanelsm==0? this.defaultbuttonsfade : 1)
		config.$rightnavbutton.fadeTo('fast', currentpanelsm==config.lastvisiblepanelsm? this.defaultbuttonsfade : 1)
	},

	addnavbuttons:function(config, currentpanelsm){
		config.$leftnavbutton=$('<img src="'+config.defaultbuttons.leftnav[0]+'">').css({zIndex:50, position:'absolute', left:config.offsets.left+config.defaultbuttons.leftnav[1]+'px', top:config.offsets.top+config.defaultbuttons.leftnav[2]+'px', cursor:'hand', cursor:'pointer'}).attr({title:'Previous project '}).appendTo('body')
		config.$rightnavbutton=$('<img src="'+config.defaultbuttons.rightnav[0]+'">').css({zIndex:50, position:'absolute', left:config.offsets.left+config.$gallery.get(0).offsetWidth+config.defaultbuttons.rightnav[1]+'px', top:config.offsets.top+config.defaultbuttons.rightnav[2]+'px', cursor:'hand', cursor:'pointer'}).attr({title:'Next project'}).appendTo('body')
		config.$leftnavbutton.bind('click', function(){ //assign nav button event handlers
			stepcarouselsm.stepBy(config.galleryid, -config.defaultbuttons.moveby)
		})
		config.$rightnavbutton.bind('click', function(){ //assign nav button event handlers
			stepcarouselsm.stepBy(config.galleryid, config.defaultbuttons.moveby)
		})
		if (config.panelsmbehavior.wraparound==false){ //if carousel viewer should stop at first or last panelsm (instead of wrap back or forth)
			this.fadebuttons(config, currentpanelsm)
		}
		return config.$leftnavbutton.add(config.$rightnavbutton)
	},

	stopautostep:function(config){
		clearTimeout(config.steptimer)
		clearTimeout(config.resumeautostep)
	},

	alignpanelsms:function($, config){
		var panelsmoffset=0
		config.panelsmoffsets=[panelsmoffset] //array to store upper left offset of each panelsm (1st element=0)
		config.panelsmwidths=[] //array to store widths of each panelsm
		config.$panelsms.each(function(index){ //loop through panelsms
			var $currentpanelsm=$(this)
			$currentpanelsm.css({float: 'none', position: 'absolute', left: panelsmoffset+'px'}) //position panelsm
			$currentpanelsm.bind('click', function(e){return config.onpanelsmclick(e.target)}) //bind onpanelsmclick() to onclick event
			panelsmoffset+=stepcarouselsm.getCSSValue($currentpanelsm.css('marginRight')) + parseInt($currentpanelsm.get(0).offsetWidth || $currentpanelsm.css('width')) //calculate next panelsm offset
			config.panelsmoffsets.push(panelsmoffset) //remember this offset
			config.panelsmwidths.push(panelsmoffset-config.panelsmoffsets[config.panelsmoffsets.length-2]) //remember panelsm width
		})
		config.panelsmoffsets.pop() //delete last offset (redundant)
		var addpanelsmwidths=0
		var lastpanelsmindex=config.$panelsms.length-1
		config.lastvisiblepanelsm=lastpanelsmindex
		for (var i=config.$panelsms.length-1; i>=0; i--){
			addpanelsmwidths+=(i==lastpanelsmindex? config.panelsmwidths[lastpanelsmindex] : config.panelsmoffsets[i+1]-config.panelsmoffsets[i])
			if (config.gallerywidth>addpanelsmwidths){
				config.lastvisiblepanelsm=i //calculate index of panelsm that when in 1st position reveals the very last panelsm all at once based on gallery width
			}
		}
		config.$bestsm.css({width: panelsmoffset+'px'}) //Set bestsm DIV to total panelsms' widths
		config.currentpanelsm=(config.panelsmbehavior.persist)? parseInt(this.getCookie(window[config.galleryid+"persist"])) : 0 //determine 1st panelsm to show by default
		config.currentpanelsm=(typeof config.currentpanelsm=="number" && config.currentpanelsm<config.$panelsms.length)? config.currentpanelsm : 0
		if (config.currentpanelsm!=0){
			var endpoint=config.panelsmoffsets[config.currentpanelsm]+(config.currentpanelsm==0? 0 : config.bestsmoffset)
			config.$bestsm.css({left: -endpoint+'px'})
		}
		if (config.defaultbuttons.enable==true){ //if enable default back/forth nav buttons
			var $navbuttons=this.addnavbuttons(config, config.currentpanelsm)
			$(window).bind("load resize", function(){ //refresh position of nav buttons when page loads/resizes, in case offsets weren't available document.oncontentload
				config.offsets={left:stepcarouselsm.getoffset(config.$gallery.get(0), "offsetLeft"), top:stepcarouselsm.getoffset(config.$gallery.get(0), "offsetTop")}
				config.$leftnavbutton.css({left:config.offsets.left+config.defaultbuttons.leftnav[1]+'px', top:config.offsets.top+config.defaultbuttons.leftnav[2]+'px'})
				config.$rightnavbutton.css({left:config.offsets.left+config.$gallery.get(0).offsetWidth+config.defaultbuttons.rightnav[1]+'px', top:config.offsets.top+config.defaultbuttons.rightnav[2]+'px'})
			})
		}
		if (config.autostep && config.autostep.enable){ //enable auto stepping of Carousel?		
			var $carouselparts=config.$gallery.add(typeof $navbuttons!="undefined"? $navbuttons : null)
			$carouselparts.bind('click', function(){
				stepcarouselsm.stopautostep(config)
				config.autostep.status="stopped"
			})
			$carouselparts.hover(function(){ //onMouseover
				stepcarouselsm.stopautostep(config)
				config.autostep.hoverstate="over"
			}, function(){ //onMouseout
				if (config.steptimer && config.autostep.hoverstate=="over" && config.autostep.status!="stopped"){
					config.resumeautostep=setTimeout(function(){
						stepcarouselsm.autorotate(config.galleryid)
						config.autostep.hoverstate="out"
					}, 1500)
				}
			})
			config.steptimer=setTimeout(function(){stepcarouselsm.autorotate(config.galleryid)}, config.autostep.pause) //automatically rotate Carousel Viewer
		} //end enable auto stepping check
		this.statusreport(config.galleryid)
		config.oninit()
		config.onslideaction(this)
	},

	stepTo:function(galleryid, pindex){ /*User entered pindex starts at 1 for intuitiveness. Internally pindex still starts at 0 */
		var config=stepcarouselsm.configholder[galleryid]
		if (typeof config=="undefined"){
			alert("There's an error with your set up of Carousel Viewer \""+galleryid+ "\"!")
			return
		}
		stepcarouselsm.stopautostep(config)
		var pindex=Math.min(pindex-1, config.panelsmoffsets.length-1)
		var endpoint=config.panelsmoffsets[pindex]+(pindex==0? 0 : config.bestsmoffset)
		if (config.panelsmbehavior.wraparound==false && config.defaultbuttons.enable==true){ //if carousel viewer should stop at first or last panelsm (instead of wrap back or forth)
			this.fadebuttons(config, pindex)
		}
		config.$bestsm.animate({left: -endpoint+'px'}, config.panelsmbehavior.speed, function(){config.onslideaction(this)})
		config.currentpanelsm=pindex
		this.statusreport(galleryid)
	},

	stepBy:function(galleryid, steps){ //isauto if defined indicates stepBy() is being called automatically
		var config=stepcarouselsm.configholder[galleryid]
		if (typeof config=="undefined"){
			alert("There's an error with your set up of Carousel Viewer \""+galleryid+ "\"!")
			return
		}
		stepcarouselsm.stopautostep(config)
		var direction=(steps>0)? 'forward' : 'back' //If "steps" is negative, that means backwards
		var pindex=config.currentpanelsm+steps //index of panelsm to stop at
		if (config.panelsmbehavior.wraparound==false){ //if carousel viewer should stop at first or last panelsm (instead of wrap back or forth)
			pindex=(direction=="back" && pindex<=0)? 0 : (direction=="forward")? Math.min(pindex, config.lastvisiblepanelsm) : pindex
			if (config.defaultbuttons.enable==true){ //if default nav buttons are enabled, fade them in and out depending on if at start or end of carousel
				stepcarouselsm.fadebuttons(config, pindex)
			}	
		}
		else{ //else, for normal stepBy behavior
			if (pindex>config.lastvisiblepanelsm && direction=="forward"){
				//if destination pindex is greater than last visible panelsm, yet we're currently not at the end of the carousel yet
				pindex=(config.currentpanelsm<config.lastvisiblepanelsm)? config.lastvisiblepanelsm : 0
			}
			else if (pindex<0 && direction=="back"){
				//if destination pindex is less than 0, yet we're currently not at the beginning of the carousel yet
				pindex=(config.currentpanelsm>0)? 0 : config.lastvisiblepanelsm /*wrap around left*/
			}
		}
		var endpoint=config.panelsmoffsets[pindex]+(pindex==0? 0 : config.bestsmoffset) //left distance for bestsm DIV to travel to
		if (pindex==0 && direction=='forward' || config.currentpanelsm==0 && direction=='back' && config.panelsmbehavior.wraparound==true){ //decide whether to apply "push pull" effect
			config.$bestsm.animate({left: -config.panelsmoffsets[config.currentpanelsm]-(direction=='forward'? 100 : -30)+'px'}, 'normal', function(){
				config.$bestsm.animate({left: -endpoint+'px'}, config.panelsmbehavior.speed, function(){config.onslideaction(this)})
			})
		}
		else
			config.$bestsm.animate({left: -endpoint+'px'}, config.panelsmbehavior.speed, function(){config.onslideaction(this)})
		config.currentpanelsm=pindex
		this.statusreport(galleryid)
	},

	autorotate:function(galleryid){
		var config=stepcarouselsm.configholder[galleryid]
		if (config.$gallery.attr('_ismouseover')!="yes"){
			this.stepBy(galleryid, config.autostep.moveby)
		}
		config.steptimer=setTimeout(function(){stepcarouselsm.autorotate(galleryid)}, config.autostep.pause)
	},

	statusreport:function(galleryid){
		var config=stepcarouselsm.configholder[galleryid]
		var startpoint=config.currentpanelsm //index of first visible panelsm 
		var visiblewidth=0
		for (var endpoint=startpoint; endpoint<config.panelsmoffsets.length; endpoint++){ //index (endpoint) of last visible panelsm
			visiblewidth+=config.panelsmwidths[endpoint]
			if (visiblewidth>config.gallerywidth){
				break
			}
		}
		startpoint+=1 //format startpoint for user friendiness
		endpoint=(endpoint+1==startpoint)? startpoint : endpoint //If only one image visible on the screen and partially hidden, set endpoint to startpoint
		var valuearray=[startpoint, endpoint, config.panelsmwidths.length]
		for (var i=0; i<config.statusvars.length; i++){
			window[config.statusvars[i]]=valuearray[i] //Define variable (with user specified name) and set to one of the status values
			config.$statusobjs[i].text(valuearray[i]+" ") //Populate element on page with ID="user specified name" with one of the status values
		}
	},

	setup:function(config){
		//Disable Step Gallery scrollbars ASAP dynamically (enabled for sake of users with JS disabled)
		document.write('<style type="text/css">\n#'+config.galleryid+'{overflow: hidden;}\n</style>')
		jQuery(document).ready(function($){
			config.$gallery=$('#'+config.galleryid)
			config.gallerywidth=config.$gallery.width()
			config.offsets={left:stepcarouselsm.getoffset(config.$gallery.get(0), "offsetLeft"), top:stepcarouselsm.getoffset(config.$gallery.get(0), "offsetTop")}
			config.$bestsm=config.$gallery.find('.'+config.bestsmclass) //Find bestsm DIV that contains all the panelsms
			config.$panelsms=config.$gallery.find('.'+config.panelsmclass) //Find panelsm DIVs that each contain a slide
			config.panelsmbehavior.wraparound=(config.autostep && config.autostep.enable)? true : config.panelsmbehavior.wraparound //if auto step enabled, set "wraparound" to true
			config.onpanelsmclick=(typeof config.onpanelsmclick=="undefined")? function(target){} : config.onpanelsmclick //attach custom "onpanelsmclick" event handler
			config.onslideaction=(typeof config.onslide=="undefined")? function(){} : function(bestsmobj){$(bestsmobj).stop(); config.onslide()} //attach custom "onslide" event handler
			config.oninit=(typeof config.oninit=="undefined")? function(){} : config.oninit //attach custom "oninit" event handler
			config.bestsmoffset=stepcarouselsm.getCSSValue(config.$bestsm.css('marginLeft')) //Find length of bestsm DIV's left margin
			config.statusvars=config.statusvars || []  //get variable names that will hold "start", "end", and "total" slides info
			config.$statusobjs=[$('#'+config.statusvars[0]), $('#'+config.statusvars[1]), $('#'+config.statusvars[2])]
			config.currentpanelsm=0
			stepcarouselsm.configholder[config.galleryid]=config //store config parameter as a variable
			if (config.contenttype[0]=="ajax" && typeof config.contenttype[1]!="undefined") //fetch ajax content?
				stepcarouselsm.getremotepanelsms($, config)
			else
				stepcarouselsm.alignpanelsms($, config) //align panelsms and initialize gallery
		}) //end document.ready
		jQuery(window).bind('unload', function(){ //clean up
			if (config.panelsmbehavior.persist){
				stepcarouselsm.setCookie(window[config.galleryid+"persist"], config.currentpanelsm)
			}
			jQuery.each(config, function(ai, oi){
				oi=null
			})
			config=null
		})
	}
}


