//jQuery Custom Core v1.0 by DanOlsavsky.com
//Includes: jCarousel Lite, Hover Intent and Mega Menu
/////////////////// Custom Core UI - Accordion
(function($) {
    $.fn.customCoreAccordion = function(speed) {
        //Find and hide all accordion content
        $('.accordionContent', this).hide();
        //Add .active class to first trigger, then open the next container
        $('.accordionTrigger:first').addClass('active').next("div").show();
        //On click execute event
        $('a.accordionTrigger', this).click(function() {
            //If the next container is closed
            if ($(this).next().is(':hidden')) {
                //Remove .active state and close the next container
                $('a.accordionTrigger').removeClass('active').next().slideUp(speed);
                //Add .active to clicked trigger and open the next container
                $(this).toggleClass('active').next().slideDown(speed);
            }
            return false;
        });
    }
})(jQuery);

/////////////////// Custom Core UI - Tabs
(function($) {
    $.fn.customCoreTabs = function() {
        //Find and hide all tab content
        $(".tabContent").hide();
        //Add .active class to first tab, then open the next container
        $(".tabTrigger:first").addClass("active").show();
        //Show first tab content
        $(".tabContent:first").show();
        //On click execute event
        $(".tabTrigger").click(function() {
            //Remove .active state and close the next container
            $(".tabTrigger").removeClass("active");
            //Add .active to selected tab and open the next container
            $(this).addClass("active");
            //Hide all tab content
            $(".tabContent").hide();
            //Find the href attribute value to identify the active tab + content
            var activeTab = $(this).find("a").attr("href");
            //Fade in the active ID content
            $(activeTab).fadeIn();
            return false;
        });
    }
})(jQuery);

//////////////////// 3rd Party - jCarousel Lite by Ganeshji Marwaha

