$(document).ready(function() {
	function initTabs(){
		var sets = document.getElementsByTagName("ul");
		for (var i = 0; i < sets.length; i++){
			if (sets[i].className.indexOf("tabs") != -1){
				var tabs = [];
				var links = sets[i].getElementsByTagName("a");
				for (var j = 0; j < links.length; j++){
					if (links[j].className.indexOf("tab") != -1){
						tabs.push(links[j]);
						links[j].tabs = tabs;
						var c = document.getElementById(links[j].href.substr(links[j].href.indexOf("#") + 1));

		//reset all tabs on start
						if (c) {
							if (links[j].className.indexOf("active") != -1) {c.style.display = "block";}
							else {c.style.display = "none";}
						}
						
						links[j].onclick = function (){
							var c = document.getElementById(this.href.substr(this.href.indexOf("#") + 1));
							window.location.hash = this.href.substr(this.href.indexOf("#"));
							if (c){
		//reset all tabs before change
								for (var i = 0; i < this.tabs.length; i++){
									document.getElementById(this.tabs[i].href.substr(this.tabs[i].href.indexOf("#") + 1)).style.display = "none";
									this.tabs[i].className = this.tabs[i].className.replace("active", "");
								}
								this.className += " active";
								c.style.display = "block";
								return false;
							}
						}
					}
				}	
			}
		}
		//change tab on page load if url contains a deep link
		if (window.location.hash.length > 0) {		
			if (document.getElementById(window.location.hash.substr(1))) { 	//only changes tab if the deep link actually corresponds to an element in the DOM
				for (var i = 0; i < tabs.length; i++){
					document.getElementById(tabs[i].href.substr(tabs[i].href.indexOf("#") + 1)).style.display = "none";
					tabs[i].className = tabs[i].className.replace("active", "");
					if (tabs[i].href.substr(tabs[i].href.indexOf("#")) == window.location.hash) tabs[i].className = "active";	// adds "active" class back to the correct tab
				}
				var deepLink = document.getElementById(window.location.hash.substr(1));
				deepLink.style.display = "block";
			}
		}
		if (window.location.hash.length > 0 && (typeof tabs != 'undefined')) {		
			if (document.getElementById(window.location.hash.substr(1, window.location.hash.length-2))) { 	//only changes tab if the deep link actually corresponds to an element in the DOM
				for (var i = 0; i < tabs.length; i++){
					document.getElementById(tabs[i].href.substr(tabs[i].href.indexOf("#") + 1)).style.display = "none";
					tabs[i].className = tabs[i].className.replace("active", "");
					if (tabs[i].href.substr(tabs[i].href.indexOf("#")) == window.location.hash.substr(0,window.location.hash.length-1)) tabs[i].className = "active";	// adds "active" class back to the correct tab
				}
				var deepLink = document.getElementById(window.location.hash.substr(1, window.location.hash.length-2));
				deepLink.style.display = "block";
			}
		}
	}

	initTabs();
	bindThickboxLinks();
	// migrate this
	// temporary RSS fix  
	fixNews();
	updateArgosyUrl();
});


// Temporary RSS Fix CR43972
function fixNews() {
    //var news = [
    //    ['http://phx.corporate-ir.net/phoenix.zhtml?c=115117&p=irol-newsArticle&ID=1379565&highlight=', 'USG Corporation Reports Quarterly, Full Year Results and Continued Progress in Strengthening Its Operations'],
    //    ['http://phx.corporate-ir.net/phoenix.zhtml?c=115117&p=irol-newsArticle&ID=1377087&highlight=', 'USG Corporation Fourth Quarter 2009 Earnings Conference Call and Webcast']
    //];
 
    //Press Release Temporary Fix  - Hard code news provided by P. Clark
    var news = [
          ['http://investor.usg.com/phoenix.zhtml?c=115117&p=irol-newsarticle&ID=1401929', 'USG Corporation Rainier Plant Awarded Prestigious Oregon OSHA VPP Star'],
          ['http://investor.usg.com/phoenix.zhtml?c=115117&p=irol-newsarticle&ID=1401929', 'USG Corporation Rainier Plant Awarded Prestigious Oregon OSHA VPP Star']
    ];
    
    
    
    var first = 0;
    var speed = 700;

    var displayNews = "";
    // jQuery loop
    $.each(news, function(index, newsItem) {
        displayNews += "<li><a href=\"" + newsItem[0] + "\" target=\"_blank\">" + newsItem[1] + "</a></li>";
    });
    $('ul#newsItems').html(displayNews);

    first = $('ul#newsItems li:first');
    $('span#story').fadeOut(speed, function() {
        $('span#story').html(first.html()).fadeIn(speed);
    });
    $(first).insertAfter('ul#newsItems li:last');
    
};

