
/*
 * Superfish v1.4.8 - jQuery menu widget
 * Copyright (c) 2008 Joel Birch
 *
 * Dual licensed under the MIT and GPL licenses:
 * 	http://www.opensource.org/licenses/mit-license.php
 * 	http://www.gnu.org/licenses/gpl.html
 *
 * CHANGELOG: http://users.tpg.com.au/j_birch/plugins/superfish/changelog.txt
 */

;(function($){
	$.fn.superfish = function(op){

		var sf = $.fn.superfish,
			c = sf.c,
			$arrow = $(['<span class="',c.arrowClass,'"> &#187;</span>'].join('')),
			over = function(){
				var $$ = $(this), menu = getMenu($$);
				clearTimeout(menu.sfTimer);
				$$.showSuperfishUl().siblings().hideSuperfishUl();
			},
			out = function(){
				var $$ = $(this), menu = getMenu($$), o = sf.op;
				clearTimeout(menu.sfTimer);
				menu.sfTimer=setTimeout(function(){
					o.retainPath=($.inArray($$[0],o.$path)>-1);
					$$.hideSuperfishUl();
					if (o.$path.length && $$.parents(['li.',o.hoverClass].join('')).length<1){over.call(o.$path);}
				},o.delay);	
			},
			getMenu = function($menu){
				var menu = $menu.parents(['ul.',c.menuClass,':first'].join(''))[0];
				sf.op = sf.o[menu.serial];
				return menu;
			},
			addArrow = function($a){ $a.addClass(c.anchorClass).append($arrow.clone()); };
			
		return this.each(function() {
			var s = this.serial = sf.o.length;
			var o = $.extend({},sf.defaults,op);
			o.$path = $('li.'+o.pathClass,this).slice(0,o.pathLevels).each(function(){
				$(this).addClass([o.hoverClass,c.bcClass].join(' '))
					.filter('li:has(ul)').removeClass(o.pathClass);
			});
			sf.o[s] = sf.op = o;
			
			$('li:has(ul)',this)[($.fn.hoverIntent && !o.disableHI) ? 'hoverIntent' : 'hover'](over,out).each(function() {
				if (o.autoArrows) addArrow( $('>a:first-child',this) );
			})
			.not('.'+c.bcClass)
				.hideSuperfishUl();
			
			var $a = $('a',this);
			$a.each(function(i){
				var $li = $a.eq(i).parents('li');
				$a.eq(i).focus(function(){over.call($li);}).blur(function(){out.call($li);});
			});
			o.onInit.call(this);
			
		}).each(function() {
			var menuClasses = [c.menuClass];
			if (sf.op.dropShadows  && !($.browser.msie && $.browser.version < 7)) menuClasses.push(c.shadowClass);
			$(this).addClass(menuClasses.join(' '));
		});
	};

	var sf = $.fn.superfish;
	sf.o = [];
	sf.op = {};
	sf.IE7fix = function(){
		var o = sf.op;
		if ($.browser.msie && $.browser.version > 6 && o.dropShadows && o.animation.opacity!=undefined)
			this.toggleClass(sf.c.shadowClass+'-off');
		};
	sf.c = {
		bcClass     : 'sf-breadcrumb',
		menuClass   : 'sf-js-enabled',
		anchorClass : 'sf-with-ul',
		arrowClass  : 'sf-sub-indicator',
		shadowClass : 'sf-shadow'
	};
	sf.defaults = {
		hoverClass	: 'sfHover',
		pathClass	: 'overideThisToUse',
		pathLevels	: 1,
		delay		: 800,
		animation	: {opacity:'show'},
		speed		: 'normal',
		autoArrows	: true,
		dropShadows : true,
		disableHI	: false,		// true disables hoverIntent detection
		onInit		: function(){}, // callback functions
		onBeforeShow: function(){},
		onShow		: function(){},
		onHide		: function(){}
	};
	$.fn.extend({
		hideSuperfishUl : function(){
			var o = sf.op,
				not = (o.retainPath===true) ? o.$path : '';
			o.retainPath = false;
			var $ul = $(['li.',o.hoverClass].join(''),this).add(this).not(not).removeClass(o.hoverClass)
					.find('>ul').hide().css('visibility','hidden');
			o.onHide.call($ul);
			return this;
		},
		showSuperfishUl : function(){
			var o = sf.op,
				sh = sf.c.shadowClass+'-off',
				$ul = this.addClass(o.hoverClass)
					.find('>ul:hidden').css('visibility','visible');
			sf.IE7fix.call($ul);
			o.onBeforeShow.call($ul);
			$ul.animate(o.animation,o.speed,function(){ sf.IE7fix.call($ul); o.onShow.call($ul); });
			return this;
		}
	});

})(jQuery);


