
var $ = $j = jQuery;
//window.loadFirebugConsole();

//WHEN DOM IS READY
$(document).ready(function() {
	
	
	//browser-specific intialization
	site.browserInit();	
	//highlight active links in nav and maybe more
	site.handleNav();
	//create functionality for site-wide search box
	site.searchBoxToggler();
	//set styles on inputs
	site.inputStyles();	
	
	
	
});




window["site"] = (function(){
						   
	function Site(){ 
		var I = this;
		//BEFORE DOM IS READY
		
	
	}
	
	Site.prototype = {		
		//These functions are called at the end of the page on dom ready
		EODOM:[
			function(){
				//make these anchors animate to position when clicked
				$("a[href='#'],div.index-anchors a[href^='#']").animateAnchors("slow");	
				
			}
		],
		ajaxProxy:"/common/php/proxy.php",


		/*
			Site.browserInit()
			Browser specific initialization.
		*/ 
		browserInit:function(){
			
			if($.browser.msie && $.browser.version.indexOf("6.")===0){
				
				if(!(/b2i.us/).test(window.location.hostname)){
					$("body *").fixPNG();		
				}
						
			}
		},		
		
		/*
			Site.highlightNav()
			Highlight links in the main nav areas, and maybe more (eg. flyouts, etc).
		*/ 
		handleNav:function(){	
			
			var nav = $("div#siteNav"),
				navPrimary = nav.find("div > ul > li > a"),
				showDelay=50;
				hideDelay = 800;
				
			navPrimary.each(function(i, ni){
				var navItem = $(ni);
				var itemContainer = navItem.closest("li");
				
				ni.container = itemContainer[0];
				//Create the hide timer
				ni.hideTimeout=null;
				ni.showTimeout=null;
				//create the hide/show initiator functions
				
				navItem.hover(startShowSub, startHideSub);
				
				itemContainer.find("ul > li > a").each(function(i, subni){
					var subNavItem = $(subni);
					
					subNavItem.hover(function(){											  
						stopHideSub.apply(ni);
					},
					function(){
						//console.log("hola?");
						startHideSub.apply(ni);
					});					
				});
				
			});
			
			function clearAllPrimary(){
				navPrimary.each(function(i, n){
					$(n).closest("li").removeClass("hover");
					clearTimeout(n.hideTimeout);
					clearTimeout(n.showTimeout);
				});
			}
			
			
			// show/hide functions should be applied directly to the element so "this" resolves to the element itself.
			function startShowSub(){
				var ni=this;
				stopHideSub.apply(ni, arguments);
				ni.showTimeout = setTimeout(function(){
					//hide all the other dropdowns
					clearAllPrimary();
					//show this one
					showSubItems.apply(ni);	
				}, showDelay);
			}
			function stopShowSub(){
				clearTimeout(this.showTimeout);
			}
			function startHideSub(){
				var ni=this;
				stopShowSub.apply(ni, arguments);
				ni.hideTimeout = setTimeout(function(){
					hideSubItems.apply(ni);
				}, hideDelay);	
			}
			function stopHideSub(){
				clearTimeout(this.hideTimeout);
			}
			
			
			function showSubItems(){
				var li = $(this).closest("li"),
					subList = li.children("ul");				
				li.addClass("hover");
				
			}
			
			function hideSubItems(){
				var li = $(this).closest("li"),
					subList = li.children("ul");				
				li.removeClass("hover");
			}
			
			//Secondary nav manipulation
			var secondaryNav = $("div#siteSubNav"),
				sNavItems =	secondaryNav.find("li"),
				sNavActives = sNavItems.filter(".active");
			
			sNavActives.children("a:first").addClass("active");
			
			//sNavActives.children("a").addClass("active");
			
			/*var navHighlighter = new tbelt.url.Highlighter({
				url:document.location.href,
				alterElements:[{element:"each", className:"active"}]
			});
			//highlight main nav
			var mainNavLinks = j("div#siteHeader a,div#siteNav a");
			navHighlighter.options.links = mainNavLinks;
			navHighlighter.highlight();
			//highlight secondary nav
			//var leftNavLinks = j("div#siteLeftNav a");
			//navHighlighter.options.links = leftNavLinks;
			//navHighlighter.highlight();
			*/
		},		
		/*
			Site.searchBoxToggler()
			Create functionality for site-wide search box.
		*/ 
		searchBoxToggler:function(){
			var searchBox = $("input#txtSiteSearch");
			/*searchBox.focus(function(evt){
				if(evt.target.value=="Search") evt.target.value="";
			});
			searchBox.blur(function(evt){
				if(evt.target.value=="") evt.target.value="Search";
			});*/
			searchBox.keydown(function(evt){
				if(evt.keyCode==13) window.location = "/search/?q="+evt.target.value;
			});
		},
		
		/*
			Site.inputStyles()
			Set the classes on the user inputs (text, radio, checkbox, textarea, buttons).
		*/ 
		inputStyles:function(){
			$("input[type='text']").addClass("input-text");
			$("select").addClass("input-select");
			$("textarea").addClass("input-textarea");
			$("input[type='button'],input[type='submit'],input[type='reset']").addClass("input-button");
		},
		
		
		createHeaderBanner:function(){
			
			var flashvars = {
				
				xmlFilePath:SITEURL+"/banner_sequence",
				xmlFileType:"Default",
				
				contentAreaBackgroundAlpha:"0",
				contentAreaStrokeAppearance:"Hidden",
				contentFrameAlpha:"0",
				
				contentScale:"Crop to Fit All",
				
				backgroundAlpha:"0",
				navAppearance:"Hidden",
				transitionLength:"2",
				transitionPause:"1",
				transitionStyle:"Cross Fade", //"None", "Blur", "Cross Fade", "Fade to Background", "Dissolve", "Drop" "Lens", "Photo Flash", "Push", "Wipe", "Wipe and Fade", "Wipe to Background" and "Wipe and Fade to Background"
				feedbackTimerAppearance:"Hidden"
				
				//TRACE_PARAMETERS:"true",
				//TRACE_MEMBERS_AVAILABLE:"true",
				//TRACE_MEMBER_ERRORS:"true",
				//TRACE_STAGE_RESIZE:"true"
			}
			var params = {
				base:".",
				allowfullscreen:"true",
				wmode:"transparent"
			}
			var attributes = {}
			
			swfobject.embedSWF(SITEURL+"/common/flash/punchout/punchout-header.swf", "headerBanner", "250", "115", "9.0.0", false, flashvars, params, attributes);
			
			var ssp = document.getElementById('ssp');
			
		
		},
	
		createHomeBanner:function(){
	
			var flashvars = {
				
				xmlFilePath:SITEURL+"/banner_sequence",
				xmlFileType:"Default",
				
				contentAreaBackgroundAlpha:"0",
				contentAreaStrokeAppearance:"Hidden",
				contentFrameAlpha:"0",
				
				contentScale:"Crop to Fit All",
				
				backgroundAlpha:"0",
				navAppearance:"Hidden",
				transitionLength:"4",
				transitionPause:"1",
				transitionStyle:"Cross Fade", //"None", "Blur", "Cross Fade", "Fade to Background", "Dissolve", "Drop" "Lens", "Photo Flash", "Push", "Wipe", "Wipe and Fade", "Wipe to Background" and "Wipe and Fade to Background"
				feedbackTimerAppearance:"Hidden"
				
				//TRACE_PARAMETERS:"true",
				//TRACE_MEMBERS_AVAILABLE:"true",
				//TRACE_MEMBER_ERRORS:"true",
				//TRACE_STAGE_RESIZE:"true"
			}
			var params = {
				base:".",
				allowfullscreen:"true",
				wmode:"transparent"
			}
			var attributes = {}
			
			swfobject.embedSWF(SITEURL+"/common/flash/punchout/punchout-home.swf", "flashBanner", "785", "360", "9.0.0", false, flashvars, params, attributes);
			
			var ssp = document.getElementById('ssp');
		
				
		},
		
		createHomeTicker:function(){
			var stockWrap = $("a.stockquote:first"),
				stockElements = stockWrap.find("var[class]");
			
			$.ajax({
				url:site.ajaxProxy,
				data:{url:"http://www.b2ixml.com/quote/quote.asp?b=1705&s=CBI"},
				dataType:"json",
				contentType:"application/json",
				cache:false,
				dataFilter:function(data){
					return $.trim(data);
				},
				success:function(data){
					//IE needs a little hand holding for the XML conversion
					if($.browser.msie){						
						var xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
						xmlDoc.async="false";
						xmlDoc.loadXML(data.contents);
						data.contents = xmlDoc.documentElement;
					}					
					var xml = $(data.contents);
					stockElements.each(function(i, e){						
						var $e=$(e),
							varName = $e.attr("class"),
							varNode = xml.children(varName),
							varVal = varNode.text();
						
						if(varName==="LastUpdate"){
							varVal = varVal.replace(/:[0-9]{2} (AM|PM)$/, "$1");
						}
						$e.text(varVal);
					});
				},
				error:function(err){
					console.log("Error in site.createHomeTicker()\n"+err.responseText);
				}
			});	
			
		
		}

	};

	return new Site();

})();





