﻿//HELPER


//AUTORUN...
$(document).ready(function() {
    ddToolTips.Setup();    
	
	ddMainMenu.Run(); //Setup Main Menu
	ddBreadcrumb.Run(); //Setup Breadcrumb
	
	//Testimonials
	$('.testimonial').each(function() {
		$(this).data('color', $(this).css('color'));
		//console.log('testimonial color',$(this).data('color'));
	})
	.hoverIntent({
		timeout: 200,
		over: function() { $(this).animate({ color: '#000' }, 500); },
		out: function() { $(this).animate({color: $(this).data('color')}, 200) }
	});
	
	//External Links	
	$("a[href^='http']").each(function() {
		var me = $(this);
		me.attr('target','_blank');
		if (me.children('img').length == 0) {
			me.addClass('extlink');	
		}
	});
	
	//LEED
	$("acronym.LEED").each(function() {
		var el = $(this);
		if (el.hasClass('AP')) {
			el.attr('title','Leadership in Energy and Environmental Design, Accredited Professional')
			.click( function() { window.open('http://www.gbci.org/DisplayPage.aspx?CMSPageID=84','LEED'); });
		} else {
			el.attr('title','Leadership in Energy and Environmental Design')
			.click( function() { window.open('http://www.usgbc.org/DisplayPage.aspx?CMSPageID=1988','LEED'); });
		}
	}); //end LEED
	
	//MAIL TO
	$('.email').mailTo();
	
});


//CONTACT
(function($){
$.fn.contact = function(name) {
	
	return this.each(function() {
		$(this).html(name + '@everGREEN-sb.com'); 
	});
	
};
})(jQuery);

//SHUFFLE
(function($){
  $.fn.shuffle = function() {
    return this.each(function(){
      var items = $(this).children();
      return (items.length) ? $(this).html($.shuffle(items)) : this;
    });
  }
 
  $.shuffle = function(arr) {
    for(
      var j, x, i = arr.length; i;
      j = parseInt(Math.random() * i),
      x = arr[--i], arr[i] = arr[j], arr[j] = x
    );
    return arr;
  }
})(jQuery);



/* STRING EXTENSIONS */
String.prototype.trim = function() {
    return (this.replace(/^[\s\xA0]+/, "").replace(/[\s\xA0]+$/, ""));
}
String.prototype.startsWith = function(str) {
    return (this.match("^" + str) == str);
}
String.prototype.endsWith = function(str) {
    return (this.match(str + "$") == str);
}
String.prototype.isDate = function() {
    var re = /^((0?\d)|(1[012]))[\/\-][0123]\d{1}[\/\-]((19)|(20))\d{2}$/;
    return re.test(this);
}
String.prototype.contains = function(str) {
    return this.toLowerCase().indexOf(str.toLowerCase()) >= 0;
}

var ddMainMenu = {
	options: {
		menuSelector: '#MAIN-MENU ul.lavaLamp',
		megaCSS: 'mega',
		parentCSS: 'parent',
		currentCSS: 'current',
		firstCSS: 'first',
		lastCSS: 'last',
		fx: 'backout',
		speed: 700
	},
	menu: null,
	Run: function() {
		menu = $(ddMainMenu.options.menuSelector);	
		if (menu && menu.length > 0) {
			//wrap each <a> innertext with <span>
			$('li a', menu).wrapInner(document.createElement("span"));
			//class each <a> as 'parent' if it has a <ul> following it
			$('li a:first-child', menu).each(function() {
				var ctrl = $(this);
				var sib = ctrl.next();
				if (sib && sib.length > 0) { ctrl.addClass(ddMainMenu.options.parentCSS); }
			});
			
			//class first <li> on each level as 'first'
			$('li:first-child', menu).addClass(ddMainMenu.options.firstCSS);
			//class last <li> on each level as 'last'
			$('li:last-child', menu).addClass(ddMainMenu.options.lastCSS);
			
			//setup current and mega menu
			var found = false, first = null;
			menu.children().each(function () {
					if (first == null) { first = this; }					
					if (ddMainMenu._isCurrent($('a',this).get(0))) {
						found = true;
						$(this).addClass(ddMainMenu.options.currentCSS);
					}
					if ($(this).hasClass(ddMainMenu.options.megaCSS)) {
						$(this).hoverIntent({
							timeout: 200,
							over: ddMainMenu._showMega,
							out: ddMainMenu._hideMega
						});
					}
			});
			if (!found) { $(first).addClass(ddMainMenu.options.currentCSS); }
					
			//setup menu
			menu.lavaLamp({ fx: ddMainMenu.options.fx, speed: ddMainMenu.options.speed});	
		}
	},
	_showMega: function() { $('.grouping',this).fadeIn(300); },
	_hideMega: function() { $('.grouping',this).fadeOut(200); },
	_isCurrent: function(el) {
		
		// get the filename of the element's href
		var href = $(el).attr('href');
		var index = href.lastIndexOf('/');
		if (index >=0 ) { href = href.substr(index+1); }
		index = href.lastIndexOf('.');
		if (index >= 0) { href = href.substr(0,index); }
		
		//does the current path contain the filename of the ref
		return window.location.pathname.contains(href);
	}
};

