/* ----------------------------------
 *
 * 2011-12-05 12:16 PM
 *
 *
 * Loosely based on:
 * jQuery Timelinr 0.9.4
 * ©2011 CSSLab.cl
 * free for any use, of course... :D
 * instructions: http://www.csslab.cl/2011/08/18/jquery-timelinr/
 *
 *
 * Edit: added touchscreen
 *       added automatic hiding of controllers
 *
---------------------------------- */

jQuery.fn.sliderControls = function(options){
	// default plugin settings
	settings = jQuery.extend({
		orientation: 				    'horizontal',		        // value: horizontal | vertical, default to horizontal
		containerDiv: 				  '.slider .container',	  // value: any HTML tag or #id, default to #timeline
		issuesDiv: 					    '.slider .slides',      // value: any HTML tag or #id, default to #issues
		issueSelector:          '.slide',               // value: any HTML tag or #id, default to nothing
		issuesSpeed:            200,				            // value: integer between 100 and 1000 (recommended), default to 200 (fast)
		issuesTransparency:     0.2,				            // value: integer between 0 and 1 (recommended), default to 0.2
		issuesTransparencySpeed:500,				            // value: integer between 100 and 1000 (recommended), default to 500 (normal)
		issuesPerSlide:         1,                      // value: integer between 1 and N, default to 1
		prevButton: 				    '#prev',			          // value: any HTML tag or #id, default to #prev
		nextButton: 				    '#next',			          // value: any HTML tag or #id, default to #next
		buttonHiddenClass:      'hidden',               // value: any class, default to hidden
		atEndGoToStart:         false,                  // value: true | false, default to false
		issueSelectedClass:     'slide-active',         // value: any class, default to active 
		arrowKeys: 					    true,			              // value: true | false, default to false
		startAt: 					      1,					            // value: integer, default to 1 (first)
		autoPlay: 					    false,			            // value: true | false, default to false
		autoPlayDirection: 			'forward',			        // value: forward | backward, default to forward
		autoPlayPause: 				  2000,				            // value: integer (1000 = 1 seg), default to 2000 (2segs)
		mouseWheel:             false,                  // value: true | false, default to false
		hashCheck:              false,                  // value: true | false, default to false
		hashData:               'data-hash',            // value: any attribute, default to data-hash
		resizeContainerOnChange:false,                  // value: true | false, default to false
		after:                  function(){}            // value: callback function, default to void function
	}, options);

	$(function(){
		var howManyIssues = $(settings.issuesDiv+' > li' + settings.issueSelector).length;
		var howManySlides = parseInt(howManyIssues/settings.issuesPerSlide);
		var currentIssue = $(settings.issuesDiv).find(' > li.' + settings.issueSelector + settings.issuesSelectedClass);
		var widthContainer = $(settings.containerDiv).width();
		var widthIssues = $(settings.issuesDiv).width();
		var widthIssue = $(settings.issuesDiv+' > li' + settings.issueSelector).width()*settings.issuesPerSlide;
		//var diaporamaIssue = 1;
		//var deactivateStartAt = false;
		
		// set positions!
    //$(settings.issuesDiv).width(widthContainer*howManyIssues);
    
    // set positions!
    $(settings.issuesDiv).width(widthContainer*howManyIssues);
    if(howManyIssues%settings.issuesPerSlide != 0)
		  howManySlides++;
		$(settings.issuesDiv).width(widthContainer*howManySlides);
    
    //Hash startAt and event handlers
    if (settings.hashCheck) {
      $(window).bind('hashchange', function() {
        goToSlide(getCurrentHashPosition());
      });
      if (window.location.hash) settings.startAt = getCurrentHashPosition()+1;
    }

    //startAt
    if(settings.startAt > 1 && settings.startAt <= howManySlides) {
      goToSlide(settings.startAt-1);
    } else
      goToSlide(0);
    

		$(settings.nextButton).bind('click', function(event){
			event.preventDefault();
			var currentPositionSlides = parseInt($(settings.issuesDiv).css('marginLeft').substring(0,$(settings.issuesDiv).css('marginLeft').indexOf('px')));
			var currentSlideIndex = currentPositionSlides/widthContainer;
			if(currentPositionSlides <= -(widthContainer*howManySlides-(widthContainer))) {
				if(settings.atEndGoToStart){
				    $(settings.issuesDiv).animate({'marginLeft':0},{queue:false, duration:settings.issuesSpeed});
				    hideShowButtons( 0 , howManySlides);
				} else {
				    $(settings.issuesDiv).stop();
				}
				//$(settings.datesDiv+' li:last-child a').click();
			} else {
				if (!$(settings.issuesDiv).is(':animated')) {
					$(settings.issuesDiv).animate({'marginLeft':currentPositionSlides-widthContainer},{queue:false, duration:settings.issuesSpeed});
					hideShowButtons(-(currentSlideIndex-1), howManySlides);
				}
			}
		});

		$(settings.prevButton).click(function(event){
			event.preventDefault();
			var currentPositionSlides = parseInt($(settings.issuesDiv).css('marginLeft').substring(0,$(settings.issuesDiv).css('marginLeft').indexOf('px')));
			var currentSlideIndex = currentPositionSlides/widthContainer;
			if(currentPositionSlides >= 0) {
				if(settings.atEndGoToStart){
				    $(settings.issuesDiv).animate({'marginLeft':-(howManySlides-1)*widthIssue},{queue:false, duration:settings.issuesSpeed});
				    hideShowButtons( howManySlides-1, howManySlides);
				} else {
				    $(settings.issuesDiv).stop();
				}
			} else {
				if (!$(settings.issuesDiv).is(':animated')) {
					$(settings.issuesDiv).animate({'marginLeft':currentPositionSlides+widthContainer},{queue:false, duration:settings.issuesSpeed});
					hideShowButtons(-(currentSlideIndex+1), howManySlides);
				}
			}
		});
		
		function goToSlide (slideIndex) {
      if (slideIndex == -1)
        return false;
      if(settings.orientation == 'horizontal') {
  				$(settings.issuesDiv).animate({'marginLeft':-widthIssue*slideIndex},{queue:false, duration:settings.issuesSpeed});
  			} else if(settings.orientation == 'vertical') {
  				$(settings.issuesDiv).animate({'marginTop':-heightIssue*slideIndex},{queue:false, duration:settings.issuesSpeed});
  			}
  			hideShowButtons(slideIndex, howManySlides);
    }
		
		function hideShowButtons(currentIndex, howMany, isNext) {
			if(!settings.atEndGoToStart){
    		//hide prev, next button
    		if (currentIndex == 0)
    		  $(settings.prevButton).addClass(settings.buttonHiddenClass);
        else
          $(settings.prevButton).removeClass(settings.buttonHiddenClass);
                
    		if (currentIndex == howMany-1)
    		  $(settings.nextButton).addClass(settings.buttonHiddenClass);
    		else
    		  $(settings.nextButton).removeClass(settings.buttonHiddenClass);
    		  
			} else {
			    $(settings.nextButton).removeClass(settings.buttonHiddenClass);
			    $(settings.prevButton).removeClass(settings.buttonHiddenClass);
			}
      
			//add selected class
			$('.' + settings.issueSelectedClass).removeClass(settings.issueSelectedClass);
			$(settings.issuesDiv).find('> li' + settings.issueSelector).eq(currentIndex).addClass(settings.issueSelectedClass);
			
			//resize container
			if(settings.resizeContainerOnChange) {
        $(settings.containerDiv).height($('.' + settings.issueSelectedClass).outerHeight(true));
			}
			
			//callback
      if (typeof settings.after == "function")
        settings.after.call(this);

			//set hash
			if(settings.hashCheck) {
        var newHash = $('.' + settings.issueSelectedClass).attr(settings.hashData);
        if (typeof newHash != 'undefined'){
          window.location.hash = newHash;
          //return false;
        }
			}

    }	
		
		function getCurrentHashPosition () {
      var hash = window.location.hash.substring(1);
      var position = -1;
      $(settings.issuesDiv+' > li' + settings.issueSelector).each( function(index){
        if ($(this).attr(settings.hashData) == hash)
          position = index;
      });
      return position;
    }
    
		
		// keyboard navigation
		if(settings.arrowKeys) {
			$(document).keydown(function(event){
				if (event.keyCode == 39) { 
			       $(settings.nextButton).click();
			    }
				if (event.keyCode == 37) { 
			       $(settings.prevButton).click();
			    }
			});
		}
		
		// mousewheel navigation
        /*if (settings.mouseWheel==true) {
            var mousewheelEvent = (/Firefox/i.test(navigator.userAgent)) ? "DOMMouseScroll" : "mousewheel";
            $(settings.containerDiv).bind(mousewheelEvent, function(e) {
                e.preventDefault();
                if (!$(settings.containerDiv).is(':animated')) {
                    e = e ? e : window.event;
                    if(settings.orientation=='horizontal') {
                        var wheelData = e.detail ? e.detail * -1 : e.wheelDelta / 40,
                            target = (wheelData < 0) ? $(settings.prevButton).click() : $(settings.nextButton).click();
                    } else if(settings.orientation=='vertical') {
                        var wheelData = e.detail ? e.detail * -1 : e.wheelDelta / 40,
                            target = (wheelData < 0) ? $(settings.nextButton).click() : $(settings.prevButton).click();
                    }
                    
                }
            });
        }*/
        
    //touch gestures
		var startX;
        var startY;
        var isMoving = false;
        var min_move_x = 20;
        var min_move_y = 20;
		
		if ('ontouchstart' in document.documentElement) {
            $(settings.containerDiv).bind('touchmove', function(e) {
                this.addEventListener('touchstart', onTouchStart, false);
            });
		}

        function cancelTouch() {
            this.removeEventListener('touchmove', onTouchMove);
            startX = null;
            isMoving = false;
        }	
   	 
        function onTouchMove(e) {
            
            if(isMoving) {
                var x = e.touches[0].pageX;
                var y = e.touches[0].pageY;
                var dx = startX - x;
                var dy = startY - y;
                if((Math.abs(dx) >= min_move_x)&&(settings.orientation == 'horizontal')) {
                   e.preventDefault();
	               cancelTouch();
	               if(dx > 0) {
	                   $(settings.nextButton).click();
	                   
	               } else {
	                   $(settings.prevButton).click();
                   }
	            } else if((Math.abs(dy) >= min_move_y)&&(settings.orientation == 'vertical')) {
	               e.preventDefault();
		           cancelTouch();
		           if(dy > 0) {
		              $(settings.nextButton).click();
		           } else {
		    		  $(settings.prevButton).click();
		           }
		        }
    		 }
        }
    	 
        function onTouchStart(e)
        {	 
            if (e.touches.length == 1) {
                startX = e.touches[0].pageX;
                startY = e.touches[0].pageY;
                isMoving = true;
                this.addEventListener('touchmove', onTouchMove, false);
            }
        }

    // autoPlay
		if(settings.autoPlay) { 
			setInterval("autoPlay()", settings.autoPlayPause);
		}
		
	});

};


// autoPlay
function autoPlay(){
	if(settings.autoPlayDirection == 'forward') {
		$(settings.nextButton).click();
	} else if(settings.autoPlayDirection == 'backward') {
		$(settings.prevButton).click();
	}
}
