// JavaScript Document

$(function(){
	
	// TABS
	var tabs = $('div.tab');
	if(tabs.length){
		// append the stylesheet
		var url = '/includes/css/js.css'
		if(document.createStyleSheet) {
			try { document.createStyleSheet(url); } catch (e) { }
		}
		else {
			var css;
			css         = document.createElement('link');
			css.rel     = 'stylesheet';
			css.type    = 'text/css';
			css.media   = "all";
			css.href    = url;
			document.getElementsByTagName("head")[0].appendChild(css);
		}


		var tabWidth = 0;
		tabs.each(function(index){
			// skip the first tab
			if(index > 0) {
				$(this).css('left', tabWidth + (index - 1) * 32);
			}
			
			tabWidth += $(this).width();
		});
		
		
		// select default tabs & content
		$('.tab01').addClass('activetab');
		$('.contentsection01').addClass('activecontentsection');
		
		// handle tab clicks
		tabs.click(function(){
			// set all tabs & content as inactive
			tabs.removeClass('activetab');
			$('.contentsection').removeClass('activecontentsection');
			
			// activate appropriate tabs & content
			$(this).addClass('activetab');
			$(this).next('.contentsection').addClass('activecontentsection');
			
			// set the anchor
			window.location.hash = 'showtab' + (tabs.index(this) + 1);
		});
		
		
		// tab anchors
		
		function updateTabs() {
			var windowHash = window.location.hash;
			var showtabPos = windowHash.indexOf("#showtab");
			if(showtabPos != -1) {
				var tabNum = windowHash.substring(showtabPos + 8) - 1;
				// set all tabs & content as inactive
				tabs.removeClass('activetab');
				$('.contentsection').removeClass('activecontentsection');
				// activate appropriate tabs & content
				tabs.eq(tabNum).addClass('activetab');
				tabs.eq(tabNum).next('.contentsection').addClass('activecontentsection');
			}
			
			if(windowHash == "" || windowHash == "#") {
				tabs.removeClass('activetab');
				$('.contentsection').removeClass('activecontentsection');
				tabs.eq(0).addClass('activetab');
				tabs.eq(0).next('.contentsection').addClass('activecontentsection');
			}
		}
		
		updateTabs();
				
		// hash change listener
		$(window).hashchange(updateTabs);
	
	}
	
	
	
	// IMAGE PROCESSING
	var pImages = $('.processimages img').not('.dontprocess');
	if(pImages.length){
		pImages.each(function(){
			var theImage = $(this);
			// build links for fancybox
			theImage.wrap('<a class="processed" href="' + theImage.attr('src') +'" title="' + theImage.attr('alt') + '"></a>');
			// style thumbnails
			var OriginalWidth = theImage.width();
			var OriginalHeight = theImage.height();
			if(OriginalWidth / OriginalHeight >= 1.3333) {
				theImage.height(120);
				theImage.width(120/OriginalHeight*OriginalWidth);
				theImage.css({
					'top':'0px',
					'left': (160 - theImage.width()) / 2 + 'px' 
				});
			} else { 
				theImage.width(160);
				theImage.height(160/OriginalWidth*OriginalHeight);
				theImage.css({
//					 'top': ( ( 120 - Height) / 2 )+ 'px',
					 'top': ( ( 120 - theImage.height()) / 2 )+ 'px',
					 'left': '0px'
				});
			}
		});
		
		
		var pLinks = pImages.parent();
		pLinks.wrap('<span class="thwrap"><span class="thcrop"></span></span>');
		
		// Set up image sets
		var setNum = 0;
		$("div.imageset").each(function(){
			// add rel's so that fancybox knows which images are a set
			$(this).find('a.processed').attr('rel', 'imageset' + setNum++);
			// clear bottom of lists
			$(this).append('<div class="clear">&nbsp;</div>');
		});
		
		pLinks.fancybox();
	}
	
		// Homepage Rotator
	if(typeof rotatorNav !== 'undefined' && typeof rotatorSlides !== 'undefined') {	
		var imageWrap = $('#mainpageimagewrap');
		
		// prep html
		// add the sliders to the page
		imageWrap.empty().append(rotatorSlides);
		$('#mainpagelinkwrapabs').after(rotatorNav);

		var thumbs = $('.mpbnfloatwrap').children('.rotatorthumb');
		
		// fix some styling
		$('#mainpagelinkwrapabs').css('z-index', 20);
		
		var imageCache = [];
		var randomNum = Math.floor(Math.random() * imageWrap.children().length);
		
		imageWrap.children().each(function(index){
			/*
			 not working :(
			// strip images from background slides
			imageCache[index] = $(this).find('div.mpicenter').css('background-image');
			
			if(index != randomNum) {
				$(this).css('background-image', 'none');
				$(this).find('div.mpicenter').css('background-image', 'none');
				// load them back in later
				var that = this;
				(function(imageCache, that, index) { 
					setTimeout("$(that).css('background-image', imageCache[index]); $(that).find('div.mpicenter').css('background-image', imageCache[index]);",4000);
				}(imageCache, that, index));		
			}
			*/
			 
			// tie thumbs to slides
			$(this).data('thumb', thumbs[index]);
			
			// enable thumb nav
			// using module pattern
			(function (index) { 
				$(thumbs[index]).click(function(){
					imageWrap.cycle(index);
				});
			}(index));
			
		});
		
		// clicking these will stop the show
		$('#mpthumbprev, #mpthumbnext, .rotatorthumb').click(function(){
			$('#mainpageimagewrap').cycle('pause');
		});
		
		
		// setup the show
		imageWrap.cycle({
			timeout: 8000,
			prev: '#mpthumbprev',
			next: '#mpthumbnext',
			startingSlide: randomNum,
            containerResize: false,
              slideResize: false,
              fit: 1,
			before: function(){
				// fade out all the thumbs
				//$('#mpbnwraprel').children('.rotatorthumb').animate({'opacity': '0.5'}, {duration: 'slow', complete:function(){$(this).css('opacity', '')}});
				//$('#mpbnwraprel').children().removeClass('mpthactive');
				$('.mpbnfloatwrap').children().removeClass('mpthactive');
				// fade in the right thumb
				var thumb = $(this).data('thumb');
				//$(thumb).stop().animate({'opacity': 1}, 'slow');
				$(thumb).addClass('mpthactive');
			}
		});
	}

});




