(function($) {
  $.fn.ContentSlider = function(options)
  {
    var defaults = {
      leftBtn : 'ContentSlider/images/backArrow.png',
      rightBtn : 'ContentSlider/images/forwardArrow.png',
	  emptyBottomBtn : 'ContentSlider/images/Sample-Image.png',
	  selectedBottomBtn : 'ContentSlider/images/Sample-Image-Highlighted.png',
	  playBtn : 'ContentSlider/images/play.png',
	  pauseBtn : 'ContentSlider/images/pause.png',
      width : '900px',
      height : '400px',
	  //height: '350px',
	  totalHeight: '550px',
      speed : 400,
	  buttonSpeed : 100,
	  autoTransitionInterval : 1000,
      easing : 'easeOutQuad',
      textResize : false,
      IE_h2 : '26px',
      IE_p : '11px'
    }
    var defaultWidth = defaults.width;
    var o = $.extend(defaults, options);
    var w = parseInt(o.width);
    var n = this.children('.cs_wrapper').children('.cs_slider').children('.cs_article').length;
    var x = -1*w*n+w; // Minimum left value
    var p = parseInt(o.width)/parseInt(defaultWidth);
    var thisInstance = this.attr('id');
	var currentSlide = 0;
	var totalSlides = 0;
    var inuse = false; // Prevents colliding animations
	var isPlaying = true;
	var statusPressedOnce = false;

    function moveSlider(d, b, b1, id)
    {
	  var l = parseInt(b.siblings('.cs_wrapper').children('.cs_slider').css('left'));
      if(isNaN(l)) {
        var l = 0;
      }
      
	  //make the previous button empty
	  $(document).find('.cs_lower_buttons').find('img[identifier="' + currentSlide + '"]').attr('src', 'ContentSlider/images/nav' + currentSlide + 'unselected.png');
	  
	 //if the id is -1 (l/r button pressed), move by 1. otherwise, calculate how much the slider should move. 
	 var m; 
	 if(id==-1){
	    m = (d=='left') ? l-w: l+w;
		if(d=='left'){
	 		 if(currentSlide<totalSlides){
				currentSlide++;	  
			 }
		  }
	  	if(d=='right'){
			  if(currentSlide>0){
				currentSlide--;	  
			 }
		  }
	 }else{
		m = l + (w * (currentSlide-id));
		if(id>currentSlide){
			b=b1;	
		}
		 currentSlide=id;
	 }
	  
	 //change the proper button to selected 
	 $(document).find('.cs_lower_buttons').find('img[identifier="' + currentSlide + '"]').attr('src', 'ContentSlider/images/nav' + currentSlide + 'selected.png');
	 
	  if(m<=0&&m>=x) {
        b
          .siblings('.cs_wrapper')
            .children('.cs_slider')
              .animate({ 'left':m+'px' }, o.speed, o.easing, function() {
                inuse=false;
              });

        if(b.attr('class')=='cs_leftBtn') {
          var thisBtn = $('#'+thisInstance+' .cs_leftBtn');
          var otherBtn = $('#'+thisInstance+' .cs_rightBtn');
        } else {
          var thisBtn = $('#'+thisInstance+' .cs_rightBtn');
          var otherBtn = $('#'+thisInstance+' .cs_leftBtn');
        }
        if(m==0||m==x) {
          thisBtn.animate({ 'opacity':'0' }, o.buttonSpeed, o.easing, function() { thisBtn.hide(); });
        }
        if(otherBtn.css('opacity')=='0') {
          otherBtn.show().animate({ 'opacity':'1' }, { duration:o.buttonSpeed, easing:o.easing });
        }
      }
    }

    function vCenterBtns(b)
    {
      // Safari and IE don't seem to like the CSS used to vertically center
      // the buttons, so we'll force it with this function
      var mid = parseInt(o.height)/2;
      b
        .find('.cs_leftBtn img').css({ 'top':mid+'px', 'padding':0 }).end()
        .find('.cs_rightBtn img').css({ 'top':mid+'px', 'padding':0 });
    }

    return this.each(function() {
	  $(this)
        // Set the width and height of the div to the defined size
        .css({
          width:o.width,
          height:o.totalHeight
        })
        // Add the buttons to move left and right
        .prepend('<a href="#" class="cs_leftBtn"><img src="'+o.leftBtn+'" /></a>')
        .append('<a href="#" class="cs_rightBtn"><img src="'+o.rightBtn+'" /></a>')
        // Dig down to the article div elements
        .find('.cs_article')
          // Set the width and height of the div to the defined size
          .css({
            width:o.width,
            height:o.height
          })
          .end()
        // Animate the entrance of the buttons
        .find('.cs_leftBtn')
          .css('opacity','0')
          .hide()
          .end()
        .find('.cs_rightBtn')
          .hide()
          .animate({ 'width':'show' })
		//Add Circles to bottom
		.end()
		.append('<div class="cs_lower_buttons"></div>')
		.append('<div class="cs_status_buttons"></div>').end();
		
		//add a bottom button for each slide, showing the selected button image for the selected slide
		totalSlides = $(this).find('.cs_slider').find('div.cs_article').length;
		for(i=0; i<totalSlides; i++){
			var message = "" + i;
			if(i==currentSlide){
				//$(this).find('.cs_lower_buttons').append('<a href="#"><img src="' + o.selectedBottomBtn + '" class="button_img" identifier="' + i + '"/></a>');
				$(this).find('.cs_lower_buttons').append('<a href="#"><img src="ContentSlider/images/nav' + i + 'selected.png" class="button_img" identifier="' + i + '"/></a>');
				$(this).find('.cs_lower_buttons').find('img[identifier = "'+ i + '"]')
				.bind('click', {ident:i},function(event) {
        			if(inuse===false) {
          				inuse = true;
						moveSlider('left', leftBtn, rightBtn, event.data.ident);
        				}
        			return false; // Keep the link from firing
				});	
				
			}
			else{
				//alert(i);
				
				//$(this).find('.cs_lower_buttons').append('<a href="#"><img src="' + o.emptyBottomBtn + '" class="button_img" identifier="' + i + '"/></a>');
				$(this).find('.cs_lower_buttons').append('<a href="#"><img src="ContentSlider/images/nav' + i + 'unselected.png" class="button_img" identifier="' + i + '"/></a>');
				$(this).find('.cs_lower_buttons').find('img[identifier = "'+ i + '"]')
				.bind('click', {ident:i}, function(event) {
						if(inuse===false) {
          					inuse = true;
          					moveSlider('right', leftBtn, rightBtn, event.data.ident);
        				}
        			return false; // Keep the link from firing
				});
			}
			
		}
		  
		  

      // Resize the font to match the bounding box
      if(o.textResize===true) {
        var h2FontSize = $(this).find('h2').css('font-size');
        var pFontSize = $(this).find('p').css('font-size');
        $.each(jQuery.browser, function(i) {
          if($.browser.msie) {
             h2FontSize = o.IE_h2;
             pFontSize = o.IE_p;
          }
        });
        $(this).find('h2').css({ 'font-size' : parseFloat(h2FontSize)*p+'px', 'margin-left' : '66%' });
        $(this).find('p').css({ 'font-size' : parseFloat(pFontSize)*p+'px', 'margin-left' : '66%' });
        $(this).find('.readmore').css({ 'font-size' : parseFloat(pFontSize)*p+'px', 'margin-left' : '66%' });
      }

      // Store a copy of the button in a variable to pass to moveSlider()
      var leftBtn = $(this).children('.cs_leftBtn');
      leftBtn.bind('click', function() {
        if(inuse===false) {
          inuse = true;
          moveSlider('right', leftBtn, rightBtn, -1);
        }
        return false; // Keep the link from firing
      });

      // Store a copy of the button in a variable to pass to moveSlider()
      var rightBtn = $(this).children('.cs_rightBtn');
      rightBtn.bind('click', function() {
        if(inuse===false) {
          inuse=true;
          moveSlider('left', rightBtn, leftBtn, -1);
        }
        return false; // Keep the link from firing
      });
	  
	  //add play button image
	  $(this).find('.cs_status_buttons').append('<a href="#"><img src="' + o.playBtn + '" identifier="status"/></a>');
	  
	  //
	 	 var tid = setInterval(loopThrough, o.autoTransitionInterval);
		 function loopThrough(){
			 if(inuse===false) {
    	        inuse = true;
				var shiftVar = (currentSlide+1) % totalSlides;
				moveSlider('left', leftBtn, rightBtn, shiftVar);
			 }
		  };
	
	//if slider is hovered over, stop the animation, if not, start unless the play button has been pressed.
		  $("div.contentslider").hover(
  			function () {
				if(!statusPressedOnce){
					clearInterval(tid);
					$(this).find('.cs_status_buttons').find('img[identifier = "status"]').attr('src', o.playBtn);
					isPlaying=false;
				}
			  }, 
		  	function () {
   				/*if(!statusPressedOnce){
					tid = setInterval(loopThrough, o.autoTransitionInterval);
					$(this).find('.cs_status_buttons').find('img[identifier = "status"]').attr('src', o.pauseBtn);
					isPlaying=true;
				}*/
  			}
		);
		
		
		//set status button to control play state of the slider.
			$(this).find('.cs_status_buttons').find('img[identifier = "status"]')
				.bind('click',function(event) {
        			if(isPlaying) {
          				clearInterval(tid);
						$(document).find('.cs_status_buttons').find('img[identifier = "status"]').attr('src', o.playBtn);
						isPlaying=false;
						statusPressedOnce=true;
        			}else{
						tid = setInterval(loopThrough, o.autoTransitionInterval);
						$(document).find('.cs_status_buttons').find('img[identifier = "status"]').attr('src', o.pauseBtn);
						isPlaying=true;
						statusPressedOnce=true;
					}
        			return false; // Keep the link from firing
				});	
	  
		
				
	  

      vCenterBtns($(this)); // This is a CSS fix function.
    });
  }
})(jQuery)
