/**
 * TAO Software Gallery Slider for mobildat.at
 * @author roman@tao.at
 * @version 15032011
 */

// simple namespace for utility functions
var Tao = {
	user_agent : false,
	is_mobile_webkit : function() {
		if( !Tao.user_agent ) Tao.user_agent = navigator.userAgent.toLowerCase();
		if( Tao.user_agent.match(/(iphone|ipad|ipod)/i) || (Tao.user_agent.match(/android/i) && Tao.user_agent.match(/webkit/i)) || Tao.user_agent.match(/webkit/i)) {
			return true;
		} else {
			return false;
		}
	}
};

// only for mobile webkit (android / iphone / ipod touch / ipad)
if( Tao.is_mobile_webkit() && typeof myArray != "undefined" ) {
	// jquery no conflict
	(function($) {
		
		// document ready - init / late bindings
		$(function() {
			
			// first - remove all onclick handlers
			$('.thumbnails a, .thumbnails img').each(function() { $(this).attr('onclick', ''); });
			
			//
			// build gallery html / style
			//
			
			// add a container to the edit element
			var target = $('<div class="container"></div>');
			$('#edit').css({overflow:'hidden', padding:'0px'}).prepend(target);
			target.css({position:'relative', overflow:'hidden', height:'0px'});
			
	       	var closeButton = $('<input type="button" value="Schliessen" class="bty" style="float:left; margin-right: 20px; margin-top: 0; margin-bottom: 5px" />');            
            var prevButton  = $('<input id="backBtn" type="button" value="" class="btyr" style="margin-right: 20px; margin-top: 0; margin-bottom: 5px" />');
            var nextButton  = $('<input id="nextBtn" type="button" value="" class="btyl" style="margin-top: 0; margin-bottom: 5px" /> <div style="clear:both"></div>');
			
			$('#edit').prepend(nextButton).prepend(prevButton).prepend(closeButton).prepend($('<div style="height:5px"></div>'));
			                                            
			
			// for each loaded image
			var i = 0;
			$(myArray).each(function() {
				var imageurl = this.replace('resize(max)','resize(45%)');
				// preload the image
				if( i<5 ) {
				    var preload = new Image();
				    preload.src = imageurl;
				}
				// add an image container
				var image = $('<img rel="'+imageurl+'" />');
				// position the image with index*100% to the right (margin 1%)
				$(image).css({position:'absolute',top:'0px',left:(100*i+1)+'%',width:'98%',height:'auto'});
				// add the image to the container
				target.append(image);
				i = i+1;
				if( i < 3 ) $(image).attr('src', $(image).attr('rel'));
			});

			//
			// touch handling
			//

			// state variables
			var base_x = 0;
			var start_offset_x = 0;
			var current_x = 0;
			var current_offset_x = 0;
			var starttime = 0;
			var elements = target.find('img');
			var do_snap = true;					// snap to edge on touchend
			var tap_timeout = 100;				// timeout to detect a tap
			var snap_speed = '.5s';			// speed of the snap animation
			var element_width = 0;
			var last_ci = 0;

			var handle_loading = function(ci) {
				ci = Math.abs(ci);
				var i = 0;
				var images = $(target).find('img');
				var count = images.length;
				images.each(function() {
					var img = $(this);
					console.log(ci);
					if( (i+1 == count && ci == 0) || i+1 == ci || i-1 == ci || i == ci) {
						img.attr('src', img.attr('rel'));
					} else {
						img.attr('src', '');
					}
					i = i+1;
				});
			};
			
			// touch start - just set the current states
			$(target).bind('touchstart', function() {
				elements.css('WebkitTransition', ''); // reset transition
				starttime = (new Date()).getTime();
				base_x = event.targetTouches[0].pageX;
				start_offset_x = current_offset_x;
				handle_loading(Math.round(current_offset_x/element_width));
				return false;
			});
			// touchmove - calculate delta, update state and perform transition
			$(target).bind( 'touchmove', function() {
				current_x = event.targetTouches[0].pageX;
		   		elements.css('WebkitTransform', "translate3d("+(current_offset_x + (current_x-base_x))+'px,0px,0px)');
		   		var current_ci = Math.round(current_offset_x/element_width);
		   		if( current_ci != last_ci ) handle_loading(current_ci);
		   		last_ci = current_ci;
				return false;
  		    });
			
			$(target).bind( 'touchend', function() {
				if( !do_snap ) return false; // no snap - we are done here
				
				// set some event parameters
				event.offsetX = current_x - base_x;
				// too fast - snap back
				if( ((new Date()).getTime() - starttime) < tap_timeout ) {
					current_offset_x = start_offset_x;
					elements.css('WebkitTransitionProperty', 'transform');
					elements.css('WebkitTransitionDuration', snap_speed);
					elements.css('WebkitTransform', "translate3d("+current_offset_x+'px,0px,0px)');
					return false;
				} else {
					current_offset_x = current_offset_x + event.offsetX;
					var dx = Math.abs(current_offset_x % element_width);
					if( Math.abs(event.offsetX) > Math.abs(event.offsetY) && event.offsetX > 160 ) $(container).trigger('back');
					current_offset_x += event.offsetX < 0 ? (element_width - dx)*-1 : dx;
					current_offset_x = Math.max(element_width*(elements.size()-1)*-1, Math.min(current_offset_x, 0));
				}
				elements.css('WebkitTransitionProperty', 'transform');
				elements.css('WebkitTransitionDuration', snap_speed);
				elements.css('WebkitTransform', "translate3d("+current_offset_x+'px,0px,0px)');
				handle_loading(Math.round(current_offset_x/element_width));
				return false;
			});
			
			//
			// init
			//
			
			// click on thumbnails -> slide to selected image
			$('.thumbnails a').click(function() {
				// show the container (just to be sure)
				target.parent().css({display:'block'});
				// get the clicked element's index
				var sel_idx = $(this).index('.thumbnails a');
				// get the corresponding image object
				var sel_img = target.find('img:eq('+sel_idx+')');
				// just to be sure - load the first image if selection failed
				if( sel_img.length <= 0 ) sel_img = target.find('img:first');
				// animate the height of the container to the selected image
				var h = sel_img.height()
				if( h<220 ) h=220;
				target.parent().stop().animate({height:(h+30)+'px'});
				target.stop().animate({height:h+'px'});
				// and scroll to the selected image
				var w = element_width = target.outerWidth();
				target.find('img').css('WebkitTransitionProperty', 'transform');
				target.find('img').css('WebkitTransitionDuration', '1s');
				current_offset_x = sel_idx*w*-1;
				handle_loading(Math.round(current_offset_x/element_width));
				target.find('img').css('WebkitTransform', "translate3d("+current_offset_x+"px,0px,0px)");
				return false;
			});
			
			//
			// button handling
			//
			
			// optionally the touchstart event could be used to speed up the response time
			
			// close button click -> size to 0px
			closeButton.click(function() {
				target.stop().animate({height:'0px'});
				target.parent().stop().animate({height:'0px'});
				return false;
			});

			// next button -> slide one image to the right -> on last image, slide back to first image
			nextButton.click(function() {
				current_offset_x = current_offset_x - element_width;
				if( current_offset_x < -1* Math.max(0, myArray.length-1) * element_width ) current_offset_x = 0;
				target.find('img').css('WebkitTransitionProperty', 'transform');
				target.find('img').css('WebkitTransitionDuration', '1s');
				target.find('img').css('WebkitTransform', "translate3d("+current_offset_x+"px,0px,0px)");
				handle_loading(Math.round(current_offset_x/element_width));
				return false;
			});
			
			// previous button -> slide one image to the left -> on first image, slide back to last image
			prevButton.click(function() {
				current_offset_x = current_offset_x + element_width;
				if( current_offset_x > 0 ) current_offset_x = -1 * element_width * Math.max(0, myArray.length-1);
				target.find('img').css('WebkitTransitionProperty', 'transform');
				target.find('img').css('WebkitTransitionDuration', '1s');
				target.find('img').css('WebkitTransform', "translate3d("+current_offset_x+"px,0px,0px)");
				handle_loading(Math.round(current_offset_x/element_width));
				return false;
			});
		
		}); // -document ready

	})(jQuery); // -jquery no conflict

} // -is mobile webkit