/* 
 * NimbleHost Theme Functions
 * Copyright 2010. All rights reserved.
 *
 */

var $dexture = jQuery.noConflict();

function menuFunctions() {
	if ((typeof nhAccordionMenu != 'function') && !($dexture.browser.opera)) {
		$dexture('<span class="currentMenuItemBorder"></span>').appendTo('#menu ul .current');
		$dexture('<span class="ancestorMenuItemBorder"></span>').appendTo('#menu ul .currentAncestor');
		var mb_currentItemWidth = $dexture('#menu ul .current').width();
		var mb_ancestorItemWidth = $dexture('#menu ul .currentAncestor').width();
		$dexture('.currentMenuItemBorder').css({'width': mb_currentItemWidth}).fadeIn(1000);
		$dexture('.ancestorMenuItemBorder').css({'width': mb_ancestorItemWidth}).fadeIn(1000);
	}	
	$dexture('#menu ul a').parent().prepend($dexture('<span class="menuDivider">&nbsp;/&nbsp;</span>'));
	$dexture('#menu ul .menuDivider:first').css({'display': 'none'});
}

function visitorInteractionPanel() {
	$dexture('<div id="visitorInteractionPanel"><ul></ul></div>').appendTo('#pageTopContentWrapper');
	
	if( $dexture('#visitorInteractionPanel').is(':visible') ) {
		$dexture('<li><p id="adjustWidth">< ></p></li>').appendTo('#visitorInteractionPanel ul');
		var aw_currentWidth = $dexture('#mainContentWrapper').width();
		var aw_headerImageBackgroundPosition = $dexture('.headerImage').css('background-position');
		var aw_changedWidth = false;
		$dexture('#adjustWidth').click(function(){
			if( aw_currentWidth != "92%" && !aw_changedWidth ) {
				$dexture('#pageTopContent, #mainContentTopShadow, #mainContentWrapper, #breadcrumbContainer, #footer, #extraContainer6').animate({width: "92%"}, 'normal');
				if ( $dexture('.headerImage').is(':visible') ) {
					$dexture('.headerImage').fadeTo('normal', 0).animate({'backgroundPosition': '0px 0px','opacity': 1}, 1100);
				}
				if ( $dexture('#extraContainer1').is(':visible') ) {
					$dexture('#extraContainer1').animate({width: "92%"}, 'normal');
				}
				
				aw_changedWidth = true;
			} else {
				$dexture('#pageTopContent, #mainContentTopShadow, #mainContentWrapper, #breadcrumbContainer, #footer, #extraContainer6').animate({width: aw_currentWidth}, 'normal');
				$dexture('.headerImage').animate({"backgroundPosition": aw_headerImageBackgroundPosition}, 1100);
				
				if ( $dexture('#extraContainer1').is(':visible') ) {
					$dexture('#extraContainer1').animate({width: aw_currentWidth}, 'normal');
				}
				
				aw_changedWidth = false;
			}
		});
		
		$dexture('<li><div id="headerColor1"></div></li><li><div id="headerColor2"></div></li><li><div id="headerColor3"></div></li>').appendTo('#visitorInteractionPanel ul');
		var headerColor1 = $dexture('#headerColor1').css('background-color');
		var headerColor2 = $dexture('#headerColor2').css('background-color');
		var headerColor3 = $dexture('#headerColor3').css('background-color');
		$dexture('#headerColor1').click(function(){
			$dexture('#pageTopBg').animate({'backgroundColor':headerColor1}, 500);
			$dexture('#footerWrapper').animate({'backgroundColor':headerColor1}, 500);
		});
		$dexture('#headerColor2').click(function(){
			$dexture('#pageTopBg').animate({'backgroundColor':headerColor2}, 500);
			$dexture('#footerWrapper').animate({'backgroundColor':headerColor2}, 500);
		});
		$dexture('#headerColor3').click(function(){
			$dexture('#pageTopBg').animate({'backgroundColor':headerColor3}, 500);
			$dexture('#footerWrapper').animate({'backgroundColor':headerColor3}, 500);
		});
		
		$dexture('<li><p id="adjustTextSize">a A</p></li>').appendTo('#visitorInteractionPanel ul');
		var textSize = 1;
		var newFontSize = '1em';
		$dexture('#adjustTextSize').click(function(){		
			if ( textSize == 1 ) {
				newFontSize = '1.15em';
				textSize ++;
			} else if ( textSize == 2 ) {
				newFontSize = '0.85em';
				textSize ++;
			} else if ( textSize == 3 ) {
				newFontSize = '1em';
				textSize = 1;
			} else {
				newFontSize = '1em';
				textSize = 1;
			}
			$dexture('#contentContainer, #sidebarContainer, #footerWrapper, #extraContainer1, #extraContainer2, #extraContainer3, #extraContainer4, #extraContainer5, #extraContainer6').animate({fontSize: newFontSize}, 'normal');
		});
	}
}


