/**
 * jquery.LavaLamp - light up your menu with fluid, jQuery powered animations.
 *
 * Requires jQuery v1.2.2 or better from http://jquery.com
 * Tested on jQuery 1.2.6 and 1.3.2
 *
 * http://nixboxdesigns.com/projects/jquery-lavalamp.php
 *
 * Copyright (c) 2008, 2009, 2010 Jolyon Terwilliger, jolyon@nixbox.com
 * Source code Copyright (c) 2007, 2008
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 * credits to Guillermo Rauch and Ganeshji Marwaha (gmarwaha.com) for original editions
 **/
 
 /** Update 23.01.2010r.
  * @copyright Copyrights by LikeLink s.c. 2010. 
  * @author Updates coded by Adam Kopeæ <a.kopec@indexo.pl, adam.kopec@gmail.com>.
  * Updates:
  * - added select() and unselect() to programmatically select and unselect items; (30.01.2010r.)
  * - corrected the selector for "noLava" class, now it allows to combine this class with others, e.g.
  *   you could write <li class="noLava foo"></li> and it will work correctly;
  * - removed unnecessary div elements from inside the li.backLava, project requires only horizontal resizing;
  * - removed recalculations of height and top due to the same reason as above;
  * - moved examples and history to the external file to reduce size by 9KB (comments.txt in the script folder)
  **/

