/*
	Kwicks for jQuery (version 1.5.1)
	Copyright (c) 2008 Jeremy Martin
	http://www.jeremymartin.name/projects.php?project=kwicks
	Licensed under the MIT license
	Modified File
*/
(function($){
	$.fn.kwicks = function(options) {
		var defaults = {
			isVertical: false,
			sticky: false,
			defaultKwick: 0,
			event: 'mouseover',
			spacing: 0,
			duration: 500,
			kwickInfo: "#kwickInformationIntro",
			kwickStartup : "#kwickInformationInfoWrapper"
		};
		var o = $.extend(defaults, options);
		var WoH = (o.isVertical ? 'height' : 'width'); // WoH = Width or Height
		var LoT = (o.isVertical ? 'top' : 'left'); // LoT = Left or Top
		
		return this.each(function() {
			var container = $(this);
			var kwicks = container.children('li');
			var kwickImage = container.parent().find('div.kwickImages');
			var kwickImages = kwickImage.children('.item');
			var normWoH = kwicks.eq(0).css(WoH).replace(/px/,''); // normWoH = Normal Width or Height
			var introSet = false;

			if (!o.rows) o.rows = kwicks.size();

			var normFlip = -13;

			if(o.defaultKwick == 0) {
				o.defaultKwick = Math.floor(Math.random()*kwicks.size());
			}
			var kwickCurrent = o.defaultKwick;
			if(!o.max) {
				o.max = (normWoH * o.rows) - (o.min * (o.rows - 1));
			} else {
				o.min = ((normWoH * o.rows) - o.max) / (o.rows - 1);
			}
			// set width of container ul
			if(o.isVertical) {
				container.css({
					width :   kwicks.eq(0).css('width'),
					height : (normWoH * (o.rows)) + (o.spacing * ((o.rows)- 1)) + 'px'
				});				
			} else {
				container.css({
					width : (normWoH * kwicks.size()) + (o.spacing * (kwicks.size() - 1)) + 'px',
					height : kwicks.eq(0).css('height')
				});				
			}
			
			container.before('<a href="#" id="kwickInformationBtn">Info</a>');

			var hoverIntent = null;
			$("#kwickInformationBtn").mouseenter(function(e){
				clearTimeout(hoverIntent);
				var el = this;
                	hoverIntent = setTimeout(function () {
						$(o.kwickInfo).stop(true, true).fadeOut("fast");
						$(o.kwickStartup).stop(true, true).fadeIn();
					}, 150);
			})
			.mouseleave(function(e){
				$(o.kwickStartup).stop(true, true).fadeOut("fast");
				$(o.kwickInfo).stop(true, true).fadeIn();
				clearTimeout(hoverIntent);
			}).css("display", "none");
			

			// pre calculate left or top values for all kwicks but the first and last
			// i = index of currently hovered kwick, j = index of kwick we're calculating
			var preCalcLoTs = []; // preCalcLoTs = pre-calculated Left or Top's
			var jRow;
			var jReset = 0;
			for(i = 0; i < kwicks.size(); i++) {
				preCalcLoTs[i] = [];
				// don't need to calculate values for first or last kwick
					for(j = 1; j < kwicks.size() - 1; j++) {
						jRow = j % o.rows;
						if (j % o.rows != 0 && j != o.rows - 1) {
							if(i == j) {
								if (o.isVertical) {
									preCalcLoTs[i][j] = jRow * o.min + (jRow * o.spacing);
								} else {
									preCalcLoTs[i][j] = jRow * o.min + (jRow * o.spacing)
								}		
							}
							else {
								if (j <= i) {
									preCalcLoTs[i][j] = (jRow * o.min) + (jRow * o.spacing);
								} else {
									preCalcLoTs[i][j] = (jRow-1) * o.min + o.max + (jRow * o.spacing);
								}
							}
						}
					}
			}
			
			// loop through all kwick elements
			kwicks.each(function(i) {
				var kwick = $(this);
				
				kwick.children().not("div.corner").prepend("<div class=\"hoverarea\"></div>")
				.prepend("<div class=\"hoverimage\"></div>");
				kwick.find("div.hoverimage").css({ opacity: 0 })

				// set initial width or height and left or top values
				// set first kwick
	
				if(i% o.rows === 0) {
					kwick.css(LoT, '0px');
				} 
				// set last kwick
				else if(i % o.rows == o.rows - 1) {
					kwick.css(o.isVertical ? 'bottom' : 'right', '0px');
				}
				// set all other kwicks
				else {
					if(o.sticky) {
						kwick.css(LoT, preCalcLoTs[o.defaultKwick][i]);
					} else {
						kwick.css(LoT, (i % o.rows * normWoH) + (i % o.rows * o.spacing));
					}
				}
				$(kwickImages).css({opacity: 0.0});
				$(kwickImages[kwickCurrent]).addClass("active").css({opacity: 1.0});
				// correct size in sticky mode
				if(o.sticky) {
					if(o.defaultKwick == i) {
						kwick.css(WoH, o.max + 'px');
						kwick.addClass('active');
						kwick.find("div.hoverimage").css({ opacity: 1 });
					} else {
						kwick.css(WoH, o.min + 'px');
					}
				}
				
				if(o.isVertical) {
					kwick.css('left', kwick.css('margin-left'));
				}
				
				kwick.css({
					margin: 0,
					position: 'absolute'
				});
				
				kwick.bind(o.event, function() {
											 
					if (disabledCSS()) { return false; }
					// calculate previous width or heights and left or top values
					var prevWoHs = []; // prevWoHs = previous Widths or Heights
					var prevLoTs = []; // prevLoTs = previous Left or Tops
					kwicks.stop().removeClass('active');
					
					kwicks.each(function(j) {
						if (kwicks.eq(j).hasClass("columnFlip")) {
							kwicks.eq(j).find("div.hoverimage").stop().animate({ left:normFlip + 'px', opacity: 0 }, 300);
						} else {
							kwicks.eq(j).find("div.hoverimage").stop().animate({ right:normFlip + 'px', opacity: 0 }, 300);
						}
					});
					
					for(j = ((parseInt(i/o.rows)) * o.rows); j < ((parseInt(i/o.rows) + 1) * o.rows); j++) {
						prevWoHs[j] = kwicks.eq(j).css(WoH).replace(/px/, '');
						prevLoTs[j] = kwicks.eq(j).css(LoT).replace(/px/, '');
					}
					var aniObj = {};
					aniObj[WoH] = o.max;
					var maxDif = o.max - prevWoHs[i];
					var prevWoHsMaxDifRatio = prevWoHs[i]/maxDif;
				
					function animateInner() {
						var active = kwickImage.find('.active');
						
						if (active.length == 0 ) active = $(kwickImages[kwickCurrent]);
						if (kwickCurrent != i) {
							
							$(o.kwickInfo).children(0).hoverFlow(o.event, { "marginBottom" : "30px" }, 300);
							$(o.kwickInfo).parent().hoverFlow(o.event, { opacity: 0 }, 300, function() {$(this).css("display","none");});		
							
							var next = $(kwickImages[i]);
							active.addClass('lastActive');
							kwickCurrent = i;
							next.css({opacity: 0.0})
								.addClass('active')
								.stop()
								.hoverFlow(o.event, {opacity: 1.0}, 400, function() {
									if ($(this).find(".kwickInformation").html() != null) {
									 	$(o.kwickInfo).html(($(this).find(".kwickInformation").html())).children(0).css({"marginBottom" : "0"}).stop().hoverFlow(o.event, { "marginBottom" : "20px" }, 500);
										$(o.kwickInfo).parent().css({"opacity" : "0", "display": "block"}).stop().hoverFlow(o.event, { opacity: 1 }, 450);
									}
									active.removeClass('active lastActive');
									
							});
						} else {
							if(!introSet) {
								if ($(kwickImages[i]).find(".kwickInformation").html()!= null) {
									$(o.kwickInfo).children(0).hoverFlow(o.event, { "marginBottom" : "30px" }, 300);
									$(o.kwickInfo).parent().hoverFlow(o.event, { opacity: 0 }, 300, function() {
										$(this).children(0).html(($(kwickImages[i]).find(".kwickInformation").html())).stop().parent().hoverFlow(o.event, { opacity: 1 }, 450);
										$(this).children(0).children(0).css({"marginBottom" : "0"}).stop().hoverFlow(o.event, { "marginBottom" : "20px" }, 450);
									
									});
								} else {
									$(o.kwickInfo).children(0).hoverFlow(o.event, { "marginBottom" : "30px" }, 300);
									$(o.kwickInfo).parent().hoverFlow(o.event, { opacity: 0 }, 300, function() {$(this).css("display","none");});		
								}
							}	
						}
						introSet = true;
					}
					
					$(o.kwickStartup).fadeOut();
					$("#kwickInformationBtn").delay(600).fadeIn();
					
					if (kwick.hasClass("columnFlip")) {
						kwick.find("div.hoverimage").stop().animate({ left:'0', opacity: 1 }, 500, animateInner);
					} else {
						kwick.find("div.hoverimage").stop().animate({ right:'-1px', opacity: 1 }, 500, animateInner);
					}
					
					kwick.addClass('active').animate(aniObj, {
						step: function(now) {
							// calculate animation completeness as percentage
							var percentage = maxDif != 0 ? now/maxDif - prevWoHsMaxDifRatio : 1;
							// adjsut other elements based on percentage
							kwicks.each(function(j) {
								if ((j >= (parseInt(i/o.rows)) * o.rows) && (j < (parseInt(i/o.rows) + 1) * o.rows) ) {
									if(j != i) {
									kwicks.eq(j).css(WoH, prevWoHs[j] - ((prevWoHs[j] - o.min) * percentage) + 'px');
									}	
									if(j % o.rows != 0 && (j % o.rows != o.rows - 1)) { // if not the first or last kwick
										kwicks.eq(j).css(LoT, prevLoTs[j] - ((prevLoTs[j] - preCalcLoTs[i][j]) * percentage) + 'px');
									}
								}
							});
						},
						duration: o.duration,
						easing: o.easing
					});
				});
			});
			if(!o.sticky) {
				container.bind("mouseleave", function() {
					if (disabledCSS()) { return false; }
					var prevWoHs = [];
					var prevLoTs = [];
					kwicks.removeClass('active').stop();
					for(i = 0; i < kwicks.size(); i++) {
						prevWoHs[i] = kwicks.eq(i).css(WoH).replace(/px/, '');
						prevLoTs[i] = kwicks.eq(i).css(LoT).replace(/px/, '');			
					}
					var aniObj = {};
					aniObj[WoH] = normWoH;
					var normDif = normWoH - prevWoHs[j - o.rows];
					kwicks.eq(j - o.rows).animate(aniObj, {
						step: function(now) {
							var percentage = normDif != j - o.rows ? (now - prevWoHs[j - o.rows])/normDif : 1;
							for(i = (j - o.rows); i < j; i++) {
								kwicks.eq(i).css(WoH, prevWoHs[i] - ((prevWoHs[i] - normWoH) * percentage) + 'px');
								if(i % o.rows != o.rows - 1) {
									kwicks.eq(i).css(LoT, prevLoTs[i] - ((prevLoTs[i] - ((i % o.rows * normWoH) + (i % o.rows * o.spacing))) * percentage) + 'px');
								}
							}
						},
						duration: o.duration,
						easing: o.easing
					});
					kwicks.each(function(j) {
						if (kwicks.eq(j).hasClass("columnFlip")) {
							kwicks.eq(j).find("div.hoverimage").stop().animate({ left:normFlip + 'px', opacity: 0 }, 300);
						} else {
							kwicks.eq(j).find("div.hoverimage").stop().animate({ right:normFlip + 'px', opacity: 0 }, 300);
						}
					});
				});
				
			}
		});
	};
})(jQuery);