(function($){
	/* hoverIntent by Brian Cherne */
	$.fn.hoverIntent = function(f,g) {
		// default configuration options
		var cfg = {
			sensitivity: 7,
			interval: 100,
			timeout: 0
		};
		// override configuration options with user supplied object
		cfg = $.extend(cfg, g ? { over: f, out: g } : f );

		// instantiate variables
		// cX, cY = current X and Y position of mouse, updated by mousemove event
		// pX, pY = previous X and Y position of mouse, set by mouseover and polling interval
		var cX, cY, pX, pY;

		// A private function for getting mouse position
		var track = function(ev) {
			cX = ev.pageX;
			cY = ev.pageY;
		};

		// A private function for comparing current and previous mouse position
		var compare = function(ev,ob) {
			ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
			// compare mouse positions to see if they've crossed the threshold
			if ( ( Math.abs(pX-cX) + Math.abs(pY-cY) ) < cfg.sensitivity ) {
				$(ob).unbind("mousemove",track);
				// set hoverIntent state to true (so mouseOut can be called)
				ob.hoverIntent_s = 1;
				return cfg.over.apply(ob,[ev]);
			} else {
				// set previous coordinates for next time
				pX = cX; pY = cY;
				// use self-calling timeout, guarantees intervals are spaced out properly (avoids JavaScript timer bugs)
				ob.hoverIntent_t = setTimeout( function(){compare(ev, ob);} , cfg.interval );
			}
		};

		// A private function for delaying the mouseOut function
		var delay = function(ev,ob) {
			ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
			ob.hoverIntent_s = 0;
			return cfg.out.apply(ob,[ev]);
		};

		// A private function for handling mouse 'hovering'
		var handleHover = function(e) {
			// next three lines copied from jQuery.hover, ignore children onMouseOver/onMouseOut
			var p = (e.type == "mouseover" ? e.fromElement : e.toElement) || e.relatedTarget;
			while ( p && p != this ) { try { p = p.parentNode; } catch(e) { p = this; } }
			if ( p == this ) { return false; }

			// copy objects to be passed into t (required for event object to be passed in IE)
			var ev = jQuery.extend({},e);
			var ob = this;

			// cancel hoverIntent timer if it exists
			if (ob.hoverIntent_t) { ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t); }

			// else e.type == "onmouseover"
			if (e.type == "mouseover") {
				// set "previous" X and Y position based on initial entry point
				pX = ev.pageX; pY = ev.pageY;
				// update "current" X and Y position based on mousemove
				$(ob).bind("mousemove",track);
				// start polling interval (self-calling timeout) to compare mouse coordinates over time
				if (ob.hoverIntent_s != 1) { ob.hoverIntent_t = setTimeout( function(){compare(ev,ob);} , cfg.interval );}

			// else e.type == "onmouseout"
			} else {
				// unbind expensive mousemove event
				$(ob).unbind("mousemove",track);
				// if hoverIntent state is true, then call the mouseOut function after the specified delay
				if (ob.hoverIntent_s == 1) { ob.hoverIntent_t = setTimeout( function(){delay(ev,ob);} , cfg.timeout );}
			}
		};

		// bind the function to the two event listeners
		return this.mouseover(handleHover).mouseout(handleHover);
	};
	
})(jQuery);

/*
 * 	 imBannerRotater - a JQuery Plugin
 * 	 @author Les Green
 * 	 Copyright (C) 2009 Intriguing Minds, Inc.
 *   
 *   Version 1.2 - 14 Jan 2011
 *   1. Added quotes around "class" so will work in IE and Safari
 *   
 *   Version 1.1 - 9 August 2010
 *   1. Added portfolio option: 
 *   	1. top and side navigation
 *   	2. description - option: side, botttom
 *   	3. Added easing - http://gsgd.co.uk/sandbox/jquery/easing/
 *   
 *      
 *   Version 1.0 - 3 July 2010
 *   1. Added interval option to have images fade in and out simultaneously when in 'rotate' mode
 *   2. Urls can be supplied for every mode, not just random
 *   3. Added title attribute to image data_map (image_title)
 *   4. Added Banner Carousel
 *   5. Added Global url_target. Default: '_blank'
 * 
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.

 *   Demo and Documentation can be found at:   
 *   http://www.grasshopperpebbles.com
 *   
 */
 