//



function updateArgosyUrl() {
	var argosyLink = $('a:contains("Order samples & literature")').get(0);
	if(argosyLink != undefined || argosyLink != null) {
		$('a:contains("Order samples & literature")').get(0).href = $('a:contains("Order samples & literature")').get(0).href.replace("myargosydirecttest", "myargosydirect");
	}
}

function bindThickboxLinks() {
    $('.thickbox').each(function(i) {
        $(this).unbind('click');
    });
    tb_init('a.thickbox');
    tb_init('a.thickbox-screencastOverlay');
    
    var link = $('a.thickbox-screencastOverlay')[1].href.split('?#');
    $('a.thickbox-screencastOverlay')[1].href = link[0] + "#" + link[1];
}

function initMenu() {
	/*
    var ul = document.getElementById('side-nav');
    if (ul) {
        var li = ul.getElementsByTagName('li');
        for (i = 0; i < li.length; i++) {
            var currentLi = li[i];
            var as = currentLi.getElementsByTagName('a');
            if (as && as.length && as.length > 0) {
				as[0].onmouseover = function() {
					this.parent.className += ' hover';
					if (this.parent.getElementsByTagName("div")[0]) { 
						hideSelectBoxes(this.parent.getElementsByTagName("div")[0]);
						}
					}
				
				as[0].onmouseout = function() {
					this.parent.className = this.parent.className.replace('hover', '');
					if (this.parent.getElementsByTagName("div")[0]) {
						showSelectBoxes(this.parent.getElementsByTagName("div")[0]);
					}
				}
			}
        }
    }*/
}

/*--- gallery function ---*/
function initGall(){
	var stay_time = 5000; // in ms
	var change_speed = 700; // in ms
	if(typeof($) == 'function'){
		var _hold = $('#gallery');
		if(_hold.length){
			var _list = _hold.find('div.slider > ul > li, div.wideSlider > ul > li, div.productCategorySlider > ul > li');
			if(_list.length > 1){
				var _t;
				var _f = true;
				var _btn = $('<ul class="paging"></ul>');
				_btn.append('<li class="back"><a href="#" title="Back">1</a></li>');
				_btn.append('<li class="pause"><a href="#" title="Pause">2</a></li>');
				_btn.append('<li class="play"><a href="#" class="active" title="Play">3</a></li>');
				_btn.append('<li class="forward"><a href="#" title="Forward">4</a></li>');
		/* ORIGINAL CODE */
		/*
				for(var i = 0; i < _list.length; i++){
					_btn.append('<li><a href="#">'+(i+1)+'</a></li>');
				}
		*/
				_hold.find('div.frame').append(_btn);
				_btn = _btn.find('a');
				var _a = _list.index(_list.index(_list.filter('.active:eq(0)')));
				if(_a == -1) _a = 0;
				_list.removeClass('active').css('opacity', 0).eq(_a).addClass('active').css('opacity', 1);
				_list.find('a.myPlayer').css('display','none');
				_list.eq(_a).find('a.myPlayer').css('display','block');
				//_btn.removeClass('active').eq(_a).addClass('active');
				
				var control = "";
				_btn.click(function(){
					control = _btn.index(this);
					if (control == 0) { // Back one slide
					//alert("reverse");
						if (_a > 0) changeEl(_a - 1);						
						else changeEl(_list.length - 1);
					}
					else if (control == 1) { // Pause
					//alert("pause");
						_btn.removeClass('active').eq(control).addClass('active');
						_f = false;
						if(_t) clearTimeout(_t);
					}
					else if (control == 2) { // Play
					//alert("play");
						_btn.removeClass('active').eq(control).addClass('active');
						_f = true;
						_t = setTimeout(function(){
							if(_a < _list.length - 1) changeEl(_a + 1);
							else changeEl(0);
						}, stay_time);
					}
					else if (control == 3) { // Forward one slide
					//alert("forward");
						if(_a < _list.length - 1) changeEl(_a + 1);
						else changeEl(0);
					}
		/* ORIGINAL CODE */
		/*
					changeEl(_btn.index(this));
					return false;
		/**/
				});
		/* ORIGINAL CODE */
		/*		
				_hold.mouseenter(function(){
					_f = false;
					if(_t) clearTimeout(_t);
				}).mouseleave(function(){
					_f = true;
					_t = setTimeout(function(){
						if(_a < _list.length - 1) changeEl(_a + 1);
						else changeEl(0);
					}, stay_time);
				});
		/**/
				_t = setTimeout(function(){
					if(_a < _list.length - 1) changeEl(_a + 1);
					else changeEl(0);
				}, stay_time);
			}
			function changeEl(_ind){
				//alert(_ind);
				if(_t) clearTimeout(_t);
				if(_ind != _a){
					//_btn.eq(_a).removeClass('active');
					//_btn.eq(_ind).addClass('active');
					_list.eq(_a).removeClass('active').animate({opacity: 0}, {queue:false, duration: change_speed}).find('a.myPlayer').css('display','none');
					_list.eq(_ind).addClass('active').animate({opacity: 1}, {queue:false, duration: change_speed}).find('a.myPlayer').css('display','block');
					_a = _ind;
				}
				if(_f){
					_t = setTimeout(function(){
						if(_a < _list.length - 1) changeEl(_a + 1);
						else changeEl(0);
					}, stay_time);
				}
			}
		}
	}
}
if (window.addEventListener) {
	//window.addEventListener("load", initTabs, false);
	window.addEventListener("load", initGall, false);
}
else if (window.attachEvent){
	//window.attachEvent("onload", initTabs);
	window.attachEvent("onload", initMenu);
	window.attachEvent("onload", initGall);
}