/* JQUERY PLUGINS */

(function(){
	
	/*
	 * buildIndexAnchors()
	*/
	$.fn.buildIndexAnchors = function(area){
		var anchorsArea = (area!=null) ? ((typeof area === "string") ? $(area) : area) : $("div.anchors-alpha > ul"),
			anchors = "";
		
		this.each(function(i, t){
			var $t = $(t),
				anchorName = $t.attr("id") || $t.closest("*[id]").attr("id") || $t.closest("h1,h2,h3,h4,h5,h6").first().find("a[name]").attr("name");
				
			anchors+="<li><a href='#"+anchorName+"'>"+$t.text()+"</a></li>";
		});
		if(anchors.length) anchorsArea.html(anchors);		
		return this;
	}
	
	
	/*
	 * animateScroll()
	 */
	$.animateScroll = function(point, duration, easing, callback){		
		if(duration==null) speed=500;
		if(easing==null) easing="swing";		
		var $html = $("html:first");		
		$html.animate({scrollTop: point.top, scrollLeft: point.left}, duration, easing, callback);
	}
	
	$.fn.animateScroll = function(duration, easing, callback){
		var point = this.offset();
		if(point!=null)	$.animateScroll(point, duration, easing, callback);
	}
	/*
	 * animateAnchors()
	 */
	$.fn.animateAnchors = function(duration, easing, callback){		
		var pagepath = _cleanPath(window.location.pathname),
			pagehash = window.location.hash.replace(/^#/,""),
			animargs = [duration, easing, callback];
		
		//check for current anchor link and go to it
		/*if(pagehash.length){
			$("#"+pagehash+",a[name='"+pagehash+"']").animateScroll(duration, easing);
		}*/
		
		//assign actions to all selected anchor links
		this.each(function(i, a){			
			var $a = $(a),				
				apath = _cleanPath(a.pathname),
				ahash = a.hash.replace(/^#/,""),
				$el = null,
				callback = callback || function(){window.location.hash=a.hash;};
				
			if(apath===pagepath){					
				$a.click(function(evt){
					if(ahash.length){
						if($el===null) $el = $("#"+ahash+",a[name='"+ahash+"']");					
						$el.animateScroll(duration, easing, callback);	
					}else{						
						$.animateScroll({top:0,left:0}, duration, easing, callback);
					}
					evt.preventDefault();				
				});
			}
			
		});
			
		
		
	}
	
	function _cleanPath(dirty){
		return dirty.replace(/(index|default)\..[a-z]*$/i,"").replace(/\/{2,5}/g,"/").replace(/(^\/)|(\/$)/g,"");	
	}
	
	
	
	
	$.fn.indexAccordion=function(opts){
		var defaults = {
			heads: this.find("h4.category-title"),
			contents: this.find("h4.category-title").next("div"),
			speed: "slow"
		};
		var options = $.extend(defaults, opts);

		//Add icons to heads
		options.heads.prepend("<span class='icon'></span>");

		//Make the first visible
		options.heads.filter(":first").addClass("expanded");
		options.heads.not(":first").addClass("collapsed");
		
		//set a reminder for all of the heights
		options.contents.each(function(i, c){
			var $c = $(c);
			$c.data("height", $c.outerHeight());
		});
		
		options.contents.filter(":first").addClass("expanded");
		options.contents.not(":first").addClass("collapsed");
		
		options.heads.click(function(evt){
			var $this = $(this),
				$content = $this.next("div"),
				$both = $this.add($content);
				//console.log($content.data("height"));
			if($content.is(":visible")){
				//$content.stop().animate({height:0}, speed,  "linear", function(){});	
				$both.removeClass("expanded").addClass("collapsed");				
			}else{
				//$content.stop().animate({height:$content.data("height")}, speed, "linear", function(){});				
				$both.removeClass("collapsed").addClass("expanded");
			}
		});
		
		
	}
	
	
	
	$.fn.fixPNG = function(){
		this.each(function(){
			DD_belatedPNG.fixPng(this);	
		});
		return this;
	};

	
})();