;(function($) {
	$.fn.extend({
        imBannerRotater: function(options) { 
        	opts = $.extend({}, $.bannerRotater.defaults, options);
			return this.each(function() {
				new $.bannerRotater(this, opts);
			});
        }
    });	

$.bannerRotater = function(obj, opts) {
	var $this = $(obj);
	var cId;
	var imgCnt = 0, totalItems = 0, displayWidth, currentIndex = 0, selectedIndex = 0, nLeft = 0, ttlWidth = 0;
	var aImages = [];
	if (opts.easing) {
		jQuery.easing.def = opts.easing;
	}
	if (opts.image_url) {
		var d = getDataString();
		doAjax('GET', opts.image_url, d, '', doCreate);
	} else {
		doCreate(opts.images);
	}
	
	function getDataString() {
		var str = '';
		$.each(opts.data, function(i, itm) {
			str += itm.name + "=" + itm.value + "&";							
		});
		//remove last "&"
		str = str.substr(0, (str.length-1));
		return str;
	};
		
	function doAjax(t, u, d, fnBefore, fnSuccess) {
		var dt = (opts.return_type == 'json') ? 'json' : 'text';
		$.ajax({
			type: t,
			url: u,
			data: d,
			dataType: dt,
			beforeSend: fnBefore, //function(){$("#loading").show("fast");}, //show loading just when link is clicked
			//complete: function(){ $("#loading").hide("fast");}, //stop showing loading when the process is complete
			success: fnSuccess,
			error: showError
	 	}); //close $.ajax(
	};
	
	function showError(XMLHttpRequest, textStatus, errorThrown) {
		console.log(textStatus);
	};
	
	function doCreate(data) {
		var img, obj, pic, tgt, sel, url, ttl, desc, li;
		var showVertNav = false;
		if (opts.return_type == 'list') {
			var daAR = data.split(',');
		} else {
			var daAR = new Array();
			$.each(data, function(i, itm) {
				if (opts.data_map.url_name) {
					ttl = (opts.data_map.image_title) ? itm[opts.data_map.image_title] : itm[opts.data_map.image_name];
					desc = (opts.data_map.image_desc) ? itm[opts.data_map.image_desc] : '';
					tgt = (opts.data_map.url_target) ? itm[opts.data_map.url_target] : opts.url_target;
					daAR[i] = new Array(itm[opts.data_map.image_name], itm[opts.data_map.url_name], ttl, desc, tgt);
				} else {
					daAR[i] = itm[opts.data_map.image_name];
				}	
			});
		}
		totalItems = daAR.length;
		if (opts.mode == 'random') {
			img = new Image();
			if (opts.data_map.url_name) {
				obj = getImageObject(daAR[Math.floor(Math.random() * daAR.length)]);
				$this.append($('<a></a>').attr({
					'href': obj.url,
					'target': obj.tgt
				}).append($(img).attr({
					src: obj.pic,
					title: obj.title
				})));
			}
			else {
				pic = opts.base_path + daAR[Math.floor(Math.random() * daAR.length)];
				$this.append($(img).attr({
					src: pic,
					title: pic
				}));
			}
		}
		else 
			if (opts.mode == 'rotate') {
				for (var i = 0; i < totalItems; i++) {
					img = new Image();
					if (opts.data_map.url_name) {
						obj = getImageObject(daAR[i]);
						var a = $('<a></a>').attr({
							'href': obj.url,
							'target': obj.tgt,
							'id': 'imImageRotate' + i
						}).css({
							'display': 'none',
							'position': 'relative',
							'zIndex': 1000 - (totalItems + i)
						}).append($(img).attr({
							src: obj.pic,
							title: obj.title
						})).appendTo($this);
						aImages[i] = $(a).width();
						
					}
					else {
						pic = opts.base_path + daAR[i];
						$this.append($(img).attr({
							src: pic,
							title: daAR[i],
							'id': 'imImageRotate' + i
						}).css({
							'display': 'none',
							'position': 'relative',
							'zIndex': 1000 - (totalItems + i)
						}));
						aImages[i] = $(img).width();
					}
				}
				if (opts.interval) {
					setFadeInterval();
				}
				else {
					imgFadeIn();
				}
			}
			else 
				if (opts.mode == 'carousel') {
					var ul = $('<ul></ul>').appendTo($this);
					for (var i = 0; i < totalItems; i++) {
						img = new Image();
						if (opts.data_map.url_name) {
							obj = getImageObject(daAR[i]);
							li = $('<li></li>').attr('id', 'imImageRotate' + i).append($('<a></a>').attr({
								'href': obj.url,
								'target': obj.tgt
							}).append($(img).attr({
								src: obj.pic,
								title: obj.title
							}))).appendTo($(ul));
							aImages[i] = $(li).width() + parseInt($(li).css('marginLeft'));
						}
						else {
							pic = opts.base_path + daAR[i];
							$('<li></li>').attr('id', 'imImageRotate' + i).append($(img).attr({
								src: pic,
								title: daAR[i]
							})).appendTo($(ul));
						}
					}
					nLeft = aImages[0];
					setCarouselInterval();
				}
				else 
					if (opts.mode == 'portfolio') {
						cId = $this.attr('id');
						
						$this.append($('<div></div>').attr({
							"id": cId + "-imImageRotate-Side-Nav-Left",
							"class": "imImageRotate-Side-Nav"
						}).append($('<div></div>').attr({
							"id": cId + "-imImageRotate-PrevBtn",
							"class": "imImageRotate-PrevBtn"
						})), $('<div></div>').attr({
							"id": cId + "-imImageRotate-SlideCntnr",
							"class": "imImageRotate-SlideCntnr"
						}).append($('<div></div>').attr({
							"id": cId + "-imImageRotate-Slider",
							"class": "imImageRotate-Slider"
						})), $('<div></div>').attr({
							"id": cId + "-imImageRotate-Side-Nav-Right",
							"class": "imImageRotate-Side-Nav"
						}).append($('<div></div>').attr({
							"id": cId + "-imImageRotate-NextBtn",
							"class": "imImageRotate-NextBtn"
						})));
						
						if ((opts.show_vert_nav != '') || (opts.show_vert_nav != 'no')) {
							showVertNav = true;
							var vertNav = $('<div></div>').attr({
								"id": cId + "-imImageRoate-Vert-Nav",
								"class": "imImageRoate-Vert-Nav"
							}).append($('<ul></ul>'));
							if (opts.show_vert_nav == 'top') {
								$this.prepend($(vertNav));
							} else	if (opts.show_vert_nav == 'bottom') {
								$this.append($(vertNav));
							}
							$(vertNav).show();
						}
						
						if (opts.show_side_nav) {
							$('#'+cId+" .imImageRotate-Side-Nav").show();
							$('#'+cId+"-imImageRotate-NextBtn").click(function() {
								portfolioMoveNext();
							});
							$('#'+cId+"-imImageRotate-PrevBtn").click(function() {
								portfolioMovePrev();
							});
						}
						
						for (var i = 0; i < totalItems; i++) {
							img = new Image();
							if (opts.data_map.url_name) {
								obj = getImageObject(daAR[i]);
								div = $('<div></div>').attr({
									id: cId + "-imImageRotate-DisplayCntnr" + i,
									"class": "imImageRotate-DisplayCntnr"
								}).append($('<a></a>').attr({
									'href': obj.url,
									'target': obj.tgt
								}).append($(img).attr({
									src: obj.pic,
									title: obj.title
								})),
								$('<div></div>').attr({
									id: cId + "-imImageRotate-TextCntnr" + i,
									"class": "imImageRotate-TextCntnr"
								}).append($('<h2></h2>').html(obj.title),
								$('<p></p>').html(obj.desc))
								).appendTo("#" + cId + "-imImageRotate-Slider");
							}
							else {
								pic = opts.base_path + daAR[i];
								$('<div></div>').attr('id', cId + "-imImageRotate-DisplayCntnr" + i).append($(img).attr({
									src: pic,
									title: daAR[i]
								})).appendTo("#" + cId + "-imImageRotate-Slider");
							}
							if (showVertNav) {
								$("#"+cId + "-imImageRoate-Vert-Nav ul").append($('<li></li>').data('liIndex', i));
								if (i == 0) {
									$("#"+cId + "-imImageRoate-Vert-Nav ul li").attr('class', 'selected');
								}
							}
						}
						
						if (showVertNav) {
							$("#"+cId + "-imImageRoate-Vert-Nav ul li").click(function() {
								selectedIndex = $(this).data('liIndex');
								showPortfolio();
							});
						}
						
						if (opts.show_desc == 'onhover') {
							$('#'+cId+' .imImageRotate-DisplayCntnr a').hover(
							    function () {
							    	$(this).siblings('.imImageRotate-TextCntnr').show();
							  	}, 
							  	function () {
							    	$(this).siblings('.imImageRotate-TextCntnr').hide();
							  	}
							);
						} else if (opts.show_desc == 'onload') {
							$('#'+cId+' .imImageRotate-TextCntnr').show();
						}
						
						displayWidth = $('#' + cId + "-imImageRotate-DisplayCntnr0").width();
						if (opts.interval) {
							setInterval(portfolioChange, opts.interval);
						}
					}
	};
	
	function getImageObject(ar) {
		var obj =  new Object();
		obj.pic = opts.base_path + ar[0]; 
		obj.url = ar[1];
		obj.title = ar[2];
		obj.desc = ar[3],
		obj.tgt = ar[4];
		return obj;
	};
	
	function setFadeInterval() {
		intervalFadeIn();
		setInterval(intervalFadeOut, opts.interval);
	};
	
	function intervalFadeIn() {
		$("#imImageRotate"+imgCnt).fadeIn(opts.speed, function(){
			$("#imImageRotate"+imgCnt).css('left', '0px');
		});
	};
	
	function intervalFadeOut() {
		$("#imImageRotate"+imgCnt).fadeOut(opts.speed);
		if (imgCnt == totalItems - 1) {
			$("#imImageRotate"+imgCnt).css('left', -aImages[imgCnt]);
			imgCnt = 0;
		} else {
			imgCnt++;
		}
		//imgCnt = (imgCnt == totalItems - 1) ? 0 : imgCnt + 1;
		if (imgCnt == 0) {
			$("#imImageRotate0").css('left', 0);
		}
		else {
			$("#imImageRotate" + imgCnt).css('left', -aImages[imgCnt]);
		}
		intervalFadeIn();
	};
	
	function imgFadeIn() {
		$("#imImageRotate"+imgCnt).fadeIn(opts.speed, function(){
			imgFadeOut();
		});
	};
	
	function imgFadeOut() {
		$("#imImageRotate"+imgCnt).fadeOut(opts.speed, function(){
			imgCnt = (imgCnt == totalItems - 1) ? 0 : imgCnt + 1;
			imgFadeIn();
		});
	};
	
	function setCarouselInterval() {
		setInterval(imgCarousel, opts.interval);
	};
	
	function imgCarousel() {
		$('ul', $this).animate({left: -nLeft+'px'}, opts.speed, function() {
			var lPos = $('ul li:last', $this).offset();
			var thisPos = $this.offset();
			if ((lPos.left + $('ul li:last', $this).width()) < (thisPos.left + $this.width())) {
				imgCnt = 0;
				nLeft = 0;
			} else {
				imgCnt++;
				nLeft += aImages[imgCnt-1];
			}
		});
	};
	
	function portfolioMoveNext() {
		if (selectedIndex < totalItems-1) {
			selectedIndex++;
			showPortfolio();
		}
	};
	
	function portfolioMovePrev() {
		if (selectedIndex > 0) {
			selectedIndex--;
			showPortfolio();
		}
	};
		
	function portfolioChange() {
		selectedIndex = (selectedIndex < totalItems-1) ? selectedIndex + 1 : 0;
		showPortfolio();
	};
	
	function showPortfolio() {
		//setVertNav();
		doPortfolioMove();
	};
	
	function setVertNav() {
		$("#"+cId + "-imImageRoate-Vert-Nav ul li").removeClass('selected');
		var nav = $("#"+cId + "-imImageRoate-Vert-Nav ul li")[selectedIndex];
		$(nav).addClass('selected');
	};
	
	function doPortfolioMove() {
		var fin = -(selectedIndex*displayWidth);
		$("#"+cId+"-imImageRotate-Slider").animate({left: fin+'px'}, opts.speed, function() {
			setVertNav();
		});
		currentIndex = selectedIndex;
	};
};

$.bannerRotater.defaults = {
	mode: 'random',//rotate, carousel, portfolio
	interval: '',//5000
	image_url: '',
	data: '',
	images: '',//can be used instead of image_url. contains comma delimited list of images
	return_type: 'list', //list, json
	base_path: '',
	url_target: '_blank',
	data_map: '', //{image_name: '', image_title: '', url_name: '', url_target: '_blank', image_desc: ''}
	speed: 1500,
	easing: 'easeOutElastic',
	show_side_nav: true,
	show_vert_nav: 'top', // bottom, 
	show_desc: 'onhover'// onload, never
};
})(jQuery);		   