(function($) {  
$.fn.jCarouselLite = function(o) {
    o = $.extend({
        btnPrev: null,
        btnNext: null,
        btnGo: null,
        mouseWheel: false,
        auto: null,
        speed: 200,
        easing: null,
        vertical: false,
        circular: true,
        visible: 3,
        start: 0,
        scroll: 1,
        beforeStart: null,
        afterEnd: null
    }, o || {});
    // Returns the element collection. Chainable.
	return this.each(function() {                           
        var running = false, animCss=o.vertical?"top":"left", sizeCss=o.vertical?"height":"width";
        var div = $(this), ul = $("ul", div), tLi = $("li", ul), tl = tLi.size(), v = o.visible;
        if(o.circular) {
            ul.prepend(tLi.slice(tl-v-1+1).clone())
              .append(tLi.slice(0,v).clone());
            o.start += v;
        }
        var li = $("li", ul), itemLength = li.size(), curr = o.start;
        div.css("visibility", "visible");
        li.css({overflow: "hidden", float: o.vertical ? "none" : "left"});
        ul.css({margin: "0", padding: "0", position: "relative", "list-style-type": "none", "z-index": "1"});
        div.css({overflow: "hidden", position: "relative", "z-index": "2", left: "0px"});
        var liSize = o.vertical ? height(li) : width(li);   // Full li size(incl margin)-Used for animation
        var ulSize = liSize * itemLength;                   // size of full ul(total length, not just for the visible items)
        var divSize = liSize * v;                           // size of entire div(total length for just the visible items)
        li.css({width: li.width(), height: li.height()});
        ul.css(sizeCss, ulSize+"px").css(animCss, -(curr*liSize));
        div.css(sizeCss, divSize+"px");                     // Width of the DIV. length of visible images
        if(o.btnPrev)
            $(o.btnPrev).click(function() {
                return go(curr-o.scroll);
            });
        if(o.btnNext)
            $(o.btnNext).click(function() {
                return go(curr+o.scroll);
            });
        if(o.btnGo)
            $.each(o.btnGo, function(i, val) {
                $(val).click(function() {
                    return go(o.circular ? o.visible+i : i);
                });
            });
        if(o.mouseWheel && div.mousewheel)
            div.mousewheel(function(e, d) {
                return d>0 ? go(curr-o.scroll) : go(curr+o.scroll);
            });
        if(o.auto)
            setInterval(function() {
                go(curr+o.scroll);
            }, o.auto+o.speed);
        function vis() {
            return li.slice(curr).slice(0,v);
        };
        function go(to) {
            if(!running) {
                if(o.beforeStart)
                    o.beforeStart.call(this, vis());
                if(o.circular) {            // If circular we are in first or last, then goto the other end
                    if(to<=o.start-v-1) {           // If first, then goto last
                        ul.css(animCss, -((itemLength-(v*2))*liSize)+"px");
                        // If "scroll" > 1, then the "to" might not be equal to the condition; it can be lesser depending on the number of elements.
                        curr = to==o.start-v-1 ? itemLength-(v*2)-1 : itemLength-(v*2)-o.scroll;
                    } else if(to>=itemLength-v+1) { // If last, then goto first
                        ul.css(animCss, -( (v) * liSize ) + "px" );
                        // If "scroll" > 1, then the "to" might not be equal to the condition; it can be greater depending on the number of elements.
                        curr = to==itemLength-v+1 ? v+1 : v+o.scroll;
                    } else curr = to;
                } else {                    // If non-circular and to points to first or last, we just return.
                    if(to<0 || to>itemLength-v) return;
                    else curr = to;
                }                           // If neither overrides it, the curr will still be "to" and we can proceed.
                running = true;
                ul.animate(
                    animCss == "left" ? { left: -(curr*liSize) } : { top: -(curr*liSize) } , o.speed, o.easing,
                    function() {
                        if(o.afterEnd)
                            o.afterEnd.call(this, vis());
                        running = false;
                    }
                );
                // Disable buttons when the carousel reaches the last/first, and enable when not
                if(!o.circular) {
                    $(o.btnPrev + "," + o.btnNext).removeClass("disabled");
                    $( (curr-o.scroll<0 && o.btnPrev)
                        ||
                       (curr+o.scroll > itemLength-v && o.btnNext)
                        ||
                       []
                     ).addClass("disabled");
                }
            }
            return false;
        };
    });
};
function css(el, prop) {
    return parseInt($.css(el[0], prop)) || 0;
};
function width(el) {
    return  el[0].offsetWidth + css(el, 'marginLeft') + css(el, 'marginRight');
};
function height(el) {
    return el[0].offsetHeight + css(el, 'marginTop') + css(el, 'marginBottom');
};
})(jQuery);