function iPadAdjustments() {
	$dexture('#visitorInteractionPanel').stop().fadeTo('fast', 1);
	$dexture('#adjustWidth').css({'display':'none'});
	
	if ( $dexture('#mainContentWrapper').width() > '700' ) {
		if ( window.orientation == 0 ) {
			$dexture('#pageTopContent, #mainContentTopShadow, #mainContentWrapper, #footer, #breadcrumbContainer, #extraContainer1, #extraContainer6').css({'width': '90%'});
		} else if ( (window.orientation == 90) || (window.orientation == -90) ) {
			$dexture('#pageTopContent, #mainContentTopShadow, #mainContentWrapper, #footer, #breadcrumbContainer, #extraContainer1, #extraContainer6').css({'width': '86%'});
		}
	}
	
	$dexture('<li><p id="iPadCloseButton">X</p></li>').appendTo('#visitorInteractionPanel ul');
	
	$dexture('#visitorInteractionPanel').click(function(){
		if ( !($dexture('#visitorInteractionPanel ul').is(':visible')) ) {	
			$dexture('#visitorInteractionPanel ul').slideDown('normal');
		}
	});
	
	$dexture('#iPadCloseButton').click(function(){	
		$dexture('#visitorInteractionPanel ul').slideUp('normal');
	});
}

function iPhoneDesktopAdjustments() {
	if(((navigator.userAgent.match(/iPhone/i))||(navigator.userAgent.match(/iPod/i))||(navigator.userAgent.match(/Android/))||(navigator.userAgent.match(/webOS/)))){
		visitorInteractionPanel();
		$dexture('#adjustWidth').css({'display':'none'});
		$dexture('#pageTopContent, #mainContentTopShadow, #mainContentWrapper, #footer, #breadcrumbContainer, #extraContainer1, #extraContainer6').css({'width': '90%'});
		
		$dexture('<li><p id="iPadCloseButton">X</p></li>').appendTo('#visitorInteractionPanel ul');
		
		$dexture('#visitorInteractionPanel').click(function(){
			if ( !($dexture('#visitorInteractionPanel ul').is(':visible') ) ) {
				$dexture('#visitorInteractionPanel').stop().fadeTo('fast', 1);
				$dexture('#visitorInteractionPanel ul').slideDown('normal');
			}
		});
		
		$dexture('#iPadCloseButton').click(function(){	
			$dexture('#visitorInteractionPanel ul').slideUp('normal');
			$dexture('#visitorInteractionPanel').pulse({
				opacity: [0,1]
			}, {
				duration: 2000,
				times: 1000
			});
		});
	}
}

function mobileMenu() {
	var mobileMenuConfig = {
		sensitivity: 3, // number = sensitivity threshold (must be 1 or higher)    
		interval: 50, // number = milliseconds for onMouseOver polling interval    
		over: revealMobileMenuChildren, // function = onMouseOver callback (REQUIRED)    
		timeout: 300, // number = milliseconds delay before onMouseOut    
		out: hideMobileMenuChildren
		};
	
	function revealMobileMenuChildren(){
		$dexture(this).find("ul:first").css({visibility: "visible",display: "none"}).slideDown(400);
	}
	
	function hideMobileMenuChildren(){
		$dexture(this).find("ul:first").slideUp(500);
	}
	
	$dexture("#menu ul ul").parent().addClass("ddarrow");
	$dexture("#menu ul ul").parent().append("<span></span>");
	$dexture("#menu ul ul").css({display: "none"}); // Opera Fix
	$dexture("#menu ul li").hoverIntent(mobileMenuConfig);
	
	$dexture('#mobileMenuTab').click(function () {
		$dexture('#menu').slideToggle('medium', function() {
			if ( $dexture('#menu').is(':visible') ) {
				$dexture('#mobileMenuTab').animate({backgroundPosition: '0px 0px'}, 0);
			} else {
				$dexture('#mobileMenuTab').animate({backgroundPosition: '0px -50px'}, 0);
			}
		});
	});
}

function mobileImageResize() {
	$dexture('.imageStyle').each(function(){
		if( window.orientation == 0 ){
			if( ($dexture(this).width() > 280) ) {
				$dexture(this).width(280);
			}
		} else if ( (window.orientation == 90) || (window.orientation == -90) ) {
			if( ($dexture(this).width() > 440) ) {
				$dexture(this).width(440);
			}
		}
	});
	$dexture('#logo img').each(function(){
		if( window.orientation == 0 ){
			if( ($dexture(this).width() > 300) ) {
				$dexture(this).width(300);
			}
		} else if ( (window.orientation == 90) || (window.orientation == -90) ) {
			if( ($dexture(this).width() > 460) ) {
				$dexture(this).width(460);
			}
		}
	});
}

