/**
* © 2010-2020, 11Eleven Development, LLC (http://www.11elevendevelopment.com)
* All Rights Reserved
*
* Author: Paul Furiani
*
**/

(function($){

	var methods = {
		init : function(settings) {
			id = $(this).attr('id');
			//$(this).find('.slider11-group').hide();
			current = $(this).find('.slider11-group:first').addClass('slider11-current-group');
//			$(this).find('.slider11-group:first').addClass('slider11-current-group');
			//$(this)..$OuterDiv = $('<div></div>')
			//    .hide()
			//    .append($('<table></table>')
			//        .attr({ cellSpacing : 0 })
			//        .addClass("text")
			//    )
			//;
			$(this).prepend($('<div class="slider11-controls"></div>')
					.append( $('<a href="Javascript:void(0);" rel="prev" class="slider11-prev">Prev Project</a>').click(function() {
						current = $('#' + id).find('.slider11-current-group');
						prev = current.prev();
						if(prev.length > 0) {
							$('#' + id).smoothDivScroll("stopAutoScroll");
							prev.addClass('slider11-current-group');
							$('#' + id).smoothDivScroll("moveToElement", "first");
							$('#' + id).data("scrollable").prev();
							current.removeClass('slider11-current-group');
							$('#' + id).smoothDivScroll("recalculateScrollableArea");
							$('#' + id).smoothDivScroll("startAutoScroll");
							$('#' + id).find('.slider11-controls .slider11-next').show();
							if(prev.prev().length > 0) {
								$('#' + id).find('.slider11-controls .slider11-prev').show();
							} else {
								$('#' + id).find('.slider11-controls .slider11-prev').hide();
							}
						}
					}))
					.append($('<a href="Javascript:void(0);" rel="next" class="slider11-next">Next Project</a>').click(function() {
						current = $('#' + id).find('.slider11-current-group');
						next = current.next();
						if(next.length > 0) {
							$('#' + id).smoothDivScroll("stopAutoScroll");
							next.addClass('slider11-current-group');
							$('#' + id).smoothDivScroll("moveToElement", "first");
							$('#' + id).data("scrollable").next();
							current.removeClass('slider11-current-group');
							$('#' + id).smoothDivScroll("recalculateScrollableArea");
							$('#' + id).smoothDivScroll("startAutoScroll");
							$('#' + id).find('.slider11-controls .slider11-prev').show();
							if(next.next().length > 0) {
								$('#' + id).find('.slider11-controls .slider11-next').show();
							} else {
								$('#' + id).find('.slider11-controls .slider11-next').hide();
							}
						}
					})));
			$(this).find('.slider11-controls .slider11-prev').hide();
			next = $(this).find('.slider11-current-group').next();
			if(next.length == 0) {
				$(this).find('.slider11-controls .slider11-next').hide();
			}

			$(this).smoothDivScroll({ autoScroll: "onstart", autoScrollDirection: "backandforth", autoScrollStep: 1, autoScrollInterval: 15});
			root = $(this).scrollable({items:'.slider11-inner-container', vertical:true});
			root.next();

			/*$(this).children('.slider11-controls a').click(function(event) {
				alert($(this).attr('id'));
				switch($this.attr("rel")) {
					// TODO: MANUAL VERTICAL SCROLL GOES HERE
					case 'prev':
						alert('prev');
						//$(this).find('.slider11-group').hide();
						//$(this).find('.slider11-group:first').show().addClass('slider11-current-group');
						break;
					case 'next':
						alert('next');
						break;
					default:break;
				};
			});*/
			//$(this).smoothDivScroll("startAutoScroll");
			//alert($(this).attr('id'));
			//({originalEvent:({}), type:"mouseleave", timeStamp:1286570472162, jQuery1286570469509:true, which:1, wheelDelta:(void 0), view:#15=({}), toElement:(void 0), target:#16=({}), srcElement:(void 0), shiftKey:false, screenY:528, screenX:175, relatedTarget:null, relatedNode:(void 0), prevValue:(void 0), pageY:484, pageX:175, originalTarget:#16#, offsetY:(void 0), offsetX:(void 0), newValue:(void 0), metaKey:false, layerY:319, layerX:51, keyCode:(void 0), handler:#5=(function (event) {alert(event.toSource());}), fromElement:(void 0), eventPhase:2, detail:0, data:(void 0), currentTarget:#16#, ctrlKey:false, clientY:371, clientX:175, charCode:(void 0), cancelable:true, button:0, bubbles:true, attrName:(void 0), attrChange:(void 0), altKey:false, handleObj:#17={handler:#5#, data:(void 0), namespace:"", type:"mouseleave", guid:1}})
			/*$(this).mousemove(function(event) {
				id = $(this).attr('id');
				containerWidth = $(this).width();
				mouseLeft = event.pageX - $(this).offset().left;
				mouseTop = event.pageY - $(this).offset().top;
				mag = (mouseLeft / (containerWidth / 2) ) - 1;
				groupWidth = $(this).find('.slider11-current-group').width();
				groupPos = $(this).find('.slider11-current-group').position();
				firstPos = $(this).find('.slider11-current-group .slider11-item:first').position();
				lastPos = $(this).find('.slider11-current-group .slider11-item:last').position();
				settings = $(this).data('settings');
				velocity = settings['hover-scroll-velocity'] * mag;
				// range of X is from 0 to -groupWidth + containerWidth
				deltaX = groupPos.left + containerWidth;
				//alert(settings.hover-scroll-velocity);
				$('#monitor').html('Client Location: ('+event.offsetX+', '+event.offsetY+')' +
				'<br />'+'Mouse Location: ('+mouseLeft+', '+mouseTop+')' +
				'<br />'+'Container Width: '+containerWidth +
				'<br />'+'Mag: '+ mag +
				'<br />'+'Group Width: '+groupWidth+
				'<br />'+'Group Pos Left: '+groupPos.left+
				'<br />'+'First Item Pos Left: '+firstPos.left+
				'<br />'+'Last Item Pos Left: '+lastPos.left+
				'<br />'+'Velocity: '+ velocity);
				//'<br />'+'Container Offset Left'+$(this).offset().left+
				//'<br />'+'Event Source ID: '+id+
				//'<br />'+'Event Source: '+ (event.toSource()));

				//calculate new velocity

				//calculate direction of velocity  if mag is +, move left... if mag is -, move right

				//figure deltaX from current location
				// if containerWidth >= groupWidth, no movement;

				// if mag is (-), move right, up to max range
				// deltaX is distance from currentLeft to 0

				//if mag is (+), move left, down to min range
				// deltaX is distance from currentLeft to max(-groupWidth + containerWidth, 0)

				//figure total time to get to finish at new velocity
				//animate deltaX over total time
				if(containerWidth < groupWidth) {
					if(mag == 0 || (mag > -0.33 && mag < 0.33)) {
						$(this).stop(true);
					} else if(mag < 0) {
						clearInterval(settings.intervalID);
						//clearTimeout(settings.TimeoutID);
						finalX = 0;
						deltaX = finalX + groupPos.left;
						// -> mag*velocity/100ms = deltaX/totalTime;
						// -> mag*velocity*totalTime/100ms = deltaX
						// -> totalTime/100ms = deltaX/mag*velocity
						// -> totalTime = 100ms*deltaX/mag*velocity
						totalTime = (deltaX) / (-mag * velocity);
						//alert(totalTime);
						//totalTime = 10000;


						//alert('LEFT: '+$(this).find('.slider11-current-group').css('left')+'<br />OFFSET: '+$(this).find('.slider11-current-group').offset().left);
						if(settings.intervalID != undefined) {
							settings.intervalID = setInterval(function() {
								//alert('' + (Math.max(finalX, parseFloat(document.getElementById('slider11-group1').style.left) - velocity)) + 'px');
								//document.getElementById('slider11-group1').style.left = '' + (parseFloat(document.getElementById('slider11-group1').style.left) - velocity) + 'px';
								//if(document.getElementById('slider11-group1').style.left == finalX)
								//	clearInterval(settings.intervalID);
								$('#' + id + ' .slider11-current-group').css('left', '' + (Math.min(finalX, parseFloat($('.slider11-current-group').css('left')) - velocity) + 'px'));
								if($('#' + id + ' .slider11-current-group').css('left') == finalX)
									clearInterval(settings.intervalID);
							}, 5);
						}
						//settings.timeoutID = setTimeout("clearTimeout('"+settings.intervalID+"');", 500);
						//queue = $(this).queue();
						//alert(queue.toSource());

						/*$(this).find('.slider11-current-group').stop(true).animate({
							left:finalX
						}, {
							queue:false,
							duration:totalTime
						});*/
					/*} else {
						clearTimeout(settings.intervalID);
						//clearTimeout(settings.TimeoutID);
						finalX = -groupWidth + containerWidth;
						deltaX = finalX - groupPos.left;
						totalTime = (deltaX) / (-mag * velocity);
						//totalTime = 10000;
						$('#monitor').html($('#monitor').html() +
						'<br />'+'Final X: '+finalX +
						'<br />'+'Delta X: '+deltaX +
						'<br />'+'Total Time: '+ totalTime);
						//queue = $(this).find('.slider11-current-group').queue();
						//alert(queue.toSource());
						intervalFunction = function() {
							try {
					*/
								/*$('#monitor').html('' +
								'<br />'+'Old Left: '+$('.slider11-current-group').css('left')+
								'<br />'+'New Left: '+'' + (Math.max(finalX, parseFloat($('.slider11-current-group').css('left')) - velocity)) + 'px'+
								'<br />'+'Delta X: '+deltaX +
								'<br />'+'Total Time: '+ totalTime);*/
					/*			$('#' + id + ' .slider11-current-group').css('left', '' + (Math.max(finalX, parseFloat($('.slider11-current-group').css('left')) - velocity)) + 'px');
								if($('#' + id + ' .slider11-current-group').css('left') == finalX)
									clearInterval(settings.intervalID);
								//alert(document.getElementById('slider11-group1').toSource());
								//alert('' + (Math.max(finalX, parseFloat(document.getElementById('slider11-group1').style.left) - velocity)) + 'px');
								//document.getElementById('slider11-group1').style.left = '' + (Math.max(finalX, parseFloat(document.getElementById('slider11-group1').style.left) - velocity) + 'px');
								//if(document.getElementById('slider11-group1').style.left == finalX)
								//	clearInterval(settings.intervalID);
								//settings.intervalID = setTimeout(timeoutFunction, 10);
							} catch(e) {
								alert('error');
							}
						};

						settings.intervalID = setInterval(intervalFunction, 10);
						*/

						/*$(this).find('.slider11-current-group').stop(true).animate({
							left:finalX
						}, {
							queue:false,
							duration:totalTime
						});*/
					/*}
				}*/

				/*if(mag > 0) { // move left
					diff = '-=' + settings['hover-scroll-velocity'] * mag;
					//if(groupPos.left - settings['hover-scroll-velocity'] * mag < groupWidth - $(this).width() )
					//	diff = 	'-' + groupWidth + 'px';
					$(this).find('.slider11-current-group').stop(true, true).animate({
						left:diff
					});
				} else if(mag < 0) { // move right
					diff = '+=' + settings['hover-scroll-velocity'] * abs(mag);
					//if(groupPos.left + settings['hover-scroll-velocity'] * abs(mag) > 0)
					//	diff = 0;
					$(this).find('.slider11-current-group').stop(true, true).animate({
						left:diff
					});
				}*/
			/*});

			$(this).mouseout(function() {
				clearTimeout(settings.intervalID);
				//clearTimeout(settings.TimeoutID);
				//$(this).find('.slider11-current-group').stop(true);
			});*/

		},

		show : function( ) {

		},

		hide : function( ) {

		},

		update : function(settings) {

		},

		prev_group : function(settings) {
			current = $(this).closest('.slider11-current-group');
			prev = current.prev();
			if(prev) {

			}
		},

		next_group : function(settings) {

		},

		startAutoScroll : function(settings) {
			$(this).smoothDivScroll("startAutoScroll");
		},

		stopAutoScroll : function(settings) {
			$(this).smoothDivScroll("stopAutoScroll");
		},

		gotoGroupById : function(settings) {
			offset = 0;
			current = $(this).find('.slider11-current-group');

			// check if we're already there
			if(current.attr('id') == settings.gotoGroupById)
				return true;

			// try looking forward
			current = current.next();
			offset++;
			while(current.length > 0) {
				if(current.attr('id') == settings.gotoGroupById) { // click forward
					for(var i = 0; i < offset; i++) {
						$(this).find('.slider11-next').click();
					}
					return true;
				} else {
					current = current.next();
					offset++;
				}
			}

			// try looking backward
			offset = 0;
			current = $(this).find('.slider11-current-group').prev();
			while(current.length > 0) {
				if(current.attr('id') == settings.gotoGroupById) { // click backward
					for(var i = 0; i <= offset; i++) {
						$(this).find('.slider11-prev').click();
					}
					return true;
				} else {
					current = current.prev();
					offset++;
				}
			}

			//no such id
			return false;
		}
	};

	$.fn.slider11 = function(method, options) {

		var settings = {
			'hover-scroll-enabled':true,
			'hover-scroll-velocity':20,
			'location':'top',
			'background-color':'blue'
		};

		if(options) {
			$.extend(settings, options);
		}

		$(this).data('settings', settings);

		// Method calling logic
		if(methods[method]) {
			return methods[method].call(this, settings);
		} else if(typeof method === 'object' || !method) {
			return methods.init.call(this, settings);
		} else {
			$.error('Method ' + method + ' does not exist on jQuery.slider11');
		}
	};

})(jQuery);

