var isiPad 	= navigator.userAgent.match(/iPad/i) != null; 	
var isiPhone = navigator.userAgent.match(/iPhone/i) != null; 	
var isiPod	= navigator.userAgent.match(/iPod/i) != null;
var isAndroid = navigator.userAgent.match(/Android/i) != null;

var isMobile =  isiPad || isiPhone || isiPod || isAndroid;


function basename(filename) {
	return filename.substr(0, filename.lastIndexOf('.'));
}
 
function stripitem(src, desc) {
	this.src = 'large/' + src;
	this.thumb = 'thumb/' + src;
	this.desc = desc
	this.el = $('<li><img src="' + this.thumb + '"/></li>');
	var self = this;
}

stripitem.prototype.setHighlighted = function(val) {
	this.highlighted = val;
	if (val) {
		this.el.addClass('highlighted')
	} else {
		this.el.removeClass('highlighted')
	}
}

stripitem.prototype.setFade = function(val) {
	if (val < 0) {
		this.el.addClass("fadeout-left")
		this.el.removeClass("fadeout-right")
	} else if (val > 0) {
		this.el.removeClass("fadeout-left")
		this.el.addClass("fadeout-right")
	} else {
		this.el.removeClass("fadeout-left")
		this.el.removeClass("fadeout-right")
	}
}


/*
 * What needs sizing
     The Thumbnail images
     the UL surrounding it.
 */

function imageviewer(el, options) {
	this.element = el
	
	this.images = []
	this.current = -1
	this.currentScrollPos = -1
	this.onSetImageListeners = []
	this.numImages = 8;
	this.thumbSize = 70;
	var me = this;
	
	if (options) { // TODO there is probably a better way to merge them.
		if (options["thumbSize"])
			this.thumbSize = options["thumbSize"];
		if (options["thumbCount"])
			this.numImages = options["thumbCount"];
	}
	

	// Get the Images
	var i = 0;
	el.find("a").each(function() {
		var src = $(this).attr("href");
		var desc = $(this).html();
		me.images.push(new stripitem(src, desc))
    });

	// Rewrite the HTML
	el.empty().append('<div class="largeimage"><img class="big" src="../../blank.png"/><img class="spinner" src="../../loading.gif"/></div><div class="descriptionline"><span class="imagedesc"></span><div class="imagecounter">image <span class="imagepos">#</span> of <span class="imagecount">#</span></div></div><div class="imgstrip"><div class="imgbutton imgbutton-left">&lt;</div><div class="imglist"><ul></ul></div><div class="imgbutton imgbutton-right">&gt;</div></div>')
	this.list = el.find('.imglist ul')
	this.listDom = this.list.get(0);
	for (i in this.images) {
		me.list.append(this.images[i].el)
	}

	// Wire up Event Listeners
	this.list.click(function(evt) {
		var offset = $(this).offset()
		var x = evt.pageX - offset.left;
		var y = evt.pageY - offset.top;
		var img = Math.floor(x / me.outerThumbSize);
		me.setImage(img);
		evt.preventDefault()
		return false
	})
	
	el.find(".imgbutton-left").click(function(evt) {
		me.prevImg()
		evt.preventDefault();
		return false;
	});
	el.find(".imgbutton-right").click(function(evt) {
		me.nextImg()
		evt.preventDefault();
		return false;
	});
	
	if (isMobile) {
		this.listDom.addEventListener('touchstart', function(evt) {
			me.touchStart(evt);
		}, false);
	}
	
	
	this.backgroundLoadImage = new Image();
	this.backgroundLoadImage.onload = function() {
		me.element.removeClass("loading");
		me.element.find('.largeimage img.big').attr('src', me.backgroundLoadImage.src)
	};
	this.setThumbSize(this.thumbSize)
	
	// Make it show the first image.
	this.setImage(0);
	this.scrollToIndex(0);

}

imageviewer.prototype.setThumbSize = function(newSize) {
	this.outerThumbSize = newSize+2;
	this.thumbSize = newSize;
	this.list.height(this.outerThumbSize);
	this.list.find("img").width(newSize).height(newSize);
	this.element.find(".imgbutton").css({"line-height": newSize + "px"})
	this.element.find(".imglist").width(this.numImages*this.outerThumbSize).height(this.outerThumbSize)
}