//SHARING / ADD THIS

$(document).ready(function () {
    $('a.stfb').click(function (e) {
        e.preventDefault();
        addthis_sendto('facebook');
    });

    $('a.sttw').click(function (e) {
        e.preventDefault();
        addthis_sendto('twitter');
    });

    $('a.stem').click(function (e) {
        e.preventDefault();
        addthis_sendto('email');
    });

    $('a.sttitle').click(function (e) {
        e.preventDefault();
        addthis_sendto('more');
    });
});


// triggering update of news pages
function triggerUpdateNews() {
    $.get('/UpdateNews.ashx');
}


// move the footer on the main page closer if JS exists
$(document).ready(function() {
	$('.homepageprefooter').css('height', '49px');
});

// scroll to headline anchors
$(function(){ 
	var scrollAnchors = $('.tmcheadlinewrap a');
	if (scrollAnchors.length) {
		scrollAnchors.click(function(){
			var hashPos = this.href.indexOf("#");
			if(hashPos != -1){		
				var hash = this.href.substring(hashPos)
				$('html,body').animate({scrollTop: $(hash).offset().top-40},'slow');
			}
		});
	}
});




// Email Watermarks
$(function(){
	// Define what happens when the textbox comes under focus
	// Remove the watermark class and clear the box
	$("#railfootersignup, #railrtsignup").focus(function() {
		$(this).filter(function() {	
			// We only want this to apply if there's not
			// something actually entered
			return $(this).val() == "" || $(this).val() == "email address"	
		}).removeClass("watermark").val("");	
	});	
	// Define what happens when the textbox loses focus
	// Add the watermark class and default text
	$("#railfootersignup, #railrtsignup").blur(function() {	
		$(this).filter(function() {	
			// We only want this to apply if there's not
			// something actually entered
			return $(this).val() == ""
		}).addClass("watermark").val("email address");	
	});
});


