
$(document).ready(function(){
	
	// global vars 
	var curIndex = 0;
	var slidesLength = 	$("#slides li").length;
	var timer = null;
	var imgLoad = [];
	
	function resetTimer() {
		if(timer) {
			clearTimeout(timer);
			timer = null;
		}
		timer = setTimeout(function(){
			toggleSlide(curIndex, 1)
		},7000)
	}
	
	function setSelectedState() {
		//set selected state for list items
		$("#slidenum li a").each(function(){
			if(parseInt($(this).attr("rel")) == curIndex) {
				$(this).parent("li").addClass("selected");
			} else {
				$(this).parent("li").removeClass("selected");
			}
		})
	}
	
	function toggleSlide(passIndex, dir){
		// handle index (currentSlide)
		if(dir == 1) {
			if(passIndex  == slidesLength - 1) {
				curIndex = 0;
			} else {
				curIndex = passIndex + 1;
			}
		} else if (dir == -1) {
			if (passIndex == 0) {
				curIndex = slidesLength -1;
			} else {
				curIndex = passIndex - 1;
			}
		} else {
			// works
			curIndex = passIndex;
		}
		
        // fade in fade out
		$("#slides li").not(curIndex).fadeOut(1000);
		$("#slides li").eq(curIndex).fadeIn(1000);

		// set title text
		origTitle = $('#slides li a').eq(curIndex).attr('title')
		$("#thumb_title").html(origTitle);
		
		resetTimer();
		setSelectedState();
		return;
	}
	
	
	

	

	// initialize
	
	// create slide_num ul and thumb_title
	$("#rotator").append("<ul id='slidenum'></ul>")
	$("#rotator").append("<span id='thumb_title'>" + $("#slides li a ").eq(0).attr('title') + "</span>")
	
	
	$("#slides li").each(function(i){
		
		//preload all images using dom because jquery returning undefined
		imgLoad[i] = new Image();
		imgLoad[i].src = document.getElementById("slides").getElementsByTagName("img")[i].src
		
		// ceate lis to navigate  
		$("#slidenum").append("<li><a href='#' class='slide_nav' rel='" + i +"' title='"+ $(this).children('a').attr('title') +"'></a></li>")
		
		// set display to none all lis execpt the first
		if(i != 0) {
			$(this).css({display:"none"})
		}
		
	})
	
	
	// initial timer instance
	resetTimer();
	
	setSelectedState();
	
	// create previous and next button and handle events
	$("#slidenum").prepend("<li><a id='previous_button' href='#' title='previous'></a></li>").append("<li ><a id='next_button' href='#' title='next'></a></li>");
	
	$("#previous_button").click(function(e) {
		toggleSlide(curIndex, -1);
		resetTimer();
		e.preventDefault();
		return false;
	})
	
	$("#next_button").click(function(e) {
		toggleSlide(curIndex, 1);
		resetTimer();
		e.preventDefault();
		return false;
	})
		

	$("#slidenum a").not('#next_button, #previous_button').click(function(e){
		resetTimer();
		toggleSlide(parseInt($(this).attr("rel")));
		e.preventDefault();
	}).hover(function(){
		$("#thumb_title").html($(this).attr("title"))
	}, function(){
		$("#thumb_title").html(origTitle);
	})	
		
})