(function(jQuery) {

var selected;
var newSelect = null;
var callback = null;

jQuery.fn.lavaLamp = function(o) {
	o = jQuery.extend({ fx: 'swing',
				speed: 500, 
				click: function(){return true}, 
				startItem: '',
				autoReturn: true,
				returnDelay: 0,
				setOnClick: true,
				homeTop:0,
				homeLeft:0,
				homeWidth:0,
				homeHeight:0,
				returnHome:false,
				onSelect: function(selected, back) {return true; }
				}, 
			o || {});

	return this.each(function() {
		// ensures parent UL or OL element has some positioning
		if (jQuery(this).css('position')=='static')
			jQuery(this).css('position','relative');

		// create homeLava element if origin dimensions set
		if (o.homeTop || o.homeLeft) { 
			//var $home = jQuery('<li class="homeLava"></li>').css({ left:o.homeLeft, top:o.homeTop, width:o.homeWidth, height:o.homeHeight, position:'absolute' });
			var home = jQuery('<li class="homeLava"></li>').css({ left:o.homeLeft, width:o.homeWidth, position:'absolute' });
			jQuery(this).prepend(home);
		}

		//var path = location.pathname + location.search + location.hash, $selected, $back, $li = jQuery('li:not(li.noLava)', this), delayTimer, bx=by=0;
		var path = location.pathname + location.search + location.hash, selected, back, li = jQuery('li:not(li.noLava)', this), delayTimer, bx=0;
		
		// start $selected default with CSS class 'selectedLava'
		selected = jQuery('li.selectedLava', this);
		
		// override $selected if startItem is set
		if (o.startItem != '')
			selected = li.eq(o.startItem);

		// default to $home element
		if ((o.homeTop || o.homeLeft) && selected<1)
			selected = home;

		// if one of the links happens to be a single forward slash / this is the only way to catch it *sigh*	
		if ( selected.length<1 && path=='/')
			selected = li.find('a[href="/"]').parent('li');
		
		// trailing fullpath (with slash) search - WordPress friendly
		// matches both root absolute and domain+root absolute URIs
		if ( selected.length<1 && path!='/')
			selected = li.find('a[href$="' + path + '"]').parent('li');

		// strip trailing slash(es) if any and check for trailing path match
		if ( selected.length<1 ) {
			path = path.replace(/\/+$/,'');
			selected = li.find('a[href$="' + path + '"]').parent('li');
		}

		// strip off leading segments of the path by each / and attempt a trailing match
		if ( selected.length<1 && path.length > 0) {
			while (path.indexOf('/')>-1) {
				path = path.substring(path.indexOf('/')+1);
				selected = li.find('a[href$="'+path+'"]').parent('li');
				if (selected.length>0 || path.indexOf('/')<0) break;
			}
		}
		
		if ( selected.length<1 && path.length > 0) {
			path = path.substring(path.indexOf('#'));
			selected = li.find('a[href$="'+path+'"]').parent('li');	
		}
	
		if ( selected.length<1 && path.length > 0) {
			path = path.substring(path.indexOf('?'));
			selected = li.find('a[href$="'+path+'"]').parent('li');	
		}
	
		// if still no matches, default to the first element
		if ( selected.length<1 )
			selected = li.eq(0);

		// make sure we only have one element as $selected and apply selectedLava class
		selected = jQuery(selected.eq(0).addClass('selectedLava'));
		
		
			
		// add mouseover event for every sub element
		li.bind('mouseenter', function() {
			// help backLava behave if returnDelay is set
			if(delayTimer) {clearTimeout(delayTimer);delayTimer=null;}
			move(jQuery(this));
		}).click(function(e) {
			if (o.setOnClick) {
				selected.removeClass('selectedLava');
				selected = jQuery(this).addClass('selectedLava');
			}
			return o.click.apply(this, [e, this]);
		});
		
		// creates and adds to the container a backLava element with absolute positioning
		back = jQuery('<li class="backLava"><div class="left"></div><div class="right"></div></li>').css('position','absolute').prependTo(this);

		
		
		// compute border and padding differences on styled backLava element
		bx = parseInt(back.css('borderLeftWidth').match(/\d+/))+parseInt(back.css('borderRightWidth').match(/\d+/))+parseInt(back.css('paddingLeft').match(/\d+/))+parseInt(back.css('paddingRight').match(/\d+/));
		//by = parseInt($back.css('borderTopWidth').match(/\d+/))+parseInt($back.css('borderBottomWidth').match(/\d+/))+parseInt($back.css('paddingTop').match(/\d+/))+parseInt($back.css('paddingBottom').match(/\d+/));
		//console.log("bx="+bx+", by="+by);

		// set the starting position for the lavalamp hover element: .back
		if (o.homeTop || o.homeLeft)
			//$back.css({ left:o.homeLeft, top:o.homeTop, width:o.homeWidth, height:o.homeHeight });
			back.css({ left:o.homeLeft, width:o.homeWidth });
		else
		{ 
			var so = selected.position();
			//$back.css({ left: so.left, top: so.top, width: $selected.outerWidth()-bx, height: $selected.outerHeight()-by });
			back.css({ left: so.left, width: selected.outerWidth()-bx });
		}
		
		o.onSelect(selected, back);
		
		// after we leave the container element, move back to default/last clicked element
		jQuery(this).bind('mouseleave', function() {
			
			var returnEl = null;
			
			/*if (selected)
			{
				returnEl = selected;
			}*/
			
			if (newSelect)
			{
				returnEl = newSelect;
			}
			
			if (o.returnHome)
				returnEl = home;
			else if (!o.autoReturn)
				return true;
		
			//console.log('move' + selected + newSelect);
			
			if (returnEl == null || returnEl == newSelect || returnEl == selected)
			{
				if (callback)
					callback();
			}
			if (o.returnDelay) {
				if(delayTimer) clearTimeout(delayTimer);
				delayTimer = setTimeout(function(){move(returnEl);},o.returnDelay);
			}
			else {
				move(returnEl);
			}
			return true;
		});

		function move(el) {
			if (!el) 
			{
				el = selected;
			}
			
			var iso = el.position();
			
			back.stop()
			.animate(
			{
				left: iso.left,
				width: el.outerWidth()-bx
			}, o.speed, o.fx);
		};
	});
};
//callback is fired when the element goes back to it's new position
jQuery.fn.lavaLamp.select = function (selector, callbackFunction) {
	newSelect = jQuery(selector).addClass('newSelectLava');
	callback = callbackFunction;
};

jQuery.fn.lavaLamp.unselect = function () {
	if (newSelect)
		newSelect.removeClass('newSelectLava');
	newSelect = null;
};
})(jQuery);