// IMage preloader
function IM_preloadImages() { //Imagemakers version
	if(arguments[0] instanceof Array) {
		return IM_preloadImages.apply(null, arguments[0]);
	}
	var d=document;
	if(d.images){ 
		if(!d.MM_p) {
			d.MM_p=new Array();
		}
		var i,j=d.MM_p.length,a=IM_preloadImages.arguments;
		for(i=0; i<a.length; i++) {
			if (a[i].indexOf("#")!=0){
				d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];
			}
		}
	}
}


// preload images
$(window).load(function() {
IM_preloadImages("/images/template/mainnav/mainlinkbkgdright.jpg","/images/template/mainnav/mainlinkbkgdleft.jpg","/images/template/mainnav/ddlibkgd.png","/images/template/mainnav/ddlibkgd-bottom.png","/images/template/mainnav/ddlibkgdhover.png","/images/template/mainnav/mnplinkbkgd.png","/images/mainpage/mainlink-bkgd-hover.png","/images/buttons/gray-left-sprite.gif","/images/buttons/gray-mid-sprite.gif","/images/buttons/gray-right-sprite.gif","/images/buttons/gray-left-sprite-002.gif","/images/buttons/gray-mid-sprite-002.gif","/images/buttons/gray-right-sprite-002.gif","/products/images/ballastblaster.jpg","/products/images/ballasttamper.jpg","/products/images/generaltools.jpg","/products/images/MOW.jpg","/products/images/railbuckets.jpg","/products/images/railcart.jpg","/products/images/rail-handler.jpg","/products/images/railrider.jpg","/products/images/railworktools.jpg","/products/images/tiehandler.jpg","/products/images/t-railer.jpg","/images/template/other/photo-small-hover.gif","/products/images/hover.png");
});


/*
 * jQuery hashchange event - v1.3 - 7/21/2010
 * http://benalman.com/projects/jquery-hashchange-plugin/
 * 
 * Copyright (c) 2010 "Cowboy" Ben Alman
 * Dual licensed under the MIT and GPL licenses.
 * http://benalman.com/about/license/
 */
(function($,e,b){var c="hashchange",h=document,f,g=$.event.special,i=h.documentMode,d="on"+c in e&&(i===b||i>7);function a(j){j=j||location.href;return"#"+j.replace(/^[^#]*#?(.*)$/,"$1")}$.fn[c]=function(j){return j?this.bind(c,j):this.trigger(c)};$.fn[c].delay=50;g[c]=$.extend(g[c],{setup:function(){if(d){return false}$(f.start)},teardown:function(){if(d){return false}$(f.stop)}});f=(function(){var j={},p,m=a(),k=function(q){return q},l=k,o=k;j.start=function(){p||n()};j.stop=function(){p&&clearTimeout(p);p=b};function n(){var r=a(),q=o(m);if(r!==m){l(m=r,q);$(e).trigger(c)}else{if(q!==m){location.href=location.href.replace(/#.*/,"")+q}}p=setTimeout(n,$.fn[c].delay)}$.browser.msie&&!d&&(function(){var q,r;j.start=function(){if(!q){r=$.fn[c].src;r=r&&r+a();q=$('<iframe tabindex="-1" title="empty"/>').hide().one("load",function(){r||l(a());n()}).attr("src",r||"javascript:0").insertAfter("body")[0].contentWindow;h.onpropertychange=function(){try{if(event.propertyName==="title"){q.document.title=h.title}}catch(s){}}}};j.stop=k;o=function(){return a(q.location.href)};l=function(v,s){var u=q.document,t=$.fn[c].domain;if(v!==s){u.title=h.title;u.open();t&&u.write('<script>document.domain="'+t+'"<\/script>');u.close();q.location.hash=v}}})();return j})()})(jQuery,this);
