//** Featured Content Slider script- © Dynamic Drive DHTML code library (http://www.dynamicdrive.com)

////Ajax related settings
var csbustcachevar=0 //bust potential caching of external pages after initial Ajax request? (1=yes, 0=no)
var csloadstatustext="<img src='siteready/loading.gif' /> Requesting content..." //HTML to indicate Ajax page is being fetched
var csexternalfiles=[] //External .css or .js files to load to style the external content(s), if any. Separate multiple files with comma ie: ["cat.css", dog.js"]

var enablepersist=true
var slidernodes=new Object() //Object array to store references to each content slider's DIV containers (<div class="contentdiv">)
var csloadedobjects="" //Variable to store file names of .js/.css files already loaded (if Ajax is used)


function ContentSlider(sliderid, autorun, transitiontime, customPaginateText, customNextText, customPreviousText){
	var slider=$(sliderid)
	var transition=1000
	
	if (typeof customPaginateText!="undefined" && customPaginateText!="") //Custom array of pagination links text 
		slider.paginateText=customPaginateText
	if (typeof customNextText!="undefined" && customNextText!="") //Custom HTML for "Next" link
		slider.nextText=customNextText
	if (typeof customPreviousText!="undefined" && customPreviousText!="") //Custom HTML for "Previous" link
		slider.prevText=customPreviousText
	if (typeof transitiontime!="undefined" && transitiontime!="") // Custom transition time
		transition=transitiontime
		
	slidernodes[sliderid]=[] //Array to store references to this content slider's DIV containers (<div class="contentdiv">)
	ContentSlider.loadobjects(csexternalfiles) //Load external .js and .css files, if any
	
	
// Finds all contentdiv divs and adds them to the slidernodes array	
	$$('div.contentdiv').each(function(el){
			slidernodes[sliderid].push(el) 
			//If get this DIV's content via Ajax (rel attr contains path to external page)
			if (typeof el.getAttribute("rel")=="string") 
				ContentSlider.ajaxpage(el.getAttribute("rel"), el)
	});
	
	
	
// Build the page, prev and next links	
	ContentSlider.buildpagination(sliderid, transition)
	
	var loadfirstcontent=true
	if (enablepersist && getCookie(sliderid)!=""){ //if enablepersist is true and cookie contains corresponding value for slider
		var cookieval=getCookie(sliderid).split(":") //process cookie value ([sliderid, int_pagenumber (div content to jump to)]
		if ($(cookieval[0])!=null && typeof slidernodes[sliderid][cookieval[1]]!="undefined"){ //check cookie value for validity
			ContentSlider.turnpage(cookieval[0], parseInt(cookieval[1])) //restore content slider's last shown DIV
			loadfirstcontent=false
		}
	}
	if (loadfirstcontent==true) //if enablepersist is false, or cookie value doesn't contain valid value for some reason (ie: user modified the structure of the HTML)
		ContentSlider.turnpage(sliderid, 0, transition) //Display first DIV within slider
	if (typeof autorun=="number" && autorun>0) {//if autorun parameter (int_miliseconds) is defined, fire auto run sequence
	
			//cancel auto run sequence on mouseover and restarts it onmouseout
			slider.onmouseover=function(){ 
			if (typeof window[sliderid+"timer"]!="undefined")
				clearTimeout(window[sliderid+"timer"])
			}
			
			slider.onmouseout=function(){ 
			if (typeof window[sliderid+"timer"]!="undefined")
				window[sliderid+"timer"]=setTimeout(function(){ContentSlider.autoturnpage(sliderid, autorun, transition)}, autorun)
			}


		window[sliderid+"timer"]=setTimeout(function(){ContentSlider.autoturnpage(sliderid, autorun, transition)}, autorun)}
}


ContentSlider.buildpagination=function(sliderid, transition){
	var slider=$(sliderid)
	var paginatediv=$("paginate-"+sliderid) //reference corresponding pagination DIV for slider
	var pcontent=""
	for (var i=0; i<slidernodes[sliderid].length; i++) //For each DIV within slider, generate a pagination link
		pcontent+='<span class="numberlink"><a href="#" onClick=\"ContentSlider.turnpage(\''+sliderid+'\', '+i+','+transition+'); return false\">'+(slider.paginateText? slider.paginateText[i] : i+1)+'</a></span>'


// Gets all images with the class thumbnail and puts it in the thumbnails div		
		var thumbnailslist=""		
		var i2 = 0			

			$$('img.thumbnail').each(function(el){
				thumbnailslist+='<a href="#" onClick=\"ContentSlider.turnpage(\''+sliderid+'\', '+i2+', '+transition+'); return false\">'+'<img src="'+el.src+'" />'+'</a>';
				i2++
			});
			
		if (thumbnailslist!="") {
			$('thumbnails-'+sliderid).setHTML(thumbnailslist);
		}

		
		pcontent+='<a href="#" style="font-weight: bold;" onClick=\"ContentSlider.turnpage(\''+sliderid+'\', parseInt(this.getAttribute(\'rel\')), '+transition+'); return false\">'+(slider.prevText || "Prev")+'</a>'

		pcontent+='<a href="#" style="font-weight: bold;" onClick=\"ContentSlider.turnpage(\''+sliderid+'\', parseInt(this.getAttribute(\'rel\')), '+transition+'); return false\">'+(slider.nextText || "Next")+'</a>'
	
	paginatediv.innerHTML=pcontent
	
	paginatediv.onclick=function(){ //cancel auto run sequence (if defined) when user clicks on pagination DIV
	if (typeof window[sliderid+"timer"]!="undefined")
		clearTimeout(window[sliderid+"timer"])
	}
	
}