var ddBreadcrumb = {
	options: {
		menuSelector: '#BREADCRUMB-WRAPPER',
		currentCSS: 'current',
		delimHTML: '<span>&raquo;</span>',
		firstCSS: 'first',
		lastCSS: 'last'
	},
	menu: null,
	Run: function() {
		menu = $(ddBreadcrumb.options.menuSelector);	
		if (menu && menu.length > 0) {
			//insert delimHTML after each except last
			$('a:not(:last)', menu).after(ddBreadcrumb.options.delimHTML);			
			//class first <li> on each level as 'first'
			$('a:first', menu).addClass(ddBreadcrumb.options.firstCSS);
			//class last <li> on each level as 'last'
			$('a:last', menu).addClass(ddBreadcrumb.options.lastCSS);
			
			//setup current
			var path = window.location.pathname;
	$('a:last', menu).addClass(ddBreadcrumb.options.currentCSS);	//Assuming last is current
			
		}
	}		
};

//** --- ToolTips --- **//
var ddToolTips = {
    options: {
        targetCss: "qtip",
        addTipCss: 'add-tip',
        showBelow: 'add-below',
        addTipSpanCss: 'help'
    },
    Setup: function() {
        var isOk;
        $("." + ddToolTips.options.targetCss + "[title]").each(function(i) {
			var ctrl = $(this);
			if (!ctrl.hasClass(ddToolTips.options.addTipCss)) {
	            ddToolTips.MakeTip(ctrl);
			}
        });
        $("." + ddToolTips.options.addTipCss + "[title]").each(function(i) {
            var ctrl = $(this);
            var tip = document.createElement("span");
			if (this.tagName == "INPUT" || this.tagName == "SELECT") {
				ctrl.after(tip);    //insert after the INPUT/SELECT ctrl
			} else {
				this.appendChild(tip);
			}
			tip = $(tip);
			tip.addClass(ddToolTips.options.addTipSpanCss);
			tip.html("&nbsp;");
			ddToolTips.MakeTip(ctrl, tip);
        });
    },
    MakeTip: function(ctrl, tip) {
        if (!tip) { tip = ctrl; }
        var thePosition = {};
        if (ctrl.hasClass(ddToolTips.options.showBelow)) { 
            thePosition = { corner: { target: 'bottomLeft', tooltip: 'topLeft'} };
        }
        tip.qtip({
            content: ctrl.attr("title"),
            position: thePosition,
            style: { name: 'dark',
                background: '#F79892',
                color: '#000',
                border: { width: 3, radius: 5, color: '#900' }
            }
        });
        ctrl.attr("tip", ctrl.attr("title"));
        ctrl.attr("title", "");
    }
};                                                       //end ddToolTips