imageviewer.prototype.touchStart = function(e) {
	if (e.touches.length == 1) {
		this.touchStartX = e.touches[0].pageX;
//	   	this.touchStartY = e.touches[0].pageY;
	    this.touchStartScroll = this.currentScrollPos;
		var me = this;
	   	this.listDom.addEventListener('touchmove', function(evt) {
			me.touchMove(evt);
		}, false);
	   	this.listDom.addEventListener('touchend', function(evt) {
			me.touchEnd(evt);
		}, false);
	}
	return false;
};

imageviewer.prototype.touchMove = function(e) {
	if (e.touches.length > 1) {
   		cancelTouch();
  	} else {
		var diff = e.touches[0].pageX - this.touchStartX;
		this.scrollToPosition(this.touchStartScroll - diff);
  	}
};

imageviewer.prototype.touchEnd = function(e) {
	this.cancelTouch();
};

imageviewer.prototype.cancelTouch = function() {
	this.listDom.removeEventListener('touchmove', this.touchMove);
  	this.listDom.removeEventListener('touchend', this.touchEnd);
  
}

imageviewer.prototype.onImageChange = function(listener) {
	this.onSetImageListeners.push(listener)
};

imageviewer.prototype.setImage = function(index) {
	if (index != this.current) {
		if (this.current != -1) {
			this.images[this.current].setHighlighted(false);
		}
		var me = this;
		
		this.element.addClass("loading");
		this.backgroundLoadImage.src = this.images[index].src;
		desc = this.images[index].desc;
		
		this.element.find('.imagecounter .imagepos').text(index+1)
		this.element.find('.imagecounter .imagecount').text(this.images.length)
		this.element.find('.imagedesc').html(desc)
		this.current = index
		if (this.current != -1) {
			this.images[this.current].setHighlighted(true);
		}
	
		this.scrollToIndex(index)
	
		if (index == 0) {
			this.element.find(".imgbutton-left").addClass("disabled")
		} else {
			this.element.find(".imgbutton-left").removeClass("disabled")
		}
		if (index == this.images.length -1) {
			this.element.find(".imgbutton-right").addClass("disabled")
		} else {
			this.element.find(".imgbutton-right").removeClass("disabled")
		}
		
		for (i in this.onSetImageListeners) {
			this.onSetImageListeners[i](this, index)
		}
	}
};
imageviewer.prototype.scrollToIndex = function(index) {
	var offset = this.outerThumbSize*(index-this.numImages/2) + this.outerThumbSize/2
	this.scrollToPosition(offset);
};

imageviewer.prototype.scrollBy = function(amount) {
	this.scrollToPosition(this.currentScrollPos + amount);
}

imageviewer.prototype.scrollToPosition = function(offset) {
	if (offset == this.currentScrollPos) {
		return;
	}
	var list = this.element.find('.imglist ul');
	var listcontainer = list.parent()
	var canScrollLeft = true;
	var canScrollRight = true;
	
	var maxScroll = this.outerThumbSize*this.images.length-listcontainer.width()


	if (offset >= maxScroll) {
		offset = maxScroll;
		canScrollRight = false;
	}
	if (offset <= 0) {
		offset = 0;
		canScrollLeft = false;
		canScrollRight = offset < maxScroll; // Need to test again for case where there are 8 items exactly
	}
	this.currentScrollPos = offset;

	list.css({left:-offset})
	
	if (canScrollLeft && canScrollRight) {
		listcontainer.removeClass('scrollleft')
		listcontainer.removeClass('scrollright')
		listcontainer.addClass('scrollboth')
	} else if (canScrollLeft) {
		listcontainer.addClass('scrollleft')
		listcontainer.removeClass('scrollright')
		listcontainer.removeClass('scrollboth')
	} else if (canScrollRight) {
		listcontainer.removeClass('scrollleft')
		listcontainer.addClass('scrollright')
		listcontainer.removeClass('scrollboth')
	} else {
		listcontainer.removeClass('scrollleft')
		listcontainer.removeClass('scrollright')
		listcontainer.removeClass('scrollboth')
	}
};

imageviewer.prototype.prevImg = function(index) {
	if (this.current > 0) {
		this.setImage(this.current-1)
	}
};
imageviewer.prototype.nextImg = function(index) {
	if (this.current < this.images.length-1) {
		this.setImage(this.current+1)
	}
};

(function( $ ){
  $.fn.imgstrip = function(params) {
	var iview = new imageviewer(this, params)
	return iview;
  };
})( jQuery );