function mobileViewport(){
	if(((navigator.userAgent.match(/iPhone/i))||(navigator.userAgent.match(/iPod/i))||(navigator.userAgent.match(/Android/))||(navigator.userAgent.match(/webOS/)))  && ($dexture('#mobileMenuTab').is(':visible'))){
		$dexture('head').append('<meta name = "viewport" content = "width=device-width; initial-scale=1.0; maximum-scale=1.0;" />');
	} 
}
$dexture(function(){ mobileViewport(); });

/* ExtraContent r1.3 02-23-09 12:33 */

function extraContent(){
	var i=0;
	while (i<=10) {
		$dexture('#myExtraContent'+i+' script').remove();
		$dexture('#myExtraContent'+i).appendTo('#extraContainer'+i);
		i++;
	}
}

function standardRwPageEnhancements() {
	var ptcTitle = $dexture('#pageTopContent .title h1').css('font-size');
	var mctsDisplay = $dexture('#mainContentTopShadow').css('display');
	$dexture('#mainContentTopShadow').height(); /* IE8 fix so it can use .animate() function */
	if ( (ptcTitle == '40px') && (mctsDisplay == 'block') ) {
		$dexture('#mainContentWrapper').animate({marginTop: '-=20px'}, 0);
		$dexture('#mainContentTopShadow').animate({marginTop: '-=20px',height: '+=20px'}, 0);
		$dexture('#mainContentCornerShadowLeft, #mainContentCornerShadowRight').animate({top: '+=20px'}, 0);
	} else if ( (ptcTitle == '80px') && (mctsDisplay == 'block') ) {
		$dexture('#mainContentWrapper').animate({marginTop: '+=20px'}, 0);
		$dexture('#mainContentTopShadow').animate({marginTop: '+=20px',height: '-=20px'}, 0);
		$dexture('#mainContentCornerShadowLeft, #mainContentCornerShadowRight').animate({top: '-=20px'}, 0);
	} else if ( (ptcTitle == '100px') && (mctsDisplay == 'block') ) {
		$dexture('#mainContentWrapper').animate({marginTop: '+=45px'}, 0);
		$dexture('#mainContentTopShadow').animate({marginTop: '+=45px',height: '-=45px'}, 0);
		$dexture('#mainContentCornerShadowLeft, #mainContentCornerShadowRight').animate({top: '-=45px'}, 0);
	}
	$dexture('<div class="entryDivider"></div>').insertAfter('.filesharing-item');
	$dexture('.filesharing-item').addClass('enhancedFilesharingItem');
	
	setTimeout(function() { 
		var browserHeight = $dexture(window).height();
		var siteContentHeight = $dexture('body').height();
		if ( browserHeight > siteContentHeight ) {
			var adjustHeight = browserHeight - siteContentHeight;
			$dexture('#mainContentWrapper').animate({'height': '+=' + adjustHeight}, 1000);
		}
	}, 1000);
}


/*
 * jQuery Color Animations
 * Copyright 2007 John Resig
 * Released under the MIT and GPL licenses.
 */

