// Common functions and variables for Home Depot sites

// Tracking HD querystring values (CJ, MMC, etc)
var undefined;		//used for IE 5.5
var Digitas = '';
var cmName = '';
verifySiteName();
verifyAddThis();

var HomeDepot = {};
	HomeDepot.queryParams = location.search.substring(1).toQueryParams();
	HomeDepot.affiliateIds = {};
	HomeDepot.affiliateIds.AID = HomeDepot.queryParams['AID'];
	HomeDepot.affiliateIds.PID = HomeDepot.queryParams['PID'];
	HomeDepot.affiliateIds.SID = HomeDepot.queryParams['SID'];
	HomeDepot.affiliateParams = '';
	HomeDepot.digitas = HomeDepot.queryParams['cm_mmc'];
	HomeDepot.linkParams = buildLinkParamStrings();
	HomeDepot.linkParamsAppended = HomeDepot.linkParams.length > 0 ? '&'+HomeDepot.linkParams.substring(1) : '';


function verifySiteName() {
	if (typeof SiteName == 'undefined') {
		alert('You must define the variable SiteName');
	}
}
function verifyAddThis() {
	if (typeof addthis_pub != 'undefined' && addthis_pub == 'CHANGE ME IF USING ADD THIS') {
		alert('You must update the addthis_pub value.');
	}
}

function buildLinkParamStrings(){
	var params = "";
	// Affiliate params
	if(HomeDepot.affiliateIds.AID){
	 	params += 'AID='+HomeDepot.affiliateIds.AID;
	}
	if(HomeDepot.affiliateIds.PID){
	 	params += params.length > 0 ? '&PID='+HomeDepot.affiliateIds.PID : 'PID='+HomeDepot.affiliateIds.PID;
	}
	if(HomeDepot.affiliateIds.SID){
	 	params += params.length > 0 ? '&SID='+HomeDepot.affiliateIds.SID : 'SID='+HomeDepot.affiliateIds.SID;
	}
	if(params.length > 0){
		params += '&cj=true';
	}
	//Digitas
	if(HomeDepot.digitas){
	 	params += params.length > 0 ? '&cm_mmc='+HomeDepot.digitas : 'cm_mmc='+HomeDepot.digitas;
		var digitasTags = HomeDepot.digitas.replace('THD_Marketing-_-'+SiteName+'-_-','_');
		Digitas = digitasTags.length > 0 ? digitasTags.replace('-_-', '_') : '';
	}

	params = params.length > 0 ? '?'+params : '';
	return params;
}

function buildCM_SP(oldURL) {			//Appends Digitas when needed
	var newURL = '';
	var spLink = oldURL.split('cm_sp=')[1];

	if (spLink != undefined && HomeDepot.digitas) {
		var digitasTags = HomeDepot.digitas.replace('THD_Marketing-_-'+SiteName+'-_-','_');
		var digitasAddOn = digitasTags.length > 0 ? digitasTags.replace('-_-', '_') : '';

		spLink = spLink.split('&')[0];
		newURL = oldURL.replace(spLink, spLink + digitasAddOn);
	}
	else {
		newURL = oldURL;
	}

	return newURL;
}

function buildFlashLink(uri) {		//For use by Flash assets to append HD link params to their clicks
	location.href=(buildCM_SP(uri)+HomeDepot.linkParamsAppended).replace('+&+','+%26+');
}

function appendSessionToMainContentLinks(){
	appendSessionLinksInElement($('container'));
}
function appendSessionLinksInElement(elm){
	var links = $A(elm.getElementsByTagName('a'));
	var areas = $A(elm.getElementsByTagName('area'));
	links.each(function(linkElement){appendSessionToLink(linkElement)});
	areas.each(function(linkElement){appendSessionToLink(linkElement)});
}

function appendSessionToLink(linkElement){		//Appends the linkParams to the element
	if(linkElement.href){
		if(linkElement.href.indexOf('javascript:') == -1){
			linkElement.href = buildCM_SP(linkElement.href);
			var hrefAppendage = linkElement.href.indexOf('?') > -1 ? HomeDepot.linkParamsAppended : HomeDepot.linkParams;
			var adjustedHref = linkElement.href + hrefAppendage;
			linkElement.href = adjustedHref;
		}
	}
}

function rollOn(elem, classid) {		//Changes the class of an element
	elem.className = classid;
}

function swapImage(elem, imgName) {	//Changes the source of an image
	elem.src = imgName;
}

function passJStoFlash(functionName, variableName) {
	flashProxy.call(functionName, variableName);
}

function addToLegal(copy, overwrite) {
	if (overwrite) {
		document.getElementsByClassName("footer-disclaimer",$("container"))[0].innerHTML = copy;
	} else {
		document.getElementsByClassName("footer-disclaimer",$("container"))[0].innerHTML += "<br />" + copy;
	}
}