//////////////////// 3rd Party - Hover Intent by Brian Cherne
(function($) {
	$.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);

//////////////////// 3rd Party - Mega Menu by Soh Tanaka
$(document).ready(function() {
	//Mega Menu Hover
	function megaHoverOver(){
		//Find subnavigation and fade it in
		$(this).find(".sub-navigation").stop().fadeTo('fast', 1).show(); 
		//Function to calculate total width of all ul's
		(function($) {
			jQuery.fn.calcSubWidth = function() {
				//Row width equals zero
				rowWidth = 0;
				//For each ul
				$(this).find("ul").each(function() {
					//Add each ul's width together
					rowWidth += $(this).width();
				});
			};
		})(jQuery); 
		//Find the row if the row exists
		if ( $(this).find(".row").length > 0 ) {
			//Biggest row equals zero
			var biggestRow = 0;	
		   //For each row
		   $(this).find(".row").each(function() {
				//Call function to calculate width of all ul's
				$(this).calcSubWidth();
				//Find thebiggest row
				if(rowWidth > biggestRow) {
					//Set biggestRow var to rowWidth var
					biggestRow = rowWidth;
				}
			});
			//Find the widest sub navigation row and set the sub navigation row width to the widest
			$(this).find(".sub-navigation").css({'width' :biggestRow}); 
			//Find the last row of the subnavigation and set it's margin to zero
			$(this).find(".row:last").css({'margin':'0'});  
		} 
		//If the row does not exist
		else {
			//Call function to calculate width of all ul's
			$(this).calcSubWidth();  
			//Find the  sub navigation row width and set the sub navigation row width with css
			$(this).find(".sub-navigation").css({'width' : rowWidth}); 
		}
	}
	//Mega menu Hover Out
	function megaHoverOut(){
		// Find the sub navigation containers and fade their opaticy to zero
		$(this).find(".sub-navigation").stop().fadeTo('fast', 0, function() {
			//Hide the subnavigation elements after fading them out
			$(this).hide();
		});
	}
	//Set custom configurations
	var config = {
		 // number = sensitivity threshold (must be 1 or higher)
		 sensitivity: 2,
		 // number = milliseconds for onMouseOver polling interval
		 interval: 100,
		 // function = onMouseOver callback (REQUIRED)
		 over: megaHoverOver,
		 // number = milliseconds delay before onMouseOut
		 timeout: 500,
		 // function = onMouseOut callback (REQUIRED)
		 out: megaHoverOut 
	};
	//Fade sub nav to 0 opacity on default
	$("ul#top-navigation li .sub-navigation").css({'opacity':'0'}); 
	//Trigger Hover intent with custom configurations
	$("ul#top-navigation li").hoverIntent(config);
	
//////////////////// Custom Core - Tooltip 
	$.fn.extend({
		_offset: $.fn.offset,
		offset: function(newOffset) {
		return newOffset ? this.setXY(newOffset) : this._offset();
	},
	setXY: function(newOffset) {
		return this.each(function() {
			var el = this;
			var hide = false;
			if ($(el).css('display') == 'none') {
				hide = true;
				$(el).show();
			}
			var style_pos = $(el).css('position');
			// default to relative
			if (style_pos == 'static') {
				$(el).css('position', 'relative');
				style_pos = 'relative';
			}
			var offset = $(el).offset();
			if (offset) {
				var delta = {
					left: parseInt($(el).css('left'), 10),
					top: parseInt($(el).css('top'), 10)
				};
				// in case of 'auto'
				if (isNaN(delta.left))
					delta.left = (style_pos == 'relative') ? 0 : el.offsetLeft;
				if (isNaN(delta.top))
					delta.top = (style_pos == 'relative') ? 0 : el.offsetTop;
				if (newOffset.left || newOffset.left === 0)
					$(el).css('left', newOffset.left - offset.left + delta.left + 'px');
				if (newOffset.top || newOffset.top === 0)
					$(el).css('top', newOffset.top - offset.top + delta.top + 'px');
			}
			if (hide) $(el).hide();
		});
	}
	});
	$('.tooltipContainer').hide();
	$('#dialog .tooltipContainer').show();
	$('.openTooltip').show();
	$('.tooltipOpen').click(function(e) {
		// Capture the event info.
		var event = e || window.event; // Some browsers (IE) do not pass the even args to the handler, the event object must be grabbed from the window.
		var trigger = event.target || event.srcElement; // Some browsers (IE) pass the "sender" of the event as srcElement instead of the W3C standard target.
		var $trigger = $(trigger);
		// Hide all bubbles.
		$('.tooltipContainer').hide();
		$('#dialog .tooltipContainer').show();
		// Find the class I'm interested in.
		var $this = $(this);
		var targetIndicator = $this.attr('id');
		// Decide where to put the bubbles.
		if (!$('#tooltip-' + targetIndicator).hasClass('staticTooltip')) {
		//var xOffset = $trigger.offset().left - $trigger.parent().offset().left;
		//var yOffset = $trigger.offset().top - $trigger.parent().offset().top;
		var xOffset = e.pageX + 20; // - $trigger.parent().offset().left;
		var yOffset = e.pageY - 10; // - $trigger.parent().offset().top;
		//alert( xOffset + " = " + e.pageX + " - " + $trigger.parent().offset().left + "\n" + yOffset + " = " + e.pageY + " - " + $trigger.parent().offset().top );
		$('#tooltip-' + targetIndicator).offset({ left: xOffset, top: yOffset });
		//$('.staticBubble').offset({ left: 342, top: 325});
	}
	// Make the bubble visible.
	$('#tooltip-' + targetIndicator).toggle();
		return false;
	});
	$('.tooltipClose').click(function() {
		var $this = $(this);
		$this.parent().hide();
		return false;
	});
});