(function(jQuery){

    // We override the animation for all of these color styles
    jQuery.each(['backgroundColor', 'borderBottomColor', 'borderLeftColor', 'borderRightColor', 'borderTopColor', 'color', 'outlineColor'], function(i,attr){
        jQuery.fx.step[attr] = function(fx){
            if ( !fx.colorInit ) {
                fx.start = getColor( fx.elem, attr );
                fx.end = getRGB( fx.end );
                fx.colorInit = true;
            }

            fx.elem.style[attr] = "rgb(" + [
                Math.max(Math.min( parseInt((fx.pos * (fx.end[0] - fx.start[0])) + fx.start[0]), 255), 0),
                Math.max(Math.min( parseInt((fx.pos * (fx.end[1] - fx.start[1])) + fx.start[1]), 255), 0),
                Math.max(Math.min( parseInt((fx.pos * (fx.end[2] - fx.start[2])) + fx.start[2]), 255), 0)
            ].join(",") + ")";
        }
    });

    // Color Conversion functions from highlightFade
    // By Blair Mitchelmore
    // http://jquery.offput.ca/highlightFade/

    // Parse strings looking for color tuples [255,255,255]
    function getRGB(color) {
        var result;

        // Check if we're already dealing with an array of colors
        if ( color && color.constructor == Array && color.length == 3 )
            return color;

        // Look for rgb(num,num,num)
        if (result = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(color))
            return [parseInt(result[1]), parseInt(result[2]), parseInt(result[3])];

        // Look for rgb(num%,num%,num%)
        if (result = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(color))
            return [parseFloat(result[1])*2.55, parseFloat(result[2])*2.55, parseFloat(result[3])*2.55];

        // Look for #a0b1c2
        if (result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(color))
            return [parseInt(result[1],16), parseInt(result[2],16), parseInt(result[3],16)];

        // Look for #fff
        if (result = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(color))
            return [parseInt(result[1]+result[1],16), parseInt(result[2]+result[2],16), parseInt(result[3]+result[3],16)];

        // Look for rgba(0, 0, 0, 0) == transparent in Safari 3
        if (result = /rgba\(0, 0, 0, 0\)/.exec(color))
            return colors['transparent'];

        // Otherwise, we're most likely dealing with a named color
        return colors[jQuery.trim(color).toLowerCase()];
    }

    function getColor(elem, attr) {
        var color;

        do {
            color = jQuery.curCSS(elem, attr);

            // Keep going until we find an element that has color, or we hit the body
            if ( color != '' && color != 'transparent' || jQuery.nodeName(elem, "body") )
                break;

            attr = "backgroundColor";
        } while ( elem = elem.parentNode );

        return getRGB(color);
    };

    // Some named colors to work with
    // From Interface by Stefan Petre
    // http://interface.eyecon.ro/

    var colors = {
        aqua:[0,255,255],
        azure:[240,255,255],
        beige:[245,245,220],
        black:[0,0,0],
        blue:[0,0,255],
        brown:[165,42,42],
        cyan:[0,255,255],
        darkblue:[0,0,139],
        darkcyan:[0,139,139],
        darkgrey:[169,169,169],
        darkgreen:[0,100,0],
        darkkhaki:[189,183,107],
        darkmagenta:[139,0,139],
        darkolivegreen:[85,107,47],
        darkorange:[255,140,0],
        darkorchid:[153,50,204],
        darkred:[139,0,0],
        darksalmon:[233,150,122],
        darkviolet:[148,0,211],
        fuchsia:[255,0,255],
        gold:[255,215,0],
        green:[0,128,0],
        indigo:[75,0,130],
        khaki:[240,230,140],
        lightblue:[173,216,230],
        lightcyan:[224,255,255],
        lightgreen:[144,238,144],
        lightgrey:[211,211,211],
        lightpink:[255,182,193],
        lightyellow:[255,255,224],
        lime:[0,255,0],
        magenta:[255,0,255],
        maroon:[128,0,0],
        navy:[0,0,128],
        olive:[128,128,0],
        orange:[255,165,0],
        pink:[255,192,203],
        purple:[128,0,128],
        violet:[128,0,128],
        red:[255,0,0],
        silver:[192,192,192],
        white:[255,255,255],
        yellow:[255,255,0],
        transparent: [255,255,255]
    };

})(jQuery);


/**
 * Pulse plugin for jQuery 
 * ---
 * @author James Padolsey (http://james.padolsey.com)
 * @version 0.1
 * @updated 16-DEC-09
 * ---
 * Note: In order to animate color properties, you need
 * the color plugin from here: http://plugins.jquery.com/project/color
 * ---
 * @info http://james.padolsey.com/javascript/simple-pulse-plugin-for-jquery/
 */

jQuery.fn.pulse = function( prop, speed, times, easing, callback ) {
    
    if ( isNaN(times) ) {
        callback = easing;
        easing = times;
        times = 1;
    }
    
    var optall = jQuery.speed(speed, easing, callback),
        queue = optall.queue !== false,
        largest = 0;
        
    for (var p in prop) {
        largest = Math.max(prop[p].length, largest);
    }
    
    optall.times = optall.times || times;
    
    return this[queue?'queue':'each'](function(){
        
        var counts = {},
            opt = jQuery.extend({}, optall),
            self = jQuery(this);
            
        pulse();
        
        function pulse() {
            
            var propsSingle = {},
                doAnimate = false;
            
            for (var p in prop) {
                
                // Make sure counter is setup for current prop
                counts[p] = counts[p] || {runs:0,cur:-1};
                
                // Set "cur" to reflect new position in pulse array
                if ( counts[p].cur < prop[p].length - 1 ) {
                    ++counts[p].cur;
                } else {
                    // Reset to beginning of pulse array
                    counts[p].cur = 0;
                    ++counts[p].runs;
                }
                
                if ( prop[p].length === largest ) {
                    doAnimate = opt.times > counts[p].runs;
                }
                
                propsSingle[p] = prop[p][counts[p].cur];
                
            }
            
            opt.complete = pulse;
            opt.queue = false;
            
            if (doAnimate) {
                self.animate(propsSingle, opt);
            } else {
                optall.complete.call(self[0]);
            }
            
        }
            
    });
    
};

(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);