document.getElementsByClassName = function(classToFind, baseElement) {		//IE 5.5 doesn't have the DOM version of this
    if (arguments.length == 1) {
        baseElement = document;
    } else if (!baseElement) {
        return([]);
    }
    var tempElements = baseElement.getElementsByTagName('*');
    if (!tempElements.length && baseElement.all) tempElements = baseElement.all;
    var matchingElements = [];
    for (var loop=0; loop<tempElements.length; loop++) {
        if ((' ' + tempElements[loop].className + ' ').indexOf(' ' + classToFind + ' ') != -1) {
            matchingElements[matchingElements.length] = tempElements[loop];
        }
    }
    return(matchingElements);
}
//Find your local store functions
function buildLocalStoreFinder(PathToRoot) {		//Builds pod
	var States = new Array("", "AK", "AL", "AR", "AZ", "CA", "CO", "CT", "DC", "DE", "FL", "GA", "HI", "IA", "ID", "IL", "IN", "KS", "KY", "LA", "MA", "ME", "MD", "MI", "MN", "MO", "MS", "MT", "NC", "ND", "NE", "NH", "NJ", "NM", "NV", "NY", "OH", "OK", "OR", "PA", "RI", "SC", "SD", "TN", "TX", "UT", "VA", "VT", "WA", "WI", "WV", "WY");

	var htmlString='';

	htmlString += '<form id="storesearch" onsubmit="javascript:void(findAStore(\'searchby_zip\', \'searchby_city\', \'searchby_state\'));return false;">';
		htmlString += '<input type="text" id="searchby_zip" value="Enter Zip" onfocus="this.value=\'\';" />';
		htmlString += '<input type="text" id="searchby_city" value="Enter City" onfocus="this.value=\'\';" />';
		htmlString += '<select id="searchby_state">';
			for (st=0;st<=States.length-1;st++) {
				htmlString += '<option value="'+ States[st] + '">'+ States[st] + '</option>';
			}
		htmlString += '</select>';
		htmlString += '<input type="image" id="storesearch_submit" class="ss_byzip" src="'+PathToRoot+'images/buttons/btn_arrow.gif" />';
		htmlString += '<a id="searchby" class="sb_byzip" href="javascript:toggleSearchBy(1);">Search by City</a>';
	htmlString += '</form>';

	$('localstore').innerHTML = htmlString;
}

function toggleSearchBy(toggle) {		//Toggles "Search by..."
	if (toggle == 1) {	//switch from zip to city
		$('searchby_city').value = 'Enter City';
		$('searchby_zip').value = '';
		$('searchby_zip').style.display = 'none';
		$('searchby_city').style.display = 'inline';
		$('searchby_state').style.display = 'inline';
		$('storesearch_submit').className = 'ss_bycity';
		$('searchby').className = 'sb_bycity';
		$('searchby').innerHTML = 'Search by Zip Code';
	}
	if (toggle == -1) {	//switch from city to zip
		$('searchby_zip').value = 'Enter Zip';
		$('searchby_city').value = '';
		$('searchby_state').selectedIndex = 0;
		$('searchby_zip').style.display = 'inline';
		$('searchby_city').style.display = 'none';
		$('searchby_state').style.display = 'none';
		$('storesearch_submit').className = 'ss_byzip';
		$('searchby').className = 'sb_byzip';
		$('searchby').innerHTML = 'Search by City';
	}

	$('searchby').href = 'javascript:toggleSearchBy('+ -toggle + ');';
}

function findAStore(zipElement, cityElement, stateElement) {		//Redirects to HD.com if good
	var zip = $(zipElement).value;
	var city = $(cityElement).value;
	var state = $(stateElement).options[$(stateElement).selectedIndex].value;
	var findstore = false;

	if (zip == '') {		//Zip not entered
		if (city == '' && state == '' && $(cityElement).style.display != 'inline') {	//Searching by Zip
			alert('Please enter your zip code');
			findstore = false;
		} else if (city == '' && state == '' && $(cityElement).style.display == 'inline') {		//Searching by city/state
			alert('Please enter a city and state');
			findstore = false;
		}
	} else {		//Zip is entered
		if (!isNaN(zip)) {
			findstore = true;
		} else {
			alert('Please enter a valid zip code');
			findstore = false;
		}
	}

	if (zip == '' && city != '' && state == '') {		//Entered only city
		alert('Please select a state');
		findstore = false;
	}

	if (zip == '' && state != '' && city == '') {		//Entered only state
		alert('Please enter a city');
		findstore = false;
	}

	if (zip == '' && state != '' && city != '') {		//Entered city & state
		findstore = true;
	}

	if (findstore) {
// 		  window.open('http://www.homedepot.com/webapp/wcs/stores/servlet/THDStoreFinder?storeId=10051&URL=StoreFinderView&errorViewName=StoreFinderView&headerStoreFinder=&List=List&catalogId=10053&zip='+ zip + '&distance_1=50&city='+ city + '&state_1='+ state + '&distance_2=50&store=');
		location.href='http://www.homedepot.com/webapp/wcs/stores/servlet/THDStoreFinder?storeId=10051&URL=StoreFinderView&errorViewName=StoreFinderView&headerStoreFinder=&List=List&catalogId=10053&zip='+ zip + '&distance_1=50&city='+ city + '&state_1='+ state + '&distance_2=50&store=';
	} else {
		return false;
	}
}
//Find your local store functions

