﻿jQuery.fn.extend({
	slideShow : function (touchFlag) {
		options={
			targetStageName : ".stage",
			targetPartsName : ".parts",
			targetUIName : ".ui",
			speed : 500,
			easing : "easeOutQuad",
			timer :7000
		};
		var _self=$(this);
		var stage =$(options.targetStageName,_self);
		var parts =$(options.targetPartsName,stage);
		var ui= $(options.targetUIName,_self);
		
		//Set Default State of each portfolio piece
		ui.show();
		$("a:first",ui).addClass("active");
		//
		//Get size of images, how many there are, then determin the size of the image reel.
		var objWidth = stage.width();
		var objSum   = $(".reel",stage).size();
		var objSumWidth = objWidth * objSum;
		
		//Adjust the image reel to its new size
		parts.css({'width' : objSumWidth});
		
		//Paging + Slider Function
		rotate = function () {	
			var triggerID = $active.attr("rel") - 1; //Get number of times to slide
			var objPosition = triggerID * objWidth; //Determines the distance the image reel needs to slide
			$("a",ui).removeClass('active'); //Remove all active class
			$active.addClass('active'); //Add active class (the $active is declared in the rotateSwitch function)
			
			//Slider Animation
			if(touchFlag==1){
				stage.flickable('select', triggerID);
			}else{
				parts.animate({left: -objPosition},options.speed,options.easing);
			}
		};
		
		//Rotation + Timing Event
		rotateSwitch = function () {
			play = setInterval(function(){ //Set timer - this will repeat itself every 3 seconds
				$active = $('a.active', ui).next();
				if ( $active.length === 0) { //If paging reaches the end...
					$active = $('a:first', ui); //go back to first
				}
				rotate(); //Trigger the paging and slider function
			}, options.timer); //Timer speed in milliseconds (3 seconds)
		};
		rotateSwitch(); //Run function on launch
	
		if(touchFlag==1){
			//タッチパネル対応の場合
			stage.flickable({section: '.reel', elasticConstant: 0.2, friction: 0.5});
			stage.flickable({
				dragStart : function(event) {
				},
				dragStop : function(event) {
				},
				change : function(event, flickui) {
					var fid=flickui.newSection.attr("rel");
					$active = $('a:eq('+(fid-1)+')', ui);
					//
					$("a",ui).removeClass('active');
					$active.addClass('active');
					clearInterval(play);
					rotateSwitch();
				}
			});
		}
			
		//On Hover
		parts.hover(function() {
			clearInterval(play); //Stop the rotation
		}, function() {
			rotateSwitch(); //Resume rotation
		});	
	
		//On Click
		$("a",ui).click(function() {						
			$active = $(this); //Activate the clicked paging
			//Reset Timer
			clearInterval(play); //Stop the rotation
			rotate(); //Trigger rotation immediately
			rotateSwitch(); // Resume rotation
			return false; //Prevent browser jump to link anchor
		});	
	}
});	


