/*ASK THE BUILDER CORE JAVASCRIPT FILE
**ORIGINALLY CREATED 8/7/08*/

var ATBCore =
{
	init: function()
	{
		PreloadImages.init();
		//NavBackgroundSwitch.init();
		HoverSwitch.init();
		DropdownNav.init();
		ShowHideNewsletterVid.init();
		CommentAlert.init();
		LinkAroundSummaryImage.init();
	}
};

Event.observe(window, 'load', ATBCore.init);


//PRELOADS IMAGES
var PreloadImages =
{	
	init: function()
	{
		if (document.images)
		{
			var imageList = new Array();
			var offImageSrc = new Array();
			var onImageSrc = [ //manually entered images src's if needed
				"2.0/images/BlueButtonBlockON166x52.png"
			];
			var offStateImageElements = $$('img.hoverSwitch'); //get off-state image objects, i want to load ON states
			if (offStateImageElements.length != 0)//if there are hoverSwitch images, get ON src, add the to array
			{
				for (var i = 0; i < offStateImageElements.length; i++)
				{
					offImageSrc[offImageSrc.length] = offStateImageElements[i].src; //make array of off image sources
					onImageSrc[onImageSrc.length] = offImageSrc[i].replace("Off", "ON"); //make array of ON image sources by replacing 'Off' with 'ON'
				}
			}
			var preloadedImages = new Array(); //initialize array for preloaded images
			for (var j = 0; j < onImageSrc.length; j++) //run throught all ON sources, creating image for each
			{
				preloadedImages[j] = document.createElement('img');
				preloadedImages[j].setAttribute('src',onImageSrc[j]);
			}
		}
	}
};


//CONTOLS BLUE NAV BARS CHANGING BACKGROUND IMAGE
var NavBackgroundSwitch =
{
	init: function()
	{
		if ($$('li.button'))
		{
			var listItemArray = $$('li.button');
			for (var i = 0; i < listItemArray.length; i++)
			{
				Event.observe(listItemArray[i], "mouseover", function(e){
					this.addClassName('hover');
				});
				Event.observe(listItemArray[i], "mouseout", function(e){
					this.removeClassName('hover');
				});
			}	
		}	
	}
};


//	SWITCHES OUT IMAGES BY REPLACINT "Off" with "ON"
var HoverSwitch =
{
	init: function()
	{
		if ($$('img.hoverSwitch')[0])
		{
			var imageToSwitch = $$('img.hoverSwitch'); //sets up event listeners on all elements with 'hoverSwitch' class
			for (var i = 0; i < imageToSwitch.length; i++)
			{
				Event.observe(imageToSwitch[i], "mouseover", HoverSwitch.swapImageOn.bindAsEventListener(imageToSwitch[i]));
				Event.observe(imageToSwitch[i], "mouseout", HoverSwitch.swapImageOff.bindAsEventListener(imageToSwitch[i]));
			}
		}
	},
	swapImageOn: function() //replaces ...off... for ...ON...
	{
		var sourceString = this.src;
		var newSource = sourceString.replace("Off", "ON");
		this.src = newSource;
	}, 
	swapImageOff: function() //replaces ...ON... with ...Off...
	{
		var sourceString = this.src;
		var newSource = sourceString.replace("ON", "Off");
		this.src = newSource;
	}
};



//DROPDOWN MENU COTROL SCRIPT
var DropdownNav = 
{
	init: function() 
	{
		if ($$('li.button'))
		{
			var mainListItemsArray = $$('li.button'); //get li that hold hidden lists
		
			for (var i = 0; i < mainListItemsArray.length; i++) //assign listeners to each li
			{
				Event.observe(mainListItemsArray[i], "mouseover", DropdownNav.showBox);
				Event.observe(mainListItemsArray[i], "mouseout", DropdownNav.hideBox);
			}
		}
	},
	showBox: function()
	{
		if (this.select('div')[0]) //if div exists inside li, show dropdown box
		{
			clearTimeout(this._timer);
			this.addClassName('hover');
			var hiddenDiv = this.select('div')[0];
			hiddenDiv.removeClassName('hiddenList');
		}
	},
	hideBox: function()
	{
		if (this.select('div')[0]) //if div exists inside li, hide dropdown box
		{
			var theItem = this;
			theItem._timer = setTimeout(function()
			{
				theItem.removeClassName('hover');
				var hiddenDiv = theItem.select('div')[0];
				hiddenDiv.addClassName('hiddenList');
			}, 10);
		}
	}
};