/******   Attaches tabs to gallery   ******/
$(document).ready( function() {
	// Hide tab slides
	$(".section-slides > ul > li").hide();

	// There are known performance issues with .live(), a fix can be found here: http://www.reddit.com/r/coding/comments/a1m4b/jquerys_selectorlive_is_actually_pretty_slow/
	$(".scroll-content ul li").live('click', function(e) {
			e.preventDefault();
		var siblingIndex = $(".scroll-content > ul > li").index(this);
		
		// hide opening slides
		$(".opening-slides").hide();
		$(".gallery .paging").hide();
		// hide any currently shown slide, and show the correct one
		$(".section-slides > ul > li.selected").hide().removeClass("selected");
		$(".section-slides > ul > li").eq(siblingIndex).show().addClass("selected");
		// unselect any selected tab, and set the clicked tab as selected
		$(".scroll-content > ul > li.selected").removeClass("selected");
		$(".scroll-content > ul > li").eq(siblingIndex).show().addClass("selected");

		return false;
	});	
});

// Navigation flyouts
$(function() {
	$('#side-nav > li > a, #side-nav > li > .drop-down').each(function() {
		var $parentLi = $(this).parent('li');
		var $mainAnchor = $parentLi.children('a') || null;
		var $flyout = $parentLi.children('.drop-down') || null;

		$parentLi.data('hoverTimer', 0);
		
		$(this).hover(
			function(e) { // over
				clearTimeout($parentLi.data('hoverTimer'));

				// Find the flyouts that need to be positioned by their bottoms
				{$flyout.css({
					'display': 'block',
					'left': -9999
				});
				
				if ($flyout.offset().top + $flyout.outerHeight() > $(window).height()) {
					$flyout.css({
						'top': 'auto',
						'bottom': 0 - $(window).height() + ($mainAnchor.offset().top + $mainAnchor.outerHeight())
					});
				}
				
				$flyout.css({
					'display': '',
					'left': ''
				});}

				$flyout.show();
				$parentLi.addClass('hover');
			},
			function(e) { // out
				// Do nothing for selects (IE considers them outside the box), $mainAnchor, and $flyout
				if (!!e.relatedTarget && e.relatedTarget.nodeName.toLowerCase() == 'select' || e.relatedTarget != $flyout[0] && e.relatedTarget != $mainAnchor[0]) {
					$parentLi.data('hoverTimer', setTimeout(function() {
						$flyout.hide();
						$flyout.css({
							'top': -26,
							'bottom': 'auto'
						});
						$parentLi.removeClass('hover');
					}, 50));
				}
			}
		)
	});
});


$(function() {
	var opening = $('.productCategorySlider > ul > li > p > a, .productCategorySlider > .section-slides > ul > li > p > a, .prod-details .slider > ul > li > p > a');
	opening.addClass('button');
	$.each(
		opening, 
		function() {
			$(this).children().filter('img').filter('[src$=flv]').parent().removeClass('button');
			$(this).filter('[href$=flv]').removeClass('button');
			var tempHtml = $(this).html();
			$(this).html('<span>' + tempHtml + '</span>');
			$(this).children().children().filter('img').filter('[src$=flv]').parent().parent().html(tempHtml);
			$(this).filter('[href$=flv]').html(tempHtml);
			
		}
	)
});