//jQuery.noConflict();
$(document).ready(function(){		
//jQuery(document).ready(function($){
	
LazyLoad.js(['/images/esx/Template/2011New/js/mylibs/bookmark_bubble.js','/images/esx/Template/2011New/js/mylibs/page.js' ]);


// -------------------------------------------------------------------------------------------
// Superfish dropdown menus
// -------------------------------------------------------------------------------------------
LazyLoad.js(['/images/esx/Template/2011New/js/mylibs/superfish/supersubs.js', '/images/esx/Template/2011New/js/mylibs/superfish/hoverIntent.js', '/images/esx/Template/2011New/js/mylibs/superfish/superfish.js'], function() {
	$('.tmenu').supersubs({ 
		minWidth:    12,   // minimum width of sub-menus in em units 
		maxWidth:    18   // maximum width of sub-menus in em units 
		//extraWidth:  1     // extra width can ensure lines don't sometimes turn over 
						   // due to slight rounding differences and font-family 
	}).superfish({ 
		hoverClass:   'sfHover',          			  // the class applied to hovered list items 
		pathClass:    'TNCurrent', 			  		  // the class you have applied to list items that lead to the current page 
		pathLevels:   1,                  			  // the number of levels of submenus that remain open or are restored using pathClass 
		delay:        400,               			  // the delay in milliseconds that the mouse can remain outside a submenu without it closing 
		animation:    {opacity:'show',height:'show'},  // fade-in and slide-down animation 
		speed:        'fast',                          // faster animation speed 
		autoArrows:   true,                            // disable generation of arrow mark-up 
		dropShadows:  true                             // disable drop shadows 
	});  
});

// -------------------------------------------------------------------------------------------
// Scroll to top
// -------------------------------------------------------------------------------------------

var blue_css = { background: '#E5F6FE',	color: '#4D9FBF', border: '2px solid #ADD9ED' }
var dark_css = { background: '#404040',	color: '#f3f3f3', border: '2px solid #303030' }
var light_css = { background: '#f1f1f1', color: '#454545', border: '2px solid #E2E2E2' }
var taup_css = { background: '#E8E6E3', color: '#928b81', border: '2px solid #D7D3D0' }
		
/*---Creates the scroll to top link---*/
$('footer').append('<a href="javascript:;" id="toTop">^ Scroll to Top</a>');
	$('#toTop').css({ 
		width: '85px',
		'font-size': '10px',
		padding: '5px 5px 10px 5px',
		position: 'fixed',
		'z-index': '120',
		bottom: '-5px',
		right: '10px',
		cursor: 'pointer',
		'text-align': 'center',
		'text-decoration': 'none',
		'font-family': 'arial',
		'-moz-border-radius': '5px',
		'-webkit-border-radius': '5px',
		'border-radius': '5px'
});
$('#toTop').css(dark_css)


//Mobile devise detection
var deviceAgent = navigator.userAgent.toLowerCase();
var agentID = deviceAgent.match(/(iphone|ipod|ipad|android)/);
if (agentID) {	
	//stick the footer at the bottom of the page if we're on an iPad/iPhone due to viewport/page bugs in mobile webkit
	$("#toTop").css("position", "static");	
}
			
/*---Starts the scroll to top function that uses the link above. This must come after the link is created above.---*/
$.fn.scrollToTop=function(){$(this).hide().removeAttr("href");if($(window).scrollTop()!="0"){$(this).fadeIn("slow")}var a=$(this);$(window).scroll(function(){if($(window).scrollTop()=="0"){$(a).fadeOut("slow")}else{$(a).fadeIn("slow")}});$(this).click(function(){$("html, body").animate({scrollTop:0},"slow")})}
$("#toTop").scrollToTop();
$("#slides .pagination li a").click(function(){$("html, body").animate({scrollTop:0},"slow")});

// -------------------------------------------------------------------------------------------
// Slides code
// -------------------------------------------------------------------------------------------

// Gets the CSS for the slider 
//if ($('.slides_container').length) { // implies *not* zero  
//	var SliderCSS = 'js/slider/slider.css'
//	if(document.createStyleSheet) {
//		try { document.createStyleSheet(SliderCSS); } catch (e) { }
//	}
//	else {
//		var css;
//		css         = document.createElement('link');
//		css.rel     = 'stylesheet';
//		css.type    = 'text/css';
//		css.media   = "all";
//		css.href    = SliderCSS;
//		document.getElementsByTagName("head")[0].appendChild(css);
//	}
//}
//else {
//    // do nothing 
//}
$.extend($.easing, {
	easeInOutCirc: function (x, t, b, c, d) { 
		if ((t/=d/2) < 1) return -c/2 * (Math.sqrt(1 - t*t) - 1) + b; 
		return c/2 * (Math.sqrt(1 - (t-=2)*t) + 1) + b; 
	}
});

LazyLoad.js(['/images/esx/Template/2011New/js/mylibs/slides/slides.min.jquery.js'], function() {	
$('#slides').slides({
	container: 'slides_container',
	preload: true,
	preloadImage: '/images/esx/Template/2011New/js/mylibs/slides/img/loading.gif',
	pagination: true,
	generatePagination: false,
	generateNextPrev: true,
	play: 10000,
	pause: 2500,
	slideSpeed: 350,
	fadeSpeed: 350,
	hoverPause: true,
	autoHeight: true,
	autoHeightSpeed: 350,
	randomize: false,
	crossfade: false,
	effect: 'slide',
	// Get the starting slide
	start: 1,
		slidesLoaded: function(){
			$('.nav_move').css({ 
			  opacity: 0,
			  width: $('.current').width()+0, 
			  height: $('.current').height()+0 
			});
			$('.current a').fadeTo("slow", 0.60);
			$(".nav_move").fadeTo("slow", 0.60);			
		},
		animationStart: function(current){
			var offset = $('.current').offset();
			var offsetBody = $('.container').offset(); //find the offset of the wrapping div
			$('.nav_move').animate(
			{ 
			  width: $('.current').width()+0, 
			  height: $('.current').height()+0, 
			  left: (offset.left - offsetBody.left - 0)
			}, 
			{ duration: 350, easing: 'easeInOutCirc' }
			);	
			$('.current a').fadeTo("slow", 0.60);    
		},
		animationComplete: function() {
			var offset = $('.current').offset();
			var offsetBody = $('.container').offset(); //find the offset of the wrapping div
			$('.nav_move').animate(
			{ 
			  width: $('.current').width()+0, 
			  height: $('.current').height()+0, 
			  left: (offset.left - offsetBody.left - 0)
			}, 
			{ duration: 350, easing: 'easeInOutCirc' }
			);
			$('.current a').fadeTo("slow", 0.99);		    
		}		
});
$('#Quotes').slides({
	container: 'quotes_container',
	preload: true,
	preloadImage: '/images/esx/Template/2011New/js/mylibs/slides/img/loading.gif',
	pagination: false,
	generatePagination: false,
	generateNextPrev: true,
	play: 7000,
	pause: 2500,
	slideSpeed: 350,
	fadeSpeed: 350,
	hoverPause: true,
	autoHeight: true,
	autoHeightSpeed: 350,
	randomize: true,
	crossfade: false,
	effect: 'fade'
});

});

// -------------------------------------------------------------------------------------------
// Clear input field of values
// -------------------------------------------------------------------------------------------

$.fn.clearDefault = function(){  
	return this.each(function(){  
		var default_value = $(this).val();  
		$(this).focus(function(){  
			if ($(this).val() == default_value)  
						  $(this).val("");  
		});  
		$(this).blur(function(){  
			if ($(this).val() == "")  
						  $(this).val(default_value);  
		});  
	});  
};
$('.SideNav input:text').clearDefault(); 

// -------------------------------------------------------------------------------------------
// Dynamic Accessible Tabs - Example: <div class="tabs"> <h1>tab</h1> Content </div>
// -------------------------------------------------------------------------------------------

$(".tabs h6").each(function() {
	$(this).nextUntil("h6").wrapAll('<div class="tabbody" />');
});
$(".tabs").accessibleTabs({
	wrapperClass: 'content', // Classname to apply to the div that is wrapped around the original Markup
	currentClass: 'current', // Classname to apply to the LI of the selected Tab
	tabhead: 'h6', // Tag or valid Query Selector of the Elements to Transform the Tabs-Navigation from (originals are removed)
	tabheadClass: 'tabhead', // Classname to apply to the target heading element for each tab div
	tabbody: '.tabbody', // Tag or valid Query Selector of the Elements to be treated as the Tab Body
	fx:'fadeIn', // can be "fadeIn", "slideDown", "show"
	fxspeed: 'slow', // speed (String|Number): "slow", "normal", or "fast") or the number of milliseconds to run the animation
	//currentInfoText: 'current tab: ', // text to indicate for screenreaders which tab is the current one
	//currentInfoPosition: 'prepend', // Definition where to insert the Info Text. Can be either "prepend" or "append"
	//currentInfoClass: 'current-info', // Class to apply to the span wrapping the CurrentInfoText
	tabsListClass:'tabs-list', // Class to apply to the generated list of tabs above the content
	syncheights:false, // syncs the heights of the tab contents when the SyncHeight plugin is available http://blog.ginader.de/dev/jquery/syncheight/index.php
	syncHeightMethodName:'syncHeight', // set the Method name of the plugin you want to use to sync the tab contents. Defaults to the SyncHeight plugin: http://github.com/ginader/syncHeight
	cssClassAvailable:false, // Enable individual css classes for tabs. Gets the appropriate class name of a tabhead element and apply it to the tab list element. Boolean value
	saveState:false, // save the selected tab into a cookie so it stays selected after a reload. This requires that the wrapping div needs to have an ID (so we know which tab we're saving)
	autoAnchor:false, // will move over any existing id of a headline in tabs markup so it can be linked to it
	pagination:false, // adds buttons to each tab to switch to the next/previous tab
	position:'top' // can be 'top' or 'bottom'. Defines where the tabs list is inserted. 
});
	
// -------------------------------------------------------------------------------------------
// Adds a focus class to the parent element so you can see what field you are on
// -------------------------------------------------------------------------------------------
			
$(".content input").focus(function() {
	$(this).parent().addClass("curFocus")
});
	$(".content input").blur(function() {
	$(this).parent().removeClass("curFocus")
});

// -------------------------------------------------------------------------------------------
// QRCode
// -------------------------------------------------------------------------------------------
LazyLoad.js(['/images/esx/Template/2011New/js/mylibs/jquery.uqr/js/jquery.uqr.js'], function() {
	$('<div id="qr2"></div>').prependTo('footer .sixteen');
	
	 $('#qr2').uQr({
		create: true,
		type: 'contact',
		size: 150,
		name: 'ESX Inc.',
		address: '2400 Augusta Suite 372, Houston, TX 77057',
		number: '(281) 822-6500',
		email: 'info@esxinc.com',
		url: 'http://www.esxinc.com'	
	});
	$('#qr2').css({ 
		width: '150px',
		float: 'left'
	});
});

// -------------------------------------------------------------------------------------------
// AddThis Button
// -------------------------------------------------------------------------------------------
LazyLoad.js(['/images/esx/Template/2011New/js/mylibs/jquery.addthis.js'], function() {
	$('<a class="addthis"></a>').prependTo('.brdr-body-content.addthis');
	$('.addthis').css({ 
		padding: '5px 5px 0px 5px',
		//float: 'right',
		display: 'block'
	});
	$.addthis('ra-4e7a27817c3d74fb', 'btn_size: large');
});


// -------------------------------------------------------------------------------------------
// Font sizer. This must be loaded before the tooltip for tooltips to work
// -------------------------------------------------------------------------------------------

$('.PageTitle').prepend('<div id="fontsizer"></div>');
$("#fontsizer").fontScaler({
	target: '.Content',
		containerclass: 'fontScaler',
		store:true,
		fx: 'smooth',
		fxspeed: '100',
		fixed: {
			size1: '100',
			size2: '120',
			size3: '145'
		}
});	
		
// -------------------------------------------------------------------------------------------
// Tooltip plugin. Only loaded if it finds a title tag.
// -------------------------------------------------------------------------------------------
	
$(function() {
  $("#fontsizer [title]").tipsy({
		delayIn: 0,      // delay before showing tooltip (ms)
		delayOut: 0,     // delay before hiding tooltip (ms)
		fade: true,     // fade tooltips in/out?
		fallback: '',    // fallback text to use when no tooltip text
		gravity: 's',    // gravity nw | n | ne | w | e | sw | s | se | $.fn.tipsy.autoNS
		html: false,     // is tooltip content HTML?
		live: false,     // use live event support?
		offset: 0,       // pixel offset of tooltip from element
		opacity: 0.5,    // opacity of tooltip
		title: 'title',  // attribute/callback containing tooltip text
		trigger: 'hover' // how tooltip is triggered - hover | focus | manual
	});   
});



// -------------------------------------------------------------------------------------------
// Link nudge.
// -------------------------------------------------------------------------------------------

/* jQuery link nudge plugin */ 
$.fn.nudge=function(params){params=$.extend({amount:20,duration:300,property:'padding',direction:'left',toCallback:function(){},fromCallback:function(){}},params);this.each(function(){var $t=$(this);var $p=params;var dir=$p.direction;var prop=$p.property+dir.substring(0,1).toUpperCase()+dir.substring(1,dir.length);var initialValue=$t.css(prop);var go={};go[prop]=parseInt($p.amount)+parseInt(initialValue);var bk={};bk[prop]=initialValue;$t.hover(function(){$t.stop().animate(go,$p.duration,'',$p.toCallback);},function(){$t.stop().animate(bk,$p.duration,'',$p.fromCallback);});});return this;};

$('.brdr-body-content ul li').nudge({
    property: 'margin',
    direction: 'left',
    amount: 3,
    duration: 200
});

// -------------------------------------------------------------------------------------------
// Magic Links - URLs, emails, and US/Canada phone numbers to be clickable links in P tags.
// -------------------------------------------------------------------------------------------
var email = /\b([A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4})\b/ig;
var phone = /\b([01]?[- .]?\(?[2-9]\d{2}\)?[- .]?\d{3}[- .]?\d{4})\b/g;
var url = /\b((?:https?):\/\/(?:-\.)?(?:[^\s\/?\.#-]+\.?)+(?:\/[^\s]*)?[A-Z0-9+&@#\/%=~_|])/ig;
var alink = /(<a [^>]*>.*?<\/a>)/i;
$('p').each(function() {
    var h = $(this).html();
    var alist = [];
    while(alink.test(h)) {
        var lnk = alink.exec(h)[0];
        h = h.replace(lnk, '<a' + alist.length + '>');
        alist.push(lnk);
    }
    h = h.replace(email, '<a href="mailto:$1">$1</a>');
    h = h.replace(phone, '<a href="tel:$1">$1</a>');
    h = h.replace(url, '<a href="$1">$1</a>');
    for(var i = 0; i < alist.length; i++) {
        h = h.replace('<a' + i + '>', alist[i]);
    }
    $(this).html(h);
});

// -------------------------------------------------------------------------------------------
// Create select dropdown from from main navigation
// -------------------------------------------------------------------------------------------

// Create the dropdown base
$("<select />").appendTo(".topbar .logo");

// Create default option "Go to..."
$("<option />", {
 "selected": "selected",
 "value"   : "",
 "text"    : "Go to..."
}).appendTo(".topbar .logo select");

// Populate dropdown with menu items
$(".topbar .twelve ul li a").each(function() {
var el = $(this);
$("<option />", {
   "value"   : el.attr("href"),
   "text"    : el.text()
}).appendTo(".topbar .logo select");
});

// To make dropdown actually work
// To make more unobtrusive: http://css-tricks.com/4064-unobtrusive-page-changer/
$(".topbar .logo select").change(function() {
window.location = $(this).find("option:selected").val();
});


LazyLoad.js(['/images/esx/Template/2011New/js/mylibs/lifestream/jquery.lifestream.js', '/images/esx/Template/2011New/js/mylibs/lifestream/jquery.timeago.js'], function() {

(function(){
      var count = 0,
      list = [
        {
          service: 'facebook_page',
          user: '112356568813646'
        },
        {
          service: 'rss',
          user: 'http://www.esxinc.com/NewsRSS.asp?QueryType=1&ChannelTitle=ESX%2C+Inc%2E+News&ChannelDesc=&MaxStories=10&DateFrom=01/01/1997&DateTo=&Topics=Corporate+News%2C+xCatalyst+News&ContentCategories='
        },
        {
          service: 'twitter',
          user: 'ESXInc'
        }
      ];

      Date.prototype.toISO8601 = function(date) {
          var pad = function (amount, width) {
              var padding = "";
              while (padding.length < width - 1 && amount < Math.pow(10, width - padding.length - 1))
                  padding += "0";
              return padding + amount.toString();
          }
          date = date ? date : new Date();
          var offset = date.getTimezoneOffset();
          return pad(date.getFullYear(), 4)
              + "-" + pad(date.getMonth() + 1, 2)
              + "-" + pad(date.getDate(), 2)
              + "T" + pad(date.getHours(), 2)
              + ":" + pad(date.getMinutes(), 2)
              + ":" + pad(date.getUTCSeconds(), 2)
              + (offset > 0 ? "-" : "+")
              + pad(Math.floor(Math.abs(offset) / 60), 2)
              + ":" + pad(Math.abs(offset) % 60, 2);
      };

      $("#lifestream").lifestream({
        limit: 500,
        list: list,
        feedloaded: function(){
          count++;
          // Check if all the feeds have been loaded
          if( count === list.length ){
            $("#lifestream li").each(function(){
              var element = $(this),
                  date = new Date(element.data("time"));
              element.append(' <abbr class="timeago" title="' + date.toISO8601(date) + '">' + date + "</abbr>");
            })
            $("#lifestream .timeago").timeago();
          }
        }
      });
      
    })();
});

// -------------------------------------------------------------------------------------------
// Closing for $(document).ready(function(){
// -------------------------------------------------------------------------------------------

});