//START search button hove script
// copyright 1999-2001 Idocs, Inc. http://www.idocs.com/tags/
// Distribute this script freely, but keep this 
// notice with the code.
var submitRolls = new Object();

function submitroll(src, oversrc, name)
{
this.src=src;
this.oversrc=oversrc;
this.name=name;
this.alt="Search";
this.write=submitroll_write;
}

function submitroll_write()
{
var thisform = 'document.forms[' + (document.forms.length - 1) + ']';
submitRolls[this.name] = new Object();
submitRolls[this.name].over = new Image();
submitRolls[this.name].over.src = this.oversrc;
submitRolls[this.name].out = new Image();
submitRolls[this.name].out.src = this.src;

document.write
	(
	'<A onMouseOver="if (document.images)document.images[\'' + this.name + "'].src=submitRolls['" + this.name + '\'].over.src"' + 
	' onMouseOut="if (document.images)document.images[\'' + this.name + "'].src=submitRolls['" + this.name + '\'].out.src"' + 
	' HREF="javascript:'
	);

if (this.sendfield)
	{
	if (! this.sendvalue)
		this.sendvalue = 1;
	document.write(thisform, ".elements['", this.sendfield, "'].value='", this.sendvalue, "';");
	}

document.write(thisform + '.submit();void(0);"');
if (this.msg)document.write(' onClick="return confirm(\'' , this.msg, '\')"');
document.write('>');

document.write('<IMG SRC="' + this.src + '" ALT="' + this.alt + '" BORDER=0 NAME="' + this.name + '"');
if (this.height)document.write(' HEIGHT=' + this.height);
if (this.width)document.write(' WIDTH='  + this.width);
if (this.otheratts)document.write(' ' + this.otheratts);
document.write('></A>');
if (this.sendfield)
	{
	document.write('<INPUT TYPE=HIDDEN NAME="' + this.sendfield + '">');
	document.forms[document.forms.length - 1].elements[this.sendfield].value='';
	}
}
//End search button hover script



var CommentAlert =
{
	init: function()
	{
		LightBox.init();
	}
};	



//auto creates links around summary images for category and home page article lists
var LinkAroundSummaryImage = //gets links from titles and images from summaries, creates a new links and wrap around images
{
	init: function() {
		if ($('catArticleList')) //if it's a category page run this one
		{
			var identifyText = 'catArticleList';
			LinkAroundSummaryImage.makeLink(identifyText); //pass the id identifier
		}
		else if ($('homeFeatures')) //if it's the homepage run this one
		{
			var identifyText = 'homeFeatures';
			LinkAroundSummaryImage.makeLink(identifyText);//pass the id identifier
		}
	},
	
	makeLink: function(id) {
		var liArray = $(id).select('li'); //get all list items inside div
		var articleLink = ''; //make all variables now so I don't have to repeat in loop
		var summaryImage = '';
		var newLinkElement = '';
		var graphElement = '';
		var firstChildNode = '';
		for (var i = 0; i < liArray.length; i++) //run through all <li>s processing images/links
		{
			if (liArray[i].select('img.summaryImage')[0])
			{
				articleLink = liArray[i].select('a.titleLink')[0].getAttribute('href'); //get link from title
				summaryImage = liArray[i].select('img.summaryImage')[0].remove(); //get image to be linked
				graphElement = liArray[i].select('p')[0]; //get paragraph element
				newLinkElement = document.createElement('a'); //creat new anchor element
				newLinkElement.setAttribute('href', articleLink); //set href attribute of link
				newLinkElement.appendChild(summaryImage); //put image inside new anchor element
				graphElement.insert({before: newLinkElement}); //insert new link/image before paragraph
			}
		}
	}
};


	
//myLightBox 10-14-07