var ddAttention = {
    wrapperDiv: null,
    timer: null,
    Show: function(typeEnum, title, html, delay) {
        //clean-up
        if (ddAttention.wrapperDiv) { $(ddAttention.wrapperDiv).remove(); }

		typeEnum = typeEnum ? typeEnum : "info";

        ddAttention.wrapperDiv = window.document.createElement("div");
        var titleWrapperDiv = window.document.createElement("div");
        var titleDiv = window.document.createElement("span");
        var closeDiv = window.document.createElement("span")
        var bodyDiv = window.document.createElement("div");
        var clickHereDiv = window.document.createElement("div");

        var cssOptions = {
            'display': 'none'
        };

        $(ddAttention.wrapperDiv).addClass("attention-box").addClass(typeEnum).css(cssOptions);
        $(titleWrapperDiv).addClass("title");
        $(titleDiv).css({ 'display': 'block', 'float': 'left'}).text(title);
        $(closeDiv).css({ 'display': 'block', 'float': 'right', 'cursor': 'pointer' }).text('x').click(ddAttention.Close);
        $(bodyDiv).addClass("content").html(html);
        $(clickHereDiv).addClass("close").text('[ click here to close this box ]').click(ddAttention.Close);

        bodyDiv.appendChild(clickHereDiv);
        titleWrapperDiv.appendChild(titleDiv);
        titleWrapperDiv.appendChild(closeDiv);
        ddAttention.wrapperDiv.appendChild(titleWrapperDiv);
        ddAttention.wrapperDiv.appendChild(bodyDiv);
        window.document.body.appendChild(ddAttention.wrapperDiv)

        $(ddAttention.wrapperDiv).slideDown(500, function() {
            if (delay) {
                ddAttention.timer = setTimeout(ddAttention.Close, delay);
            }
        });

    },
    Close: function() {
        if (ddAttention.timer) { clearTimeout(ddAttention.timer); }

        if (ddAttention.wrapperDiv) {
            $(ddAttention.wrapperDiv).fadeOut(1000, function() {
                $(ddAttention.wrapperDiv).remove();
                ddAttention.wrapperDiv = null;
            });
        }
    }
};

var ddAutoScroll = {
    parents: null,
	selector: 'ul.auto-scroll',
	timer: null,
	delay: 6000,
	fxRate: 600,
	quick: true,
	assoc_container: null,
	assoc_current_cssClass: 'current',
    Setup: function() {
		ddAutoScroll.parents = $(ddAutoScroll.selector).data('index',0);
		ddAutoScroll._ShowNext();
	},
	Pause: function() {
		if (ddAutoScroll.timer) { clearInterval(ddAutoScroll.timer); ddAutoScroll.timer = null; }
	},
	Resume: function() {
		ddAutoScroll._ShowNext();	
	},
	Show: function(ID, index) {
		var bFound = false;
		
		//stop the auto scroll
		if (ddAutoScroll.timer) { clearInterval(ddAutoScroll.timer); ddAutoScroll.timer = null; }
		
		//find the parent with the id
		ddAutoScroll.parents.each(function() {
			var LIs = $('li',this);
			if (LIs.filter('#'+ID).length == 1) {
				//found the parent
				
				if (index != undefined && index != null) {
					$(this).data('index', index);
					bFound == true;
				} else {
					// calculate the index
					for (var i=0; i<LIs.length; i++) {
						if (LIs.eq(i).attr('id') == ID) {
							bFound = true;
							$(this).data('index',i);
						}
					}
				}
			}						
		});
		
		//Did we find the ID?
		if (bFound == true) {
			ddAutoScroll._ShowNext(); //start it again				
		} else {
			// could throw error or ...
			ddAutoScroll._ShowNext(); //start it again				
		}

	},
	_ShowNext: function() {
		if (ddAutoScroll.timer) { clearInterval(ddAutoScroll.timer); ddAutoScroll.timer = null; }
		
		// if using associations, clear all current
		if (ddAutoScroll.assoc_container && ddAutoScroll.assoc_container.length > 0) {
			ddAutoScroll.assoc_container.removeClass(ddAutoScroll.assoc_current_cssClass);
		}
		
		
		ddAutoScroll.parents.each(function() {
		    var index = $(this).data('index');
			index = index ? index : 0;
			var LIs = $('li', this);
			if (LIs && LIs.length > 0 ) {
				if (index >= LIs.length) { index = 0; }
				else if (index < 0) { index = LIs.length-1; }
				
				for (var i=0; i<LIs.length; i++) {
					if (i == index) {
						if (ddAutoScroll.quick == true) {
							LIs.eq(i).show();
						} else {
							LIs.eq(i).fadeIn(ddAutoScroll.fxRate);
						}
						// if using associations (and LI has ID), add assoc  current class
						if (ddAutoScroll.assoc_container && ddAutoScroll.assoc_container.length > 0) {
							var id = LIs.eq(i).attr('id');
							if (id && id.length > 0) {
								ddAutoScroll.assoc_container.filter("." + id).addClass(ddAutoScroll.assoc_current_cssClass);	
							}
						}
					} else if( LIs.eq(i).is(':visible') )  {
						if (ddAutoScroll.quick == true) {
							LIs.eq(i).hide();
						} else {
							LIs.eq(i).fadeOut(ddAutoScroll.fxRate);
						}
					}
				}
				$(this).data('index',++index);
			}
		});
		ddAutoScroll.quick = false;
		ddAutoScroll.timer = setInterval(ddAutoScroll._ShowNext,ddAutoScroll.delay);
	}
};