//Cookie functions
function setCookie(cookieName, cookieValue, cookieLengthDays) {
	if (cookieLengthDays != undefined) {
		var expDate = new Date();
		expDate.setTime(expDate.getTime()+(cookieLengthDays*24*60*60*1000));
		var expires = 'expires='+expDate.toGMTString();
	} else {
		var expires = '';
	}

	document.cookie = cookieName+'='+cookieValue+';'+expires;
}
function getCookie(cookieName) {
	cookieName += '=';
	var cookies = document.cookie.split(';');

	for (var i=0;i<=cookies.length-1;i++) {
		var c = cookies[i];
		while (c.charAt(0) == ' ') { c = c.substring(1,c.length); }
		if (c.indexOf(cookieName) == 0) { return c.substring(cookieName.length, c.length); }
	}
	return null;
}
function clearCookie(cookieName) {
	setCookie(cookieName, '', -1);
}
//Cookie functions

function goToAnchor(anchorname) {		//Needed for Flash to hit anchors
	location.href='#'+anchorname;
}

//Get a parameter from the url
function getQueryParameter(param) {
	var querystring = document.location.search.toLowerCase() || document.location.hash.toLowerCase();
	if(querystring){
		var startIndex = querystring.indexOf(param +"=");
		var endIndex = (querystring.indexOf("&", startIndex) > -1) ? querystring.indexOf("&", startIndex) : querystring.length;
		if (querystring.length > 1 && startIndex > -1) {
			return querystring.substring(querystring.indexOf("=", startIndex)+1, endIndex);
		}
	}
	return '';
}

//Randomly picks a link from an array of possible locations
function randomLink(locations) {
	location.href = locations.random();
}

//onClick tracking for external site linking off www6
function offsiteClickTrack(CM_SP_TAG) {
	return "var s=s_gi('homedepot');s.linkTrackVars='eVar47';s.linkTrackEvents='None';s.eVar47=s.pageName+':"+CM_SP_TAG+"';s.tl(this,'o','Offsite Link Tracking');";
}

function callOmniture_evar47(value, linkDesc) {
	var s=s_gi('homedepot');
	s.linkTrackVars='eVar47';
	s.linkTrackEvents='None';
	s.eVar47=s.pageName+':'+value;
	s.tl(this,'o',linkDesc);
}

function addSProp(propNum, propVal) {
	HomeDepotNav.headerNavContent = HomeDepotNav.headerNavContent.replace('s.pageName=document.title;','s.prop'+propNum+'="'+propVal+'";s.pageName=document.title;');
}

function addPod(podLocation, selector) {
	$(podLocation).innerHTML += Pods[selector]();
}

//Helper function to handle browser DOM differences with XML reading
function getText(node) {
	if (node.text != undefined) {		//IE
		return node.text.replace(/&amp;/g, '&');
	} else if (node.textContent != undefined) {		//FireFox
		return node.textContent.replace(/&amp;/g, '&');
	}
}

//Get the Extra CTAs (Shop All, Learn More) Links  ----\/\/\/
var ExtraCTAList = new Array();
function ExtraCTA(id,linktext,link, icon,tracktag, newwin) {		//used to manage product categories
	this.ID = id;
	this.LinkText = linktext;
	this.URL = link;
	this.Icon = '';
	if (icon != '') {
		this.Icon = '<img src="http://www6.homedepot.com/moxieshared/images/buttons/'+icon+'" alt="&gt;" style="vertical-align:middle;float:left;" />';
	}
	this.TrackTag = '_'+linktext.replace(/\W/gi, '')+((tracktag!=null) ? '_'+tracktag : '');
	this.NewWin = newwin;
}

function getExtraCTALinks() {
	var htmlString = '';
	var xmlpath = (typeof EXTRACTA_XML_LOCATION == 'undefined') ? '../moxieshared/extractas.xml' : EXTRACTA_XML_LOCATION;
	var request = new Ajax.Request(rootPath + xmlpath,{
		method: 'get',
		asynchronous: false
	});

	var XMLresponse = request.transport.responseXML;

	var categories = XMLresponse.getElementsByTagName('extractalink');

	for (var cat=0;cat<categories.length;cat++) {
		var id = categories[cat].getAttribute('id');
		var linktext = categories[cat].getAttribute('linktext');
		var link = categories[cat].getAttribute('url');
		var icon = categories[cat].getAttribute('icon');
		var tracktag = categories[cat].getAttribute('tracktag');
		var newwin = categories[cat].getAttribute('newwin');

		ExtraCTAList.push(new ExtraCTA(id,linktext,link,icon,tracktag,newwin));
	}
}

getShopAllLink = getExtraCTALink;
function getExtraCTALink(linkID) {
	for (sa=0;sa<ExtraCTAList.length;sa++) {
		if (ExtraCTAList[sa].ID == linkID) {
			return ExtraCTAList[sa];
		}
	}
	return new ExtraCTA('','','');	// No matches

}
//Get the Extra CTAs (Shop All, Learn More) Links  ----/\/\/\