var LightBox = 
{
	counter: 0,
	
	init: function()
	{	
		if (document.getElementsByClassName('lightBox'))
		{
			
			var lightBoxLinkElements = document.getElementsByClassName('lightBox');  //sets click listender to all links of class .lightBox
			for (var i = 0; i < lightBoxLinkElements.length; i++)
			{
				Event.observe(lightBoxLinkElements[i], 'click', LightBox.animate.bindAsEventListener(lightBoxLinkElements[i]));
			}
		}
	},
	
	animate: function(e)
	{
		LightBox.counter++;
		var cookieValue = Cookies.readCookie('commentAlert'); //assign cookie value to variable
		
		if(cookieValue != 'off' && LightBox.counter <= 1)
		{
			var linkId = $w(this.className)[0];  //get first class name of the link clicked, ex: someText, by get string of names, split into array by whitespace, take the first one
			var textId = linkId + 1;  // id of text that matches link, ex: someText1
			var textElement = $(textId);  //get div element by id that matches link, contains the hidden text
			
			var innerContent = textElement.innerHTML;  //get html inside the hidden text, dom node work is too hard
			var displayBox = $("box");  //get lightbox display div
			displayBox.innerHTML = innerContent;  //put html content from hidden div into lightbox div
			
			var inputOffsetValue = $('nameInput').cumulativeOffset();
			var yOffset = inputOffsetValue[1] + 20;
			displayBox.setStyle({
				top:yOffset + "px"
			});
			
			new Effect.Appear('screen', {duration:0.5, from:0.0, to:0.7});
			
			new Effect.Appear('box', {duration:0.5, from:0.0, to:1.0});
			
			var theInput = $('dontShow');
			
			var clickCloseDiv = $('box').select('div.clickClose')[0]; //get div.clickClose
			Event.observe(clickCloseDiv, 'click', function(e){
				if (theInput.checked) //problem with conditional in safari
				{
					Cookies.createCookie("commentAlert", "off", 300);
				}
				new Effect.Fade('box', {duration:0.5, from:1.0, to:0.0});
				new Effect.Fade('screen', {duration:0.5, from:0.7, to:0.0});
				Event.stop(e);
			}, false);
		}
	}
};


var Cookies = 
{
	createCookie: function(name,value,days) 
	{
		if (days) {
			var date = new Date();
			date.setTime(date.getTime()+(days*24*60*60*1000));
			var expires = "; expires="+date.toGMTString();
		}
		else var expires = "";
		document.cookie = name+"="+value+expires+"; path=/";
	},

	readCookie: function(name) 
	{
		var nameEQ = name + "=";
		var ca = document.cookie.split(';');
		for(var i=0;i < ca.length;i++) {
			var c = ca[i];
			while (c.charAt(0)==' ') c = c.substring(1,c.length);
			if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
		}
		return null;
	},

	eraseCookie: function(name) 
	{
		Cookies.createCookie(name,"",-1);
	}

};


/*CREATED JUNE 8 2009
**ROTATES THE VARIOUS NEWSLETTER SIGNUP FORMS TO TEST EFFECTIVENESS*/

var RotateNewsletter =
{
	init: function()
	{
		if ($('newsletterFrame'))
		{
			var srcArray = [  //create array of all possible srcs
				'http://www.askthebuilder.com/newsletterForms/NewsletterHardCode1.html',
				'http://www.askthebuilder.com/newsletterForms/NewsletterHardCode2.html',
				'http://www.askthebuilder.com/newsletterForms/NewsletterHardCode3.html',
				'http://www.askthebuilder.com/newsletterForms/NewsletterHardCode4.html',
				'http://www.askthebuilder.com/newsletterForms/NewsletterHardCode5.html'
			];
			var randomNumber = Math.floor(Math.random()*4)  //generate random number between 0 and 4
			$('newsletterFrame').setAttribute('src', srcArray[randomNumber]);
		}
	}
};


/*Show Hide Newsletter Vid*/
//on page load, newsletter video pitch block "blinds" into view if a visitor hasn't seen it yet.
var ShowHideNewsletterVid =
{
	init: function()
	{
		if ($('homeNews'))
		{
			if (!(Cookies.readCookie('newsletterVid'))) //if no cookie exists
			{
				//new Effect.BlindDown('homeNews'); //show newsletter pitch
				$('homeNews').show();
				Cookies.createCookie('newsletterVid', 1, 365); //create cookie so they only see it once
			}
		}
	}
};