//setup console
try {
    if (!("console" in window) || !("firebug" in console)) {
        window.console = {};
        //simulate logging by sending to alert        
        var names = ["log", "debug", "info", "warn", "error"];
        for (var i = 0; i < names.length; ++i) {
            window.console[names[i]] = function() { for (var i = 0; i < arguments.length;  i++) { alert(arguments[i]); } };
        }
        //add the reset just in case
        names = ["assert",
             "dir", "dirxml", "group", "groupEnd", "time",
             "timeEnd", "count", "trace", "profile", "profileEnd"];
        for (var i = 0; i < names.length; ++i) {
            window.console[names[i]] = function() { };
        }

    }
} catch (e) { }


/* Mail To

*/
jQuery.fn.mailTo = function() {
	var address="info@evergreen-sb.com";
	var text = this.text();
	text = text.replace('{at}','@').replace('{dot}','.');
	return this.text(text).css('cursor','pointer').click( function() {
		if (confirm('Create a new message to ' + address)) {
			window.location = "mailto:" + address;	
		}
	});
};

jQuery.fn.removeHighlight = function(cssClass) {
  cssClass = cssClass ? cssClass : 'highlight';
	
 return this.find("span." + cssClass).each(function() {
  this.parentNode.firstChild.nodeName;
  with (this.parentNode) {
   replaceChild(this.firstChild, this);
   normalize();
  }
 }).end();
};

/*

highlight v3

Highlights arbitrary terms.

<http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html>

MIT license.

Johann Burkard
<http://johannburkard.de>
<mailto:jb@eaio.com>

Modified to use user-defined css class name (defaults to "highlight"
*/

jQuery.fn.highlight = function(pat, cssClass) {
	
 function innerHighlight(node, pat, cssClass) {
  var skip = 0;
  if (node.nodeType == 3) {
   var pos = node.data.toUpperCase().indexOf(pat);
   if (pos >= 0) {
    var spannode = document.createElement('span');
    spannode.className = cssClass;
    var middlebit = node.splitText(pos);
    var endbit = middlebit.splitText(pat.length);
    var middleclone = middlebit.cloneNode(true);
    spannode.appendChild(middleclone);
    middlebit.parentNode.replaceChild(spannode, middlebit);
    skip = 1;
   }
  }
  else if (node.nodeType == 1 && node.childNodes && !/(script|style)/i.test(node.tagName)) {
   for (var i = 0; i < node.childNodes.length; ++i) {
    i += innerHighlight(node.childNodes[i], pat, cssClass);
   }
  }
  return skip;
 }
 
 return this.each(function() {
  cssClass = cssClass ? cssClass : 'highlight';
  innerHighlight(this, pat.toUpperCase(), cssClass);
 });
};

jQuery.fn.removeHighlight = function(cssClass) {
  cssClass = cssClass ? cssClass : 'highlight';

 return this.find("span." + cssClass).each(function() {
  this.parentNode.firstChild.nodeName;
  with (this.parentNode) {
   replaceChild(this.firstChild, this);
   normalize();
  }
 }).end();
};