ContentSlider.turnpage=function(sliderid, thepage, transition){
	var paginatelinks=document.getElementById("paginate-"+sliderid).getElementsByTagName("a") //gather pagination links
	var cookieval=getCookie(sliderid).split(":") //process cookie value ([sliderid, int_pagenumber (div content to jump to)]

	for (var i=0; i<slidernodes[sliderid].length; i++){ //For each DIV within slider
		paginatelinks[i].className="" //empty corresponding pagination link's class name

// Loops through all divs except the last visible div and hides them
		if (parseInt(cookieval[1])!=i){
			slidernodes[sliderid][i].style.display="none"
			slidernodes[sliderid][i].style.visibility="hidden" 
		}

}	
	paginatelinks[thepage].className="selected" //for selected DIV, set corresponding pagination link's class name

// Checks to see if there is a cookie, if so it hides the last visible div unless it is the same div then it does nothing		
if (cookieval!=""){	
	if(parseInt(cookieval[1]) != thepage) {
		var hidelast = new Fx.Style($(slidernodes[sliderid][parseInt(cookieval[1])]), 'opacity', {duration: transition}).addEvent('onComplete', function() {
	
			var shownew = new Fx.Style($(slidernodes[sliderid][thepage]), 'opacity', {duration: transition});
			slidernodes[sliderid][parseInt(cookieval[1])].style.display="none"; // sets last visible div to display none 	
			slidernodes[sliderid][thepage].style.opacity=0 //show selected DIV		
			slidernodes[sliderid][thepage].style.display="block" //show selected DIV		
	
			shownew.start(0,1);
		});
		hidelast.start(1,0);
	}
} else {

// Since there is no cookie this is the first run of the script so it just shows the seleced div		
		slidernodes[sliderid][thepage].style.opacity=0 //show selected DIV		
		slidernodes[sliderid][thepage].style.display="block" //show selected DIV		
		$(slidernodes[sliderid][thepage]).effect('opacity', {duration: transition}).start(0,1);
}	
	
	//Set "Previous" pagination link's (last link within pagination DIV) "rel" attribute to the previous DIV number to show
	var arrlength = paginatelinks.length-3
	paginatelinks[paginatelinks.length-2].setAttribute("rel", theprevpage=(arrlength<arrlength+thepage)? thepage-1 : paginatelinks.length-3)
	
	//Set "Next" pagination link's (last link within pagination DIV) "rel" attribute to the next DIV number to show
	paginatelinks[paginatelinks.length-1].setAttribute("rel", thenextpage=(thepage<arrlength)? thepage+1 : 0)
	
	if (enablepersist)
		setCookie(sliderid, sliderid+":"+thepage)
}


ContentSlider.autoturnpage=function(sliderid, autorunperiod, transition){
	var paginatelinks=document.getElementById("paginate-"+sliderid).getElementsByTagName("a") //Get pagination links
	var nextpagenumber=parseInt(paginatelinks[paginatelinks.length-1].getAttribute("rel")) //Get page number of next DIV to show
	ContentSlider.turnpage(sliderid, nextpagenumber, transition) //Show that DIV
	window[sliderid+"timer"]=setTimeout(function(){ContentSlider.autoturnpage(sliderid, autorunperiod, transition)}, autorunperiod)
}


function getCookie(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 ""
}


function setCookie(name, value){
	document.cookie = name+"="+value
}

////////////////Ajax Related functions //////////////////////////////////

ContentSlider.ajaxpage=function(url, thediv){
	var page_request = false
	var bustcacheparameter=""
	if (window.XMLHttpRequest) // if Mozilla, Safari etc
		page_request = new XMLHttpRequest()
	else if (window.ActiveXObject){ // if IE
		try {
		page_request = new ActiveXObject("Msxml2.XMLHTTP")
		} 
		catch (e){
		try{
		page_request = new ActiveXObject("Microsoft.XMLHTTP")
		}
		catch (e){}
		}
	}
	else
		return false
	thediv.innerHTML=csloadstatustext
	page_request.onreadystatechange=function(){
		ContentSlider.loadpage(page_request, thediv)
	}
	if (csbustcachevar) //if bust caching of external page
		bustcacheparameter=(url.indexOf("?")!=-1)? "&"+new Date().getTime() : "?"+new Date().getTime()
	page_request.open('GET', url+bustcacheparameter, true)
	page_request.send(null)
}

ContentSlider.loadpage=function(page_request, thediv){
	if (page_request.readyState == 4 && (page_request.status==200 || window.location.href.indexOf("http")==-1))
		thediv.innerHTML=page_request.responseText
}

ContentSlider.loadobjects=function(externalfiles){ //function to load external .js and .css files. Parameter accepts a list of external files to load (array)
	for (var i=0; i<externalfiles.length; i++){
		var file=externalfiles[i]
		var fileref=""
		if (csloadedobjects.indexOf(file)==-1){ //Check to see if this object has not already been added to page before proceeding
			if (file.indexOf(".js")!=-1){ //If object is a js file
				fileref=document.createElement('script')
				fileref.setAttribute("type","text/javascript");
				fileref.setAttribute("src", file);
			}
			else if (file.indexOf(".css")!=-1){ //If object is a css file
				fileref=document.createElement("link")
				fileref.setAttribute("rel", "stylesheet");
				fileref.setAttribute("type", "text/css");
				fileref.setAttribute("href", file);
			}
		}
		if (fileref!=""){
			document.getElementsByTagName("head").item(0).appendChild(fileref)
			csloadedobjects+=file+" " //Remember this object as being already added to page
		}
	}
